forge
Explore
Log in

Don't you dare go Hollow

πŸ–οΈ name the board roster the same on the way in as on the way out

Browse files at this commit

43bbae8e6619260b173f2e9b8ced183fb13b788fAhmet Kaan GümüşParent: ba1184c
  • fix
    • πŸ–οΈ name the board roster the same on the way in as on the way out
Show full message
fix: πŸ–οΈ name the board roster the same on the way in as on the way out

POST /boards read the invite list from `participant_ids` while the board
response and PATCH /boards/{id} both call it `participants`. Serde ignored
the unknown key, so a client that posted back a board it had just read got
a 201 for a board it was silently alone on β€” no error, no roster, a seat
spent. The create field is now `participants` like the other two; the repo
is pre-customer and the real volume holds zero board rows, so it is a clean
break with no alias and nothing stored to migrate.

Both board request bodies also deny unknown fields now, which makes the
next misspelling a 422 instead of a silent drop. That is deliberate local
deviation: no other REST DTO in this crate does it, and only these two have
already proven what ignoring a key costs.

Board::delete goes through transaction_with_retry. It was a bare query +
check() around a five-statement cascade that writes the stroke rows, the
board row and the creator's board_count; a stroke claim touching the same
board row aborts it, and check() retired that retryable round as a 500. No
statement can legitimately answer "already exists" β€” the DELETEs are
idempotent and the UPDATE is field-scoped β€” so re-sending is sound, and a
forced-abort probe confirmed the aborted round leaves the board, its
strokes and the seat untouched. No statement moved: RETURN stays slot 4.
.claude/kb-sync.shadded+60 -0
@@ -0,0 +1,60 @@
1+#!/usr/bin/env bash
2+# Keep README.md and the Claude SurrealDB kb in sync.
3+# kb-sync.sh session SessionStart: re-ingest kb if README drifted, warn on
4+# src modules missing from README
5+# kb-sync.sh post PostToolUse (Edit|Write): README edited -> re-ingest;
6+# src/*.rs edited -> warn if module missing from README
7+cd "$(dirname "$0")/.." || exit 0
8+SURREAL="$HOME/.surrealdb/surreal"
9+DB="surrealkv://$HOME/.claude/kb/kb.db"
10+kb() { "$SURREAL" sql -e "$DB" --ns claude --db hezarfen_backend --json --hide-welcome --log error; }
11+
12+ingest() {
13+ have=$(echo 'SELECT VALUE sha256 FROM meta:readme;' | kb 2>/dev/null | grep -o '[0-9a-f]\{64\}')
14+ want=$(sha256sum README.md | cut -d' ' -f1)
15+ if [ "$have" != "$want" ]; then
16+ python3 "$HOME/.claude/kb/ingest.py" README.md | kb >/dev/null 2>&1
17+ python3 "$HOME/.claude/kb/ingest-endpoints.py" README.md | kb >/dev/null 2>&1
18+ fi
19+}
20+
21+check() {
22+ # ponytail: substring match on "<name>.rs" anywhere in README β€” a module
23+ # mentioned outside ## Layout also counts; tighten to the section if it lies
24+ missing=""
25+ for f in src/domain/*.rs src/web/*.rs; do
26+ b=$(basename "$f" .rs)
27+ [ "$b" = mod ] && continue
28+ grep -q "$b\.rs" README.md || missing="$missing $b"
29+ done
30+ # Route drift: every utoipa path under a lib.rs nest prefix must appear
31+ # backticked in the README ## Endpoints table.
32+ routes=""
33+ while read -r prefix mod; do
34+ while read -r p; do
35+ full="$prefix$p"; full="${full%/}"
36+ grep -qF "\`$full\`" README.md || routes="$routes $full"
37+ done < <(grep -oP 'path = "\K[^"]*' "src/web/$mod.rs" 2>/dev/null)
38+ done < <(grep -oP '\.nest\("\K[^"]+", web::\w+' src/lib.rs | sed 's/", web::/ /')
39+ msg=""
40+ [ -n "$missing" ] && msg="README.md ## Layout is missing src modules:$missing."
41+ [ -n "$routes" ] && msg="$msg README.md ## Endpoints is missing routes:$routes."
42+ if [ -n "$msg" ]; then
43+ printf '{"hookSpecificOutput":{"hookEventName":"%s","additionalContext":"%s Update README before finishing. kb re-ingest is automatic."}}\n' "$1" "$msg"
44+ fi
45+}
46+
47+case "$1" in
48+ session)
49+ ingest
50+ check SessionStart
51+ ;;
52+ post)
53+ fp=$(jq -r '.tool_input.file_path // empty' 2>/dev/null)
54+ case "$fp" in
55+ */README.md) ingest ;;
56+ */src/*.rs) check PostToolUse ;;
57+ esac
58+ ;;
59+esac
60+exit 0
CLAUDE.mdadded+84 -0
@@ -0,0 +1,84 @@
1+# hezarfen_backend
2+
3+Rust/axum school-management API (auth, roles, exams, notes, messaging,
4+courses, attendance, pomodoro, meals) on SurrealDB v3. Swagger UI at `/swagger`.
5+
6+## Project docs β€” query the knowledge base, do NOT read README.md
7+
8+README.md is 73KB (~18k tokens). Its `##` sections live in an embedded
9+SurrealDB knowledge base. Fetch only what you need:
10+
11+```bash
12+KB() { ~/.surrealdb/surreal sql -e "surrealkv://$HOME/.claude/kb/kb.db" \
13+ --ns claude --db hezarfen_backend --json --hide-welcome --log error; }
14+# list sections
15+echo 'SELECT id, title FROM doc;' | KB
16+# fetch one section body
17+echo 'SELECT body FROM doc:`time-policy`;' | KB
18+# full-text search, best sections first
19+echo "SELECT id, title, search::score(0) AS s FROM doc WHERE body @0@ 'retake' ORDER BY s DESC LIMIT 3;" | KB
20+# routes for ONE resource (auth, users, notes, messages, events, courses,
21+# subjects, sessions, exams, marks, work, pomodoro, attendance, settings, terms)
22+echo 'SELECT routes FROM endpoint:exams;' | KB
23+```
24+
25+Staleness: if `sha256sum README.md` differs from
26+`echo 'SELECT sha256 FROM meta:readme;' | KB`, re-ingest:
27+
28+```bash
29+python3 ~/.claude/kb/ingest.py README.md | KB
30+python3 ~/.claude/kb/ingest-endpoints.py README.md | KB
31+```
32+
33+The project's own SurrealDB (container `hezarfen-surrealdb`, ns/db
34+`hezarfen`) is runtime data β€” never write knowledge-base rows there.
35+
36+## Code map β€” orient here, skip discovery greps
37+
38+Pattern: `src/domain/<x>.rs` = validated newtypes + entity + its own
39+persistence (SurrealValue). `src/web/<x>.rs` = DTOs + axum handlers, one file
40+per resource, routes wired in `lib.rs`.
41+
42+- core: `main`(bootstrap) `lib`(build_router+OpenAPI) `config` `constant`(limits)
43+ `validate` `error` `database`(connect+SCHEMAFULL migration)
44+ `rate_limit`(fixed-window per-IP) `state`
45+- `domain/`: user role session timestamp profile preferences note note_file
46+ message parent_link event attendance registration course course_session
47+ session_attendance enrollment subject term settings work_entry pomodoro
48+ exam exam_attempt exam_question exam_answer exam_result question_image
49+ menu menu_dish dietary_profile meal_booking meal_attendance meal_ledger
50+- `ai/`: QUIC bridge to the out-of-process AI services (backend listens,
51+ services dial in). `protocol`(frames) `server`(AiBridge: listen+dispatch)
52+ `registry`(workers, capability routing) `tls` `error`. Off unless
53+ `AI_QUIC_ADDR` is set. Spec: README `## AI bridge (QUIC)`.
54+- `web/`: `extractor`(CurrentUser/RequireTeacher/Manager/Admin) `dto`(shared
55+ responses) `page`(pagination) `exam_ws`(exam-room WebSocket) + per-resource:
56+ auth users notes messages events courses subjects sessions exams marks work
57+ pomodoro attendance settings terms meals
58+- `tests/`: integration(oneshot+mem db) e2e(real TCP+cookies) rate_limit
59+ pagination persistence ai_bridge(real QUIC + fake AI service)
60+ ai_protocol(hab/1 wire contract; raw byte-level client, imports no protocol
61+ types β€” the only suite that catches a wire-format change)
62+
63+Note: README `## Layout` lags src/ (missing newer domain files); this map +
64+live `ls src/` win on conflict.
65+
66+## Token discipline
67+
68+- Open-ended "where/how does X work" sweeps: use the Explore subagent β€” keep
69+ exploration out of the main context.
70+- Quiet commands: `cargo test --quiet 2>&1 | tail -30`,
71+ `cargo build 2>&1 | tail -15`.
72+
73+## Conventions
74+
75+- No `PUT`. Routes use `GET`/`POST`/`DELETE`/`PATCH` only.
76+- API contract changes move three doc surfaces together: utoipa annotations,
77+ the tag descriptions in `lib.rs`, and `README.md` (intro, route table, and
78+ the relevant section).
79+- Pre-customer, so clean breaks are fine β€” but any validation change needs
80+ its stale-data impact analyzed first: existing rows may already violate the
81+ new rule.
82+- Commits are emoji + conventional type. Vocabulary in use: `feat`, `fix`,
83+ `docs`, `test`, `style`, `chore`. Never `refactor` (unused in this repo's
84+ history). `🎨 style` is reserved for `cargo fmt` commits.
README.mdmodified+7 -1
@@ -860,7 +860,7 @@ window filtering, before paging; negative values are a `400` naming the field.
860860 | POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≀ `max_chatbot_message_len`) β€” send a turn; `202 {message_id, status: "pending"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` β€” nothing is written; `429` + `Retry-After` on the send tier) |
861861 | GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |
862862 | GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β€” or one `error` β€” and close; an already-finished answer replays (see "Chatbot") |
863-| POST | `/boards` | student | `{title, participant_ids?}` β€” open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |
863+| POST | `/boards` | student | `{title, participants?}` β€” open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |
864864 | GET | `/boards` | student | Boards the caller created or was invited to, newest first Β· paged |
865865 | GET | `/boards/{id}` | student | One board β€” a `404`, never a `403`, for anyone not on it |
866866 | GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged |
@@ -2509,6 +2509,12 @@ model β€” no course, no lesson session, no appointment. Any account from
25092509 `student` upwards may open one. **Every participant draws; the creator
25102510 alone clears, locks, closes or deletes.**
25112511
2512+The roster is spelled `participants` everywhere β€” in the `POST` body, in the
2513+`PATCH` body and in every board response β€” so a client may post back a board it
2514+just read. Unlike the rest of this API, the two board request bodies **reject
2515+an unknown key** (`422`) rather than ignoring it: a misspelled roster would
2516+otherwise open a board its author is silently alone on.
2517+
25122518 **No parents, anywhere.** The `parent` role is the school's read-only observer,
25132519 and it has no whiteboard access at all β€” not a view-only tier, none. It is
25142520 refused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named*
history.txtadded+101 -0
@@ -0,0 +1,101 @@
1+#V2
2+DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25;
3+DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25;
4+REMOVE TABLE IF EXISTS endpoint;
5+INSERT INTO endpoint [{"id": "health", "routes": "| GET | `/health` | no | Liveness check |"}, {"id": "root", "routes": "| GET | `/` | no | Same as `/health` |"}, {"id": "time", "routes": "| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |"}, {"id": "limits", "routes": "| GET | `/limits` | no | Every fixed validation bound, grouped by resource \\u2014 see Validation limits |"}, {"id": "swagger", "routes": "| GET | `/swagger` | no | Interactive API docs (Swagger UI) |"}, {"id": "api-docs", "routes": "| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |"}, {"id": "ai", "routes": "| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |"}, {"id": "auth", "routes": "| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken \\u2014 see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |"}, {"id": "users", "routes": "| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` \\u2014 own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) \\u00b7 paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` \\u2014 find users by username/name fragment (pickers); refs only, no contact info \\u00b7 paged |\\n| GET | `/users` | admin | List all users \\u00b7 paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` \\u2014 set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` \\u2014 tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students \\u00b7 paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |"}, {"id": "notes", "routes": "| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes \\u00b7 paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) \\u2014 \\u2264 the school's `max_file_bytes`, \\u2264 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) \\u00b7 paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |"}, {"id": "messages", "routes": "| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` \\u2014 send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` \\u2014 the caller's folder, newest first; `?folder=inbox&read=false&limit=1` \\u2192 `total` is the unread badge \\u00b7 paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` \\u2014 read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** \\u2014 only from the trash (`409` elsewhere); the row vanishes once both sides deleted |"}, {"id": "events", "routes": "| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` \\u2014 `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` \\u2014 mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) \\u00b7 paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` \\u00b7 paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` \\u2014 seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |"}, {"id": "appointments", "routes": "| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` \\u2014 publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, \\u2264 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) \\u2014 a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar \\u2014 future slots only, demoted teachers' slots left out \\u00b7 paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` \\u2014 book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests \\u00b7 paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` \\u2014 call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included \\u2014 they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` \\u2014 counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal \\u2014 this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |"}, {"id": "courses", "routes": "| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` \\u2014 `kind` is `course` (default), `study` (et\\u00fct), or `club` (kul\\u00fcp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) \\u00b7 paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses \\u00b7 paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ \\u2014 **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` \\u2014 assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` \\u2014 enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u00b7 paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` \\u2014 add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` \\u2014 add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` \\u2014 add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) \\u00b7 paged |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` \\u2014 assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, \\u2264 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) \\u00b7 paged |"}, {"id": "subjects", "routes": "| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |"}, {"id": "sessions", "routes": "| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` \\u2014 roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) \\u00b7 paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |"}, {"id": "exams", "routes": "| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist \\u2014 the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` \\u2014 grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) \\u00b7 paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt \\u2014 students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) \\u00b7 paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question \\u2014 the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam \\u2014 copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** \\u2014 copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question \\u2014 text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` \\u2014 autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers \\u22c3 marks), ascending \\u2014 the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first \\u2014 the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** \\u2014 the answer key the caller checks their own sheet against (same review gate) \\u00b7 paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers \\u22c3 marks), ascending \\u2014 only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster \\u00d7 latest attempts \\u00d7 marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |"}, {"id": "bank-questions", "routes": "| GET | `/bank-questions` | teacher | The school-wide question bank \\u2014 `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) \\u00b7 paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist \\u2014 `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question \\u2014 the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |"}, {"id": "homework", "routes": "| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) \\u00b7 paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade \\u2014 the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades \\u2014 file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` \\u2014 hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part \\u2014 **any** content type, \\u2264 `max_file_bytes`, \\u2264 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) \\u2014 the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student \\u00d7 submission/files/grade + computed `late`/`missing`/`unenrolled` \\u2014 a straggler's stale work stays visible (course manager) \\u00b7 paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` \\u2014 grade `done`/`incomplete`/`missing` (+ optional 0\\u2013100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable \\u2014 that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) \\u2014 readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade \\u2014 un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows \\u2014 submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` \\u2014 full, statuses and marks only, never files \\u00b7 paged |"}, {"id": "questions", "routes": "| POST | `/questions` | student | `{title, body}` \\u2014 ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` \\u2014 the pool questions visible to the caller, each with its `solution_count` \\u00b7 paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question \\u2014 publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` \\u2014 offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first \\u2014 a discussion thread \\u00b7 paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` \\u2014 edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |"}, {"id": "marks", "routes": "| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "work", "routes": "| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) \\u00b7 paged |\\n| GET | `/work/{user}` | manager | A staff member's work log \\u00b7 paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` \\u2014 correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |"}, {"id": "pomodoro", "routes": "| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** \\u2014 a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` \\u00b7 paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape \\u00b7 paged; *or a `parent` linked to `{user}` |"}, {"id": "attendance", "routes": "| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "settings", "routes": "| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |"}, {"id": "terms", "routes": "| POST | `/terms` | manager | `{name, starts_at, ends_at}` \\u2014 past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first \\u00b7 paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term \\u2014 `409` while any course still links to it |"}, {"id": "meals", "routes": "| POST | `/meals/menus` | manager | `{date, slot, capacity?}` \\u2014 publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range \\u00b7 paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` \\u2014 the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` \\u2014 add a dish (\\u2264 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` \\u2014 record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` \\u2014 take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first \\u00b7 paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included \\u00b7 paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` \\u2014 mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu \\u00b7 paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day \\u00b7 paged \\u00b7 own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line |"}, {"id": "payments", "routes": "| POST | `/payments/plans` | manager | `{name, installments}` \\u2014 write a fee plan (1\\u201360 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first \\u00b7 paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it \\u2014 its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (\\u2264 200) \\u2014 place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first \\u00b7 paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` \\u2014 record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` \\u2014 hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` \\u2014 undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines \\u2014 charges, payments, refunds, reversals \\u2014 newest first \\u00b7 paged \\u00b7 own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |"}, {"id": "chatbot", "routes": "| POST | `/chatbot/threads` | student | `{title?}` \\u2014 start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first \\u00b7 paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` \\u2014 rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first \\u2014 user and assistant rows alike \\u00b7 paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (\\u2264 `max_chatbot_message_len`) \\u2014 send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` \\u2014 nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` \\u2014 or one `error` \\u2014 and close; an already-finished answer replays (see \\"Chatbot\\") |"}, {"id": "boards", "routes": "| POST | `/boards` | student | `{title, participant_ids?}` \\u2014 open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first \\u00b7 paged |\\n| GET | `/boards/{id}` | student | One board \\u2014 a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first \\u00b7 paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included \\u00b7 `?epoch=` for one epoch \\u00b7 paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) \\u00b7 paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` \\u2014 re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap \\u2014 nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board \\u2014 permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |"}];
6+REMOVE TABLE IF EXISTS doc;
7+REMOVE TABLE IF EXISTS meta;
8+INSERT INTO doc [{"id": "intro", "title": "intro", "body": "# hezarfen_backend\\n\\nNote, attendance, course + weighted exam mark backend. **Rust (edition 2024) Β· axum Β· SurrealDB 3 (server, WebSocket) Β· tokio.**\\n\\nSession-cookie auth with five hierarchical roles (`parent < student < teacher\\n< manager < admin`). A **`parent`** observes and changes nothing: admins tie\\nstudents to a parent account, and the parent reads those students' mark,\\nattendance, pomodoro, and homework reports β€” that's the whole role. Notes are per-user and carry **file attachments** (PDFs, documents,\\n…): blobs live on disk next to the database, metadata in the database, and the\\nper-file size cap is school policy in settings (`max_file_bytes`, default\\n5 MiB). Any two users can **message** each other, mail-style β€” subject +\\nbody into the recipient's inbox, each side filing its own copy through\\narchive/trash with a read flag the sender sees as a receipt (one of the two\\nplaces a `parent` writes β€” whiteboards below are the other). Attendance is event + attendees: create an event with an **audience**\\n(the whole school, one role, a course's enrollment, or a **registration**\\nsignup list β€” omit for school-wide), then teachers mark the expected attendees\\npresent / absent / late / excused (students never self-mark), and a **roster\\nreport** shows who was expected and who missed. Registration lists fill seat\\nby seat: teachers register students (never the other way round), staff\\nregister only themselves, an optional `capacity` caps the seats, and the list\\ncloses the moment the event starts (or, for an event with only an end time β€”\\na pure signup deadline β€” the moment that end passes). Every event stays visible to everyone β€”\\nthe audience is a roster, not a wall. Marks are course-shaped\\n(Google Classroom style): a teacher creates a course β€” kind **`course`** (a\\nregular class), **`study`** (a supervised study session β€” *etΓΌt*), or\\n**`club`** (a student club β€” *kulΓΌp*; same behavior, different label),\\noptionally capped by a `capacity` that refuses new enrolls once the roster is\\nfull β€” lays out its **subjects** (curriculum topics β€”\\nevery exam question must be tagged with one of its course's subjects, so\\nresults can later be read per topic), enrolls students, adds\\nexams inside it, and grades β€” enrolling, sitting exams, roll call, and marks are\\nall student-only, staff never take part. A course is run by whoever created it\\nplus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`):\\nan assigned teacher manages everything inside the course β€” exams, sessions,\\nsubjects, roster, grading β€” but can't delete it or change who else teaches it,\\nand a demotion below `teacher` sweeps their assignments away. Students read a per-course weighted average and\\nan overall average from their mark report β€” each exam weighted by its **kind**\\n(midterms can count double, orals once: weights are set per kind in settings,\\nnot per exam). Exams run **sync** (one\\nfixed window), **async** (start anytime inside the window, with a personal\\ntime budget), or **open** (sit anytime, optionally timed per attempt);\\nstudents *sit* them via attempts β€” retakes metered by a per-exam limit\\n(`0` = unlimited), each sitting keeping its own answers, drawings, and mark\\nso staff can read a student's full attempt history, leaving the exam room\\ngoverned by a teacher-controlled rejoin door. Writing an exam takes a while, so it can be saved as a\\n**draft** β€” invisible to students, unsittable, ungradable β€” and published\\nwhen it's ready. Questions can carry **images**: any question may hold one\\nillustration (a map above the prompt), and each option of a choice question\\nmay be a picture of its own (pick the right city off the map) β€” raster\\nuploads capped by the same `max_file_bytes` policy as note files. Good\\nquestions get reused, so a teacher+ can bank one in a school-wide **question\\nbank** β€” detached templates (with their own images) that any teacher copies\\ninto a fresh exam question across years, editable and deletable only by\\nwhoever saved them. Teachers\\nwatch attendance, per-student remaining time,\\nsittings, walk-outs, no-shows (`absent` once the window closes), submissions,\\nand marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out\\n**homework**: assigned to the whole class or a named subset (the unnamed never\\neven see it), tagged with a course subject, due by a required future `due_at`\\nβ€” students hand in text and/or **files of any type** (same size cap, 10 per\\nsubmission, served back only as forced downloads), editable until the teacher\\ngrades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark\\n(grading freezes the hand-in until the grade is removed); lateness is computed\\nfrom two stamps (first hand-in vs last touch), never stored, and homework\\nmarks stay out of the weighted `/marks` averages. Courses also carry **lesson\\nsessions** with teacher-taken roll call (students never self-mark a lesson),\\nstaff clock in/out on a server-stamped **work log**, students track study time\\nwith a server-stamped **pomodoro log** (the timer runs in the frontend; the\\nbackend records the focus stints, and teachers can read any student's log),\\nand every user has an\\n**attendance report** (event + per-course lesson tallies with rates).\\nA school-wide **question pool** runs on moderation: a student asks a question\\n(optionally attaching one photo of the problem β€” raster only, same\\n`max_file_bytes` cap), a teacher+ **approves** it into the pool (or deletes\\nit β€” rejection is deletion, there is no rejected state), and every approved\\nquestion is readable by the whole school with anyone free to offer\\n**solutions** under it (parents stay out) β€” text plus an optional photo of\\nthe worked steps, both editable by the solution's author anytime; pending\\nquestions show only to their asker and to teacher+, and approval freezes the\\ncontent so nothing unmoderated ever reaches the pool.\\nTeachers keep an **appointment calendar**: a teacher+ publishes availability\\nslots (one-off, or repeating weekly up to an `until` date as a series that\\ndeletes as one), and students and parents book a slot with a reason β€” the\\nbooking lands `pending` until the teacher approves it, rejects it, or\\ncounter-proposes another time (which sends it back to `pending` for the\\nrequester to accept or decline); the **requester** may cancel until the meeting\\nstarts β€” a teacher ends a booking by rejecting it, or by counter-proposing and\\nthen rejecting an approved one β€” one live booking holds a slot, a teacher's own\\npublished windows may not overlap each other, and no approved meeting may\\noverlap another for the teacher or the requester (see \\"Appointments\\").\\nSchool-varying policy is data, not code: exam kinds (each with its weight in\\ncourse averages), attendance statuses, grade-display bands, the note-file\\nsize limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms**\\nare plain rows courses can link to (see \\"Per-school policy\\"). Each account\\nalso carries its own **UI preferences** β€” theme (`light`/`dark`), language\\n(`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` β€”\\nany hex, deliberately not a fixed palette) β€” self-managed, admin-editable for\\nanyone, `null` until chosen so the client can fall back to the device\\npreference (or, for the accent, its own default).\\nThe **AI features live in separate projects**, so the backend also opens a\\nQUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in,\\nregister the capabilities they serve, and each request rides its own QUIC\\nstream on that one connection β€” no correlation ids, no head-of-line blocking.\\nThe bridge's certificate is published at `GET /ai/certificate` so a service can\\npin it before dialling (see \\"AI bridge (QUIC)\\").\\nThe first thing riding that bridge is the **chatbot**: every signed-in user\\n(`parent` included) keeps private threads with an AI service, free-form β€”\\nno rule tables, no canned answers, the backend only owns auth, limits,\\npersistence and the payload format. Sending is asynchronous because an\\ninference outlives a request: the turn plus an empty `pending` answer are\\nwritten *first*, the call goes out after, so a reload never loses an answer;\\nthe client then polls the message or reads it off an SSE stream (see\\n\\"Chatbot\\").\\nAny signed-in account (a `parent` included) can also open a **collaborative\\nwhiteboard**: a titled board whose membership is an **ad-hoc invite list** β€”\\nthe creator names participant user ids, and no course, session or appointment\\nis involved. Every participant draws over a WebSocket, the creator alone\\nclears, locks, closes or deletes, and someone who is not on a board gets a\\n`404` for it on every route, existence included. Strokes are **append-only and\\na clear deletes nothing** β€” it bumps the board's epoch, so the live canvas\\nempties while every mark ever drawn stays stored and replayable through the\\nhistory reads (see \\"Collaborative whiteboard\\").\\nThe school's **food program** is published here too: a manager puts up one\\n**menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot`\\ndrawn from the school's `meal_slots`, unique per pair), lists its **dishes**\\nwith dietary tags from the school's own list, and prices them in **minor\\nunits** (kuruş) as integers β€” this API never speaks decimals or floats about\\nmoney. A student's own **dietary profile** is tagged from that same list\\n(manager-written β€” an allergen list is a school record, not a self-service\\npreference), so every dish a menu read returns names the tags it `conflicts`\\nwith for whoever is reading. Every authenticated user reads what is being\\nserved; students (or their parents) book a seat, and every seat writes a line into an\\n**append-only** meal ledger whose balance is derived and never stored (see\\n\\"Food program: menus, dishes, bookings & the ledger\\").\\nSchool **fees** are tracked the same way, in a ledger of their own: a manager\\nwrites a **fee plan** (a name and 1–60 installments, each an amount in minor\\nunits and a due date that may sit in the past) and **assigns** it to students,\\nwhich appends every installment as a `charge` at once β€” there is no scheduler,\\nand \\"overdue\\" is derived at read time. Payments are recorded against one named\\ncharge, refunds against one named payment, and nothing is ever edited or\\ndeleted: a mistake is corrected by appending the opposing line. **There is no\\nonline payment integration and none is planned** β€” no gateway, no card data,\\n`method` is free text. Teachers see no money at all (see \\"Payments\\").\\n\\nEvery field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)\\nconstructed only after its restrictions pass β€” invalid input can't be\\nrepresented. Those restrictions are published rather than left to be guessed:\\n**`GET /limits`** (no auth) serves every fixed bound and closed value set the\\nAPI enforces, read straight from the constants the newtypes use, so a frontend\\nvalidates against the server's own rules instead of a hand-kept copy (see\\n\\"Validation limits\\"). Those same types derive `surrealdb::types::SurrealValue`, so one\\ntyped value flows from HTTP request into the `SCHEMAFULL` database. Record ids\\nare ULIDs (time-sortable).", "source": "README.md"}, {"id": "run", "title": "Run", "body": "```sh\\nsurreal start --user root --pass root surrealkv:./data/hezarfen.db # the DB server\\ncp .env.example .env # optional\\ncargo run\\n```\\n\\nBoots on `http://127.0.0.1:8080`, talking to the SurrealDB server at\\n`DB_URL` (default `ws://127.0.0.1:8000`, root credentials via\\n`DB_USER`/`DB_PASS`) and storing uploaded note files in\\n`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs\\n(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at\\n`/api-docs/openapi.json`.", "source": "README.md"}, {"id": "run-in-a-container-podman", "title": "Run in a container (podman)", "body": "```sh\\npodman compose up -d --build # build + start, http://127.0.0.1:8080\\npodman compose logs -f backend\\npodman compose down # stop (data survives in the volume)\\n```\\n\\nThe `Containerfile` is a two-stage build (Rust builder with cargo cache\\nmounts, `debian:trixie-slim` runtime, non-root user). Two services: the\\n`surrealdb` server (official image, surrealkv storage) and the backend, which\\nwaits for the server's healthcheck and connects over `ws://surrealdb:8000`.\\nEach has its own named volume β€” `surreal-data` holds the database,\\n`hezarfen-data` the uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the\\ncontainer so the published port works. Production knobs (`COOKIE_SECURE`,\\n`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in\\n`compose.yaml` β€” uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset\\nmeans dev mirror mode without credentials; a cookie-using browser frontend\\nmust be allowlisted explicitly. Works with `docker compose` too.\\n\\nThe backend survives the database going away, at boot and at runtime.\\n\\nAt boot it retries the connection (1s doubling to 5s) until the server\\nanswers, rather than exiting. Exiting looks tidier but is worse: the container\\nruntime restarts the process, it fails again in milliseconds, and a few\\nseconds of startup skew burns the whole restart budget and leaves the backend\\ndown for good.\\n\\nAt runtime a keepalive query every 5s doubles as a liveness probe. This\\nmatters more than it sounds: a query issued while the socket is down does\\n*not* fail β€” the SDK's reconnect loop stops draining its request queue, so the\\nquery parks until the database returns and only *then* runs. Left alone, a\\nrequest waits out the entire outage and any write it carries lands long after\\nthe caller gave up.\\n\\nSo while the probe says the socket is down, requests are refused at the edge\\nwith `503` and `Retry-After: 1`, before they can reach the database. Nothing\\nis queued, which is what makes that retry safe. Requests that slip through in\\nthe window between the socket dying and the probe noticing are capped at 30s\\nand answer `503` *without* `Retry-After`, with a message saying the write may\\nor may not have applied β€” they were already queued, so retrying them could\\napply the same write twice. WebSocket and SSE routes are unaffected: both\\nreturn their response immediately and stream afterwards.\\n\\nWithout compose:\\n\\n```sh\\npodman build -t hezarfen-backend .\\npodman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backend\\n```", "source": "README.md"}, {"id": "auth-model", "title": "Auth model", "body": "Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, stored\\nserver-side). Send it back on later requests. Every endpoint below whose `Auth`\\ncolumn names a role requires a valid session; the ones marked `no` (`/health`,\\nthe docs pages, `register` / `login` / `logout`) don't (`logout` is idempotent β€”\\nit clears the session if one is present). Set `COOKIE_SECURE=true` when serving\\nbehind TLS to add the cookie's `Secure` attribute.\\n\\n**Register never reveals whether a username is taken.** `POST /auth/register`\\nanswers `201` either way with the *same* body β€” `{username, role}`, the echoed\\nname and the `student` role every fresh account gets. Both outcomes return one\\nvalue built before the insert is even attempted, so they are byte-identical by\\nconstruction. This is deliberate: the route is unauthenticated, so a `409` (or a\\nfaster reply) would let anyone enumerate the school's users. The password is\\nhashed *before* the availability check so both outcomes cost the same ~33ms.\\n\\nThe reply carries **no `id`**: on the taken path there is no row to name, and a\\nfabricated one would leave the client holding an id that matches nothing. Log\\nin and read `GET /auth/me` to learn who you are. The accepted cost: a caller who\\ncollides with an existing account gets no distinct error and simply cannot log\\nin with that password β€” they pick another name. Do not \\"fix\\" this back to a\\n`409`, and do not add an `id` back.", "source": "README.md"}, {"id": "time-policy", "title": "Time policy", "body": "Timezones and clock differences cannot corrupt data, by construction:\\n\\n- **Every instant is a UTC unix-millisecond `i64`** (`domain::timestamp::Timestamp`),\\n stored as an `int`, sent as a plain number. Nothing stores or parses a\\n timezone, so the server's `TZ`, the container's clock config, and the\\n client's locale are all irrelevant β€” clients convert millis to local time\\n for display only.\\n- **One clock choke point.** `Timestamp::now()` is the only wall-clock read.\\n `clippy.toml` bans every other source (`chrono::Local`/`Utc::now`,\\n `SystemTime::now`, `time::OffsetDateTime::now_*`, absolute cookie\\n `Expires`) and `[lints.clippy]` raises that to a hard `cargo clippy` error,\\n so local-time bugs can't be reintroduced.\\n- **Expiry is server-authoritative.** Sessions expire by comparing the stored\\n millis against the server clock; the cookie carries a relative `Max-Age`\\n (never an absolute `Expires`), so a wrong client clock changes nothing.\\n- **Pacing uses the monotonic clock.** The rate limiter runs on `Instant`,\\n immune to NTP steps and wall-clock jumps.\\n- **Calendar dates get a timezone grace.** A birth date is a calendar date on\\n the writer's wall, not an instant: validation accepts up to UTC-tomorrow,\\n since a client ahead of UTC (up to UTC+14) legitimately writes a date the\\n server's UTC calendar hasn't reached yet.\\n- **Times-of-day are UTC too, and staff enter them that way.** A meal slot's\\n `serving_minute` (minutes past midnight, `0`–`1439`) is the one clock-face\\n value a school types in, and it is read as UTC on the menu's `date` β€” there\\n is deliberately **no school-timezone setting** (a rejected feature), so a\\n UTC+3 school enters `540` (09:00 UTC) for a meal served at noon locally.\\n- **Nothing schedules in the past.** A request-supplied schedule instant β€” an\\n exam window, a lesson's `starts_at`/`ends_at`, an event time β€” must not lie\\n before the server's now, on create and on every `PATCH` that sets it: a\\n deadline that starts in the past is dead on arrival, so it's a `400`. A\\n 60-second grace absorbs request latency and client-clock skew (\\"starts now\\"\\n survives its own round trip). Values a `PATCH` merely keeps are exempt β€” a\\n running exam's `starts_at` is legitimately past, and a rename or deadline\\n extension must not trip over it. (Work-log corrections are records of past\\n work, not schedules, and stay free.)\\n- **Frontends can sync to the server clock.** `GET /time` (no auth) returns\\n `{\\"now\\": <UTC unix-millis>}`. Fetch once, keep\\n `offset = now - Date.now()`, and use `Date.now() + offset` for countdowns\\n and past/future checks instead of trusting the device clock.\\n\\nKeep the single server's clock NTP-synced; that's the only clock that matters.", "source": "README.md"}, {"id": "validation-limits", "title": "Validation limits", "body": "Every fixed bound the API enforces is published at `GET /limits` (no auth), so\\na client never has to hard-code a copy that drifts the day a constant moves.\\nThe handler reads `src/constant.rs` directly β€” a changed constant changes the\\nresponse in the same commit.\\n\\n```json\\n{\\n \\"user\\": { \\"min_username_len\\": 3, \\"max_username_len\\": 32,\\n \\"username_separators\\": [\\".\\", \\"_\\", \\"-\\"],\\n \\"reserved_usernames\\": [\\"admin\\", \\"…\\"],\\n \\"min_password_len\\": 6, \\"max_password_len\\": 128,\\n \\"max_name_len\\": 100, \\"max_email_len\\": 254,\\n \\"min_phone_digits\\": 7, \\"max_phone_digits\\": 15,\\n \\"roles\\": [\\"parent\\", \\"student\\", \\"teacher\\", \\"manager\\", \\"admin\\"],\\n \\"themes\\": [\\"light\\", \\"dark\\"], \\"languages\\": [\\"tr\\", \\"en\\"],\\n \\"palette_color_pattern\\": \\"^#[0-9a-fA-F]{6}$\\", \\"palette_color_len\\": 7,\\n \\"session_duration_days\\": 7 },\\n \\"note\\": { \\"max_title_len\\": 200, \\"max_content_len\\": 10000, \\"max_files\\": 10 },\\n \\"file\\": { \\"max_name_len\\": 255, \\"max_content_type_len\\": 100,\\n \\"min_max_file_bytes\\": 1024, \\"max_max_file_bytes\\": 26214400,\\n \\"default_max_file_bytes\\": 5242880,\\n \\"image_content_types\\": [\\"image/png\\", \\"image/jpeg\\", \\"image/webp\\", \\"image/gif\\"] },\\n \\"message\\": { \\"max_subject_len\\": 200, \\"max_body_len\\": 10000, \\"max_label_len\\": 50 },\\n \\"event\\": { \\"max_title_len\\": 200, \\"max_description_len\\": 2000 },\\n \\"course\\": { \\"kinds\\": [\\"course\\", \\"study\\", \\"club\\"], \\"max_title_len\\": 200, \\"…\\": 0 },\\n \\"exam\\": { \\"modes\\": [\\"sync\\", \\"async\\", \\"open\\"],\\n \\"question_kinds\\": [\\"choice\\", \\"text\\"],\\n \\"min_duration_ms\\": 60000, \\"max_duration_ms\\": 86400000,\\n \\"max_attempts\\": 100, \\"unlimited_attempts\\": 0,\\n \\"min_mark\\": 0, \\"max_mark\\": 100, \\"…\\": 0 },\\n \\"homework\\": { \\"statuses\\": [\\"done\\", \\"incomplete\\", \\"missing\\"],\\n \\"max_files_per_submission\\": 10, \\"max_assigned\\": 200, \\"…\\": 0 },\\n \\"question_pool\\": { \\"max_title_len\\": 200, \\"max_body_len\\": 10000, \\"max_solution_body_len\\": 10000 },\\n \\"appointment\\": { \\"max_note_len\\": 500, \\"max_reason_len\\": 1000, \\"max_slot_occurrences\\": 52 },\\n \\"chatbot\\": { \\"max_message_len\\": 8000, \\"max_thread_title_len\\": 200,\\n \\"min_max_message_len\\": 100, \\"…\\": 0 },\\n \\"board\\": { \\"max_title_len\\": 200, \\"max_participants\\": 50,\\n \\"max_stroke_payload_len\\": 4096,\\n \\"max_epoch_strokes\\": 5000, \\"max_board_strokes\\": 50000,\\n \\"max_boards_per_creator\\": 200,\\n \\"stroke_kinds\\": [\\"stroke\\", \\"clear\\"],\\n \\"ws_tick_secs\\": 15, \\"ws_max_board_id_len\\": 64 },\\n \\"settings\\": { \\"max_list_len\\": 20, \\"max_item_len\\": 50,\\n \\"min_exam_kind_weight\\": 1, \\"max_exam_kind_weight\\": 100,\\n \\"max_grade_bands\\": 20, \\"max_grade_label_len\\": 20,\\n \\"required_attendance_statuses\\": [\\"present\\", \\"absent\\", \\"late\\", \\"excused\\"] },\\n \\"request\\": { \\"max_page_limit\\": 500, \\"schedule_past_grace_ms\\": 60000,\\n \\"request_timeout_secs\\": 30 },\\n \\"rate\\": { \\"window_secs\\": 60, \\"auth_per_minute\\": 10,\\n \\"api_per_minute\\": 300, \\"chatbot_per_minute\\": 20 }\\n}\\n```\\n\\nThe `rate` group is the one part that is **not** compile-time: those tiers are\\nenvironment-tunable, so the endpoint serves *this* server's live values (read\\nfrom its running limiters), not the shipped defaults. `0` means the tier is\\noff. A client should read its budget here rather than discovering it by\\ncollecting a `429`.\\n\\n### Two surfaces, one source\\n\\nThe bounds are published twice, on purpose, because clients consume them two\\ndifferent ways:\\n\\n| Surface | Shape | Use it when |\\n|---------|-------|-------------|\\n| `GET /limits` | One JSON document, grouped by resource, closed value sets included | Runtime fetch. No codegen step, survives a deploy skew, and carries things OpenAPI holds awkwardly (`reserved_usernames`, `image_content_types`) |\\n| `/api-docs/openapi.json` | Per-field `maxLength` / `minLength` / `minimum` / `maximum` / `maxItems` on the request schemas | Build-time codegen β€” `openapi-typescript`, `orval`, and friends turn these into types *and* validators automatically |\\n\\nBoth are generated from the same `src/constant.rs`, and **neither is allowed to\\ndrift from it**, which is enforced rather than asked for:\\n\\n- `tests/limits_completeness.rs` parses every `pub const` out of `constant.rs`\\n and fails unless each one is either referenced by `src/web/limits.rs` or\\n listed as a deliberate exclusion *with a reason*. A new constant breaks the\\n suite until someone decides, consciously, whether clients need it.\\n- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 161 published\\n bounds back out of the emitted JSON, and asserts each equals its constant.\\n This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal\\n only** β€” a `const` there does not compile β€” so the annotations are\\n unavoidably a second copy of each number. The test is what makes that copy\\n safe. It also pins the `limit` query parameter's `maximum` to\\n `MAX_PAGE_LIMIT`, a duplication `constant.rs` previously only *asked* a human\\n to maintain.\\n- A third check in `limits_completeness.rs` refuses to let a validation bound\\n be declared **outside** `constant.rs` at all. Without it a limit can hide in\\n a domain module and reach neither surface β€” which is exactly where\\n `MAX_CHATBOT_THREAD_TITLE_LEN` was found sitting, private and unpublished.\\n\\nNotes:\\n\\n- **No auth.** The registration and login forms need the username and password\\n bounds before a session exists, and none of these are secrets β€” they are the\\n same rules a `400` already spells out in prose.\\n- **Answers during a database outage.** `/limits` touches no row, so it is\\n exempt from the guard that answers `503` while the database reconnects β€” a\\n frontend booting against a degraded backend is exactly when it needs the\\n contract. Every route that does read the database still refuses.\\n- **Fetch once.** The values are compile-time constants, so the response only\\n changes with a deploy. Cache it for the session; the `ETag`/`304` path makes\\n a revalidation cheap if you'd rather re-check.\\n- **`/limits` is not `/settings`.** School-adjustable policy β€” the exam kinds\\n and their weights, the attendance statuses, the grade bands, the live\\n `max_file_bytes` and chatbot knobs β€” is on `GET /settings` and changes when a\\n manager edits it. What `/limits` carries for those knobs is the fixed range a\\n manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the\\n attendance statuses no school may remove.\\n- **Open sets travel as a pattern.** `palette_color` accepts any hex accent\\n color, so `/limits` publishes `palette_color_pattern` (a regular expression)\\n and `palette_color_len` instead of a value list β€” validate the shape, not\\n membership in a palette. The pattern describes what the server *accepts*, so\\n it matches either case; the stored (and returned) value is lowercased, which\\n is the one place a response may differ in case from the request.\\n- **Closed value sets ride along.** `roles`, `themes`, `languages`, course\\n `kinds`, exam `modes`, `question_kinds`, homework `statuses`, board\\n `stroke_kinds`, and the\\n uploadable `image_content_types` are the exact accepted spellings β€” build\\n pickers from these rather than from a literal list.", "source": "README.md"}, {"id": "rate-limiting", "title": "Rate limiting", "body": "Requests are limited per client IP over a fixed 60-second window, in two tiers:\\n`/auth/login` + `/auth/register` get a strict budget\\n(`RATE_LIMIT_AUTH_PER_MINUTE`, default 10) against credential brute-force,\\nand every route β€” Swagger included β€” shares a generous catch-all\\n(`RATE_LIMIT_API_PER_MINUTE`, default 300). Exceeding either answers `429` with\\na `Retry-After` header (seconds). Set a limit to `0` to disable that tier β€”\\nuseful for load tests.\\n\\nSending a chatbot message adds a third tier, and it is keyed by **user id**,\\nnot by IP (`RATE_LIMIT_CHATBOT_PER_MINUTE`, default 20), because an inference\\ncosts the school real money and a shared-IP classroom must not spend one\\nstudent's budget on another's. `0` disables it like the other two. It is\\ncharged before anything is written, so a `429` leaves no trace (see\\n\\"Chatbot\\").\\n\\nAll three tiers admit from memory β€” no request ever waits on the database to be\\nlet in β€” but the window **outlives the process**. A background task folds each\\ntier's new admits into one shared `rate_limit` row per tier + client + minute\\nevery 2 seconds, then caps the in-memory bucket by the total that comes back,\\nso a restart mid-minute does not hand every client a fresh budget. One caveat:\\na just-started process can spend up to the tier's budget in the 2 seconds\\nbefore its first fold tightens it. If the database is down the tiers simply\\nfall back to their own local budgets β€” nobody is refused for it.\\n\\nBehind a reverse proxy every connection carries the proxy's address, so also\\nset `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry\\n(the one the proxy itself appends). Leave it off when clients reach the server\\ndirectly β€” the header is client-forged in that case.", "source": "README.md"}, {"id": "cors", "title": "CORS", "body": "Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin`\\n(browsers refuse it on credentialed requests), so origins listed in the\\ncomma-separated `CORS_ALLOWED_ORIGINS` allowlist are echoed back with\\n`Access-Control-Allow-Credentials: true`. When the allowlist is unset the\\nserver reflects the request's `Origin` β€” dev-friendly β€” but **without**\\ncredentials: mirroring with credentials would let any website ride a\\nvisitor's session cookie. A browser frontend that needs the session cookie\\ncross-origin must therefore be allowlisted explicitly.", "source": "README.md"}, {"id": "roles-access-control", "title": "Roles & access control", "body": "Every user has one of five roles, ranked lowest to highest:\\n\\n```\\nparent < student < teacher < manager < admin\\n```\\n\\nThe check is **hierarchical** β€” a higher role satisfies any lower requirement\\n(an admin can do anything a teacher can). New accounts always register as\\n`student`; a role read is re-checked on every request, so a role change takes\\neffect on the user's very next call (no re-login).\\n\\n`parent` is the read-only observer at the bottom of the ladder: an admin ties\\nany number of students to a parent account (`POST /users/{id}/students`), and\\nthe tie is the parent's whole power β€” they list their students\\n(`GET /users/me/students`) and read each one's mark, attendance, pomodoro,\\nand homework reports in full. Student-only checks are exact (`role == student`), so a\\nparent can never enroll, sit an exam, be graded, or land on a roll call; and\\nsitting below every staff bar, they can't touch anything else either β€” except\\nmessages, which any role sends and receives (that's how a parent reaches a\\nteacher). A role\\nchange off either end of a tie (the parent stops being a `parent`, the\\nstudent stops being a `student`) drops the tie, exactly like promotion drops\\ncourse enrollments.\\n\\n| Action | Minimum role | Notes |\\n|------------------------------------------|--------------|-----------------------------------------------|\\n| Register / login / view own account | (any) | Registration always creates a `student` |\\n| View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves |\\n| Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included β€” the role's one write); each party only ever touches their own copy |\\n| Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark β€” a teacher+ may mark anyone expected, themselves included |\\n| Create events | teacher | The audience (school / role / course / registration) is set at creation and editable later |\\n| Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** β€” never for another staff member. Unregistering mirrors the same rule |\\n| List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report |\\n| Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |\\n| View a course's sessions | student | Only inside **visible** courses: enrolled, creator, assigned teacher, or `manager`+ |\\n| List a session's roll call | teacher | The **session's teacher**, or anyone with course-management rights |\\n| Create / edit / delete a course session | teacher | Course-management rights (course creator, an assigned teacher, or `manager`+) |\\n| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights; only students sit on a roster |\\n| Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call β€” the teacher can't self-mark |\\n| Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied |\\n| View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries |\\n| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session |\\n| View **any** user's pomodoro log | teacher | Study oversight β€” same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' |\\n| Ask into the school question pool | student | **Students only** (exact); born `pending` β€” visible to the asker + teacher+ only; the asker may attach/replace/remove one photo while pending |\\n| Read the pool; offer / edit / withdraw own solutions | student | Every `approved` question is school-wide (parents stay out); a solution's author edits its body and photo anytime (solutions never freeze) and deletes it, teacher+ delete any |\\n| Approve a pending pool question; delete any question or solution | teacher | Approval publishes school-wide and **freezes** the content; rejection = deletion β€” moderation never edits, so teacher+ cannot rewrite a solution |\\n| Read the school **question bank**; save / instantiate bank questions | teacher | Every bank row is school-wide (reads + copy into an exam); saving one makes the caller its owner |\\n| Edit / delete a bank question (and its images) | teacher | **Owner only** (admin bypass); bank rows carry no exam link, so they never freeze |\\n| Read **own** attendance report | student | |\\n| Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created + assigned; `manager`+: all); exam **drafts** show only to the course's managers |\\n| Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** β€” staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |\\n| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |\\n| Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |\\n| Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights β€” one teacher can't read another's answer key |\\n| Watch an exam's live monitor (poll the snapshot) | teacher | Course-management rights |\\n| Create courses | teacher | The creator manages the course, and owns it for good |\\n| Assign / unassign a course's teachers | manager | Staffing is the office's call β€” a course's own creator cannot hand rights to peers; the assignee must be `teacher`+ |\\n| Delete a course | teacher | Only the **creator**, or a `manager`+ β€” an assigned teacher runs the course but doesn't own it |\\n| Manage inside a course: edit it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | The **course creator**, a teacher **assigned** to it, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions or homework won't delete (`409`) |\\n| View a course's roster, an exam's result list / statistics | teacher | Course-management rights |\\n| Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself |\\n| Assign / edit / delete homework; grade it; read its roster | teacher | Course-management rights; an `assigned` subset (≀ 200 enrolled students) can't be narrowed over existing work (`409`); a grade (`done`/`incomplete`/`missing` + optional mark) freezes the submission until removed |\\n| Submit **own** homework (text + files); read own submission and grade | student | **Students only** β€” staff never submit; enrolled + in the audience; editable until graded; ≀ 10 files of any type, each ≀ `max_file_bytes`, always downloaded as attachments |\\n| Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full β€” statuses/marks/flags, never files |\\n| Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields |\\n| Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen β€” the client then follows the device preference |\\n| List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports β€” a parent changes nothing, anywhere |\\n| Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |\\n| Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call |\\n| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role |\\n\\n### Bootstrapping the first admin\\n\\nThere is no self-service path to `admin` β€” registration always creates a\\n`student`. The first admin comes from the startup seed: set both\\n\\n```sh\\nADMIN_USERNAME=admin\\nADMIN_PASSWORD=admin123 # local-dev default used by compose.yaml; change it\\n```\\n\\nand on boot the account is created with the `admin` role **if the username\\ndoesn't exist yet**. The seed is idempotent and deliberately conservative: it\\nnever promotes or rewrites an existing account (if the name is taken by a\\nnon-admin it logs a warning and leaves it alone β€” promoting someone else's\\naccount would be an escalation). Setting only one of the two variables aborts\\nstartup. `compose.yaml` ships with the credentials above for local dev.\\n\\nThat admin can then promote everyone else through `PATCH /users/{id}/role`.\\n\\nManual fallback (also the recovery path if the seeded name was squatted or the\\nsole admin locked themselves out): run\\n\\n```surql\\nUPDATE user SET role = 'admin' WHERE username = 'ada';\\n```\\n\\nagainst the SurrealDB server β€” e.g.\\n`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db hezarfen`\\n(in the container setup, `podman exec -it hezarfen-surrealdb /surreal sql ...`).", "source": "README.md"}, {"id": "endpoints", "title": "Endpoints", "body": "`Auth` is the minimum role; `no` means no session required, `student` means any\\nlogged-in user.\\n\\nA course is a regular class (kind `course`, the default), an *etΓΌt* (kind\\n`study` β€” a supervised study session), or a *kulΓΌp* (kind `club` β€” a student\\nclub). The three kinds behave identically everywhere β€” enrollment, exams,\\nsessions, marks β€” the kind is a label the UI renders differently, settable at\\ncreation and editable later. A course may also carry a `capacity`: once the\\nroster reaches it, new enrolls are refused with `409` (members already on the\\nroster are unaffected, even if the cap is later lowered below them; `null`\\nlifts the cap).\\n\\n**Who runs a course.** Its **creator** owns it for good β€” only they (or a\\nmanager+) may delete it. On top of that, a manager can **assign** any\\n`teacher`+ to the course with `POST /courses/{id}/teachers` (`{user_id}`,\\nidempotent) and drop them again with `DELETE /courses/{id}/teachers/{user}`.\\nAn assigned teacher gets full **course-management rights** β€” edit the course,\\nenroll and unenroll students, add exams, sessions and subjects, grade, take\\nroll call β€” but *not* the two owner powers: they cannot delete the course, and\\nthey cannot change who else teaches it. Staffing is deliberately the office's\\ncall, so a course's own creator cannot hand rights to their peers; only\\nmanager+ may touch the list. Every course response carries its `teachers`\\narray alongside `creator`, and a user demoted below `teacher` is swept off\\nevery course they were assigned to (the mirror of promotion dropping\\nenrollments).\\n\\nCourse data is walled per course. A course, its exams, its sessions, and its\\nsubjects are\\n**visible** only to its enrolled users, its creator, its assigned teachers,\\nand manager+ β€” a student\\nsees just the classes they were added to, and the `/courses` / `/exams`\\ncatalogs are filtered accordingly. Teacher-level reads *inside* a course\\n(roster, results, statistics, the question list, answer sheets, the live\\nmonitor) additionally need **course-management rights** (creator, an assigned\\nteacher, or manager+):\\none teacher cannot look into another teacher's course, and the per-user\\nmarks/attendance reports narrow to the courses the caller manages.\\n\\n**Paging.** Every list endpoint below (the rows tagged **Β· paged**) accepts\\n`?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope\\nrather than a bare array. `total` is the full row count *before* the window, so\\na frontend can show \\"100 of 256\\" and page with `offset`. Paging is **opt-in**:\\nomit `limit` and you get every remaining row (the echoed `limit` is then\\n`null`), so a caller that sends no parameters still receives the whole list β€”\\nnothing silently truncates. `limit` must be `1`–`500`, `offset` defaults to `0`\\nand must be β‰₯ 0 (bad values are `400`), and an `offset` at or past the end\\nreturns an empty `items` (not an error). Deliberately **not** paged β€” these keep\\ntheir existing shapes: the student exam-room reads\\n`/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and\\n`/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`.\\n\\n**Schedule window (`GET /events`, `GET /exams`).** Both lists additionally\\naccept `?starts_after=` and `?ends_after=`, UTC unix-millis, both optional and\\nindependent (AND-ed when both are sent). `ends_after=T` keeps rows whose window\\nhas not finished β€” `ends_at > T`, falling back to `starts_at > T` when `ends_at`\\nis `null`; `starts_after=T` keeps rows with `starts_at > T`. A row with no\\nschedule at all (an event without times, an exam with no `mode` or in `open`\\nmode) is excluded by either parameter. Supplying either one flips the order to\\n**ascending by schedule** (`starts_at`, falling back to `ends_at`; ties by id),\\nso `?ends_after=<now>&limit=20` gives the twenty *soonest* rows instead of the\\ntwenty newest-created β€” with neither parameter the list is byte-for-byte the\\nnewest-first list it always was. `total` is the count after visibility *and*\\nwindow filtering, before paging; negative values are a `400` naming the field.\\n\\n| Method | Path | Auth | Description |\\n|--------|----------------------------------|---------|---------------------------------|\\n| GET | `/health` | no | Liveness check |\\n| GET | `/` | no | Same as `/health` |\\n| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |\\n| GET | `/limits` | no | Every fixed validation bound, grouped by resource β€” see Validation limits |\\n| GET | `/swagger` | no | Interactive API docs (Swagger UI) |\\n| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |\\n| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |\\n| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken β€” see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |\\n| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` β€” own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) Β· paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` β€” find users by username/name fragment (pickers); refs only, no contact info Β· paged |\\n| GET | `/users` | admin | List all users Β· paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` β€” set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` β€” tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students Β· paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |\\n| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes Β· paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) β€” ≀ the school's `max_file_bytes`, ≀ 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) Β· paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |\\n| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` β€” send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` β€” the caller's folder, newest first; `?folder=inbox&read=false&limit=1` β†’ `total` is the unread badge Β· paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` β€” read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** β€” only from the trash (`409` elsewhere); the row vanishes once both sides deleted |\\n| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` β€” `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` β€” mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) Β· paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` Β· paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` β€” seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |\\n| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` β€” publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, ≀ 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) β€” a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar β€” future slots only, demoted teachers' slots left out Β· paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` β€” book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests Β· paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` β€” call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included β€” they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` β€” counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal β€” this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |\\n| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` β€” `kind` is `course` (default), `study` (etΓΌt), or `club` (kulΓΌp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) Β· paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses Β· paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ β€” **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` β€” assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` β€” enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) Β· paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β€” add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β€” add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |\\n| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` β€” roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) Β· paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` β€” add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) Β· paged |\\n| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist β€” the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` β€” grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) Β· paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt β€” students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) Β· paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question β€” the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam β€” copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** β€” copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question β€” text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` β€” autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers ⋃ marks), ascending β€” the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first β€” the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** β€” the answer key the caller checks their own sheet against (same review gate) Β· paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers ⋃ marks), ascending β€” only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster Γ— latest attempts Γ— marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |\\n| GET | `/bank-questions` | teacher | The school-wide question bank β€” `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) Β· paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist β€” `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question β€” the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` β€” assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≀ 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) Β· paged |\\n| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) Β· paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade β€” the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades β€” file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` β€” hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part β€” **any** content type, ≀ `max_file_bytes`, ≀ 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) β€” the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student Γ— submission/files/grade + computed `late`/`missing`/`unenrolled` β€” a straggler's stale work stays visible (course manager) Β· paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` β€” grade `done`/`incomplete`/`missing` (+ optional 0–100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable β€” that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) β€” readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade β€” un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows β€” submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` β€” full, statuses and marks only, never files Β· paged |\\n| POST | `/questions` | student | `{title, body}` β€” ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` β€” the pool questions visible to the caller, each with its `solution_count` Β· paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question β€” publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` β€” offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first β€” a discussion thread Β· paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` β€” edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |\\n| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) Β· paged |\\n| GET | `/work/{user}` | manager | A staff member's work log Β· paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` β€” correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |\\n| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** β€” a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` Β· paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape Β· paged; *or a `parent` linked to `{user}` |\\n| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |\\n| POST | `/terms` | manager | `{name, starts_at, ends_at}` β€” past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first Β· paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course still links to it |\\n| POST | `/meals/menus` | manager | `{date, slot, capacity?}` β€” publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first Β· `?from=&to=` inclusive `YYYY-MM-DD` range Β· paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` β€” the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` β€” add a dish (≀ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` β€” record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` β€” take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first Β· paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included Β· paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent β€” cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` β€” mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu Β· paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history Β· `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day Β· paged Β· own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` β€” record money received; **admin only**, appends a `credit` line |\\n| POST | `/payments/plans` | manager | `{name, installments}` β€” write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it β€” its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (≀ 200) β€” place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first Β· paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` β€” record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` β€” hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` β€” undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines β€” charges, payments, refunds, reversals β€” newest first Β· paged Β· own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |\\n| POST | `/chatbot/threads` | student | `{title?}` β€” start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first Β· paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` β€” rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first β€” user and assistant rows alike Β· paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≀ `max_chatbot_message_len`) β€” send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` β€” nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β€” or one `error` β€” and close; an already-finished answer replays (see \\"Chatbot\\") |\\n| POST | `/boards` | student | `{title, participant_ids?}` β€” open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first Β· paged |\\n| GET | `/boards/{id}` | student | One board β€” a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |\\n\\n`status` must be one of the school's attendance statuses (`GET /settings`);\\nthe core four `present | absent | late | excused` always exist, plus whatever\\nthe school added.\\n`kind` must be one of the school's exam kinds (`GET /settings`; defaults:\\n`homework | quiz | midterm | final | project | oral`). The kind carries the\\nexam's weight in the course average β€” an integer `1`–`100` set per **kind** in\\nsettings (defaults all `1`), resolved when a report is read; an exam whose\\nkind was later removed from settings counts with weight `1`.\\nA course may carry a `term_id` (`null` = unassigned); on `PATCH\\n/courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`\\nclears it.\\n`role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are\\nULIDs. `parent` accounts are made by an admin (register as `student`, then\\n`PATCH /users/{id}/role`) and observe only the students an admin tied to them\\nβ€” see \\"Roles & access control\\".\\nAn exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row,\\nnever in a `note`. Students never grade anyone β€” grading is teacher+ with\\ncourse-management rights, and the target must be enrolled in the exam's course;\\na student reads just their own mark via `GET /exams/{id}/result`.\\nA course average is `Ξ£(markΓ—weight) / Ξ£(weight)` over the student's **graded**\\nexams in that course (`null` while nothing is graded β€” ungraded exams are\\nskipped, not zeroed). The overall average is the plain mean of the non-null\\ncourse averages. Unenrolling keeps result rows: the marks drop out of the\\nreport until re-enrollment, but stay visible on the exam itself. A course\\nwith anyone still on its roster refuses deletion (`409`) β€” empty the roster\\nfirst; once empty, deleting it cascades its exams, their results, its\\nsessions and roll call, and its subjects.\\nA **subject** is one topic of a course's curriculum (`name` ≀ 200 chars,\\noptional `description` ≀ 2000): every exam question carries a mandatory\\n`subject_id` naming one of *its own course's* subjects (an unknown or\\nforeign-course subject is a `400`), so exam content is always attributable to\\na topic. A subject's course link is fixed at creation, and a subject still\\nreferenced by questions refuses deletion with a `409` β€” re-tag (PATCH the\\nquestions' `subject_id`) or delete those questions first. Questions written\\nbefore subjects existed are **destroyed on boot** (answers first) β€” the clean\\nbreak instead of inventing a placeholder topic.\\nEvent `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both\\nare given, `ends_at` must not precede `starts_at`, and neither may be set in\\nthe past (else `400`). On `PATCH`, an omitted time keeps its value and an\\nexplicit `null` clears it.\\nAn event's `audience` is a tagged object β€” `{\\"kind\\": \\"school\\"}` (the default),\\n`{\\"kind\\": \\"role\\", \\"role\\": \\"student\\"}` (that exact role, no \\"and above\\"),\\n`{\\"kind\\": \\"course\\", \\"course\\": \\"<id>\\"}` (the course's current enrollment), or\\n`{\\"kind\\": \\"registration\\", \\"capacity\\": 30}` (a signup list; `capacity` optional,\\n`null` = unlimited) β€” and is the event's **expected-attendee roster**, resolved\\nlive at read time: role changes, (un)enrollments, and (un)registrations move\\npeople in and out by themselves. It never hides the event β€” everyone sees every\\nevent. Only audience members can be marked; `GET /events/{id}/roster` joins the\\nlive roster with the recorded marks (`status: null` = expected but never\\nmarked). Attendance rows for people a later audience edit (or unenrollment /\\nrole change) dropped stay stored and listed under `/events/{id}/attendance`,\\nbut leave the roster report.\\nA registration list fills through `POST /events/{id}/register`: teachers place\\nstudents (a student never registers, not even themselves) and take seats only\\nfor themselves β€” registering another staff member is refused. Re-registering\\nsomeone is a no-op, a full list is a `409`, and the list freezes the moment\\nthe event starts β€” or, when only `ends_at` is set (a pure signup deadline),\\nthe moment it passes (register and unregister both). Signup rows survive an\\naudience switch inertly and resurface if the event returns to the registration\\nkind; deleting the event deletes them. Pre-existing hand-picked (`users`)\\naudiences convert on boot: each listed user becomes a signup row credited to\\nthe event's creator, and the audience becomes an uncapped registration list.\\nReading a child collection of a missing parent (`/events/{id}/attendance`,\\n`/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`,\\n`/courses/{id}/sessions`, `/courses/{id}/subjects`, `/courses/{id}/homework`,\\n`/homework/{id}/submissions`, `/sessions/{id}/attendance`) is a `404`, not an\\nempty list.\\nPersonal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same\\noptional set on every account, whatever the role, and is `null` until filled\\nin. On `PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) each field\\nis independent: omitted (or `null`) keeps the current value, an empty string\\n`\\"\\"` clears it, anything else is validated β€” email must look like\\n`name@example.com`, phone is 7–15 digits with an optional `+` and cosmetic\\nseparators, `birth_date` is a real `YYYY-MM-DD` calendar date not in the\\nfuture. Names allow unicode; usernames are strict: lowercase letters and\\ndigits plus non-consecutive interior `.`, `_`, `-` separators, starting and\\nending with a letter or digit (3–32 chars). Staff-looking names (`admin`,\\n`administrator`, `root`, `support`, `system`, `moderator`, `staff`) are\\nrejected at `/auth/register` only β€” the `ADMIN_USERNAME` bootstrap may still\\nseed them.\\nUI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`,\\n`palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the\\nsame account row and come back on every user response (`/auth/me` included).\\n`PATCH /users/me/preferences` (or the admin `PATCH /users/{id}/preferences`)\\nuses the same field semantics as the profile patch: omitted keeps, `\\"\\"` clears\\nback to `null` (\\"never chose\\" β€” the client then follows the device\\npreference, or its own default accent), anything else must be valid or the\\nwhole patch is a `400`. `palette_color` is the one **open** set: any valid hex\\npasses (mixed case in, stored and returned lowercase), so a new frontend\\npalette needs no backend change β€” `/limits` publishes its pattern rather than a\\nlist of colors.", "source": "README.md"}, {"id": "appointments", "title": "Appointments", "body": "Office hours and parent-teacher conferences, booked instead of arranged by\\nmessage. A teacher+ **publishes availability**; a student or a parent\\n**books** one of those windows with a reason; the teacher **decides**. Two\\nrows carry it: an `appointment_slot` (the offer) and an `appointment` (the\\nbooking sitting on it) β€” a slot is never \\"half booked\\", and a refused request\\nstays readable instead of vanishing.\\n\\nA slot is a window on one teacher's calendar: `starts_at`/`ends_at` (unix\\nmilliseconds, `starts_at` strictly before `ends_at`, neither in the past β€” the\\nusual 60-second grace) plus an optional `note` (≀ 500 chars) shown to\\nrequesters (\\"office hours\\", \\"veli gΓΆrüşmesi\\"). Windows are **half-open**, so\\n10:00–10:30 and 10:30–11:00 are two slots, not a collision. A window that *does*\\noverlap one the same teacher has already published is refused with a `409` β€” the\\nguard is **per-teacher** (two teachers may hold office hours at the same hour)\\nand boundary-touching windows are legal by that same half-open rule, which is\\nhow an hour gets carved into back-to-back slots. `POST\\n/appointments/slots` publishes on the caller's *own* calendar (managers and\\nadmins included β€” the calendar always belongs to whoever posted) and **always\\nanswers an array**: one element for a one-off, one per occurrence for a\\nrecurring publish.\\n\\n`repeat_weekly: true` with an `until` expands the same window every seven days\\nup to and including `until`, server-side, into **concrete rows** sharing a\\n`series` id β€” no recurrence rule is stored, so one week can be cancelled\\nwithout touching the rest. At most 52 occurrences (a year); asking for more is\\na `400`, as is `repeat_weekly` without `until` β€” and so is a window sitting so\\nfar ahead that shifting it by a week would run off the end of representable\\ntime (the shift is checked, never wrapped: a wrapped end would land *before*\\nits start, and an inverted window can never overlap anything, which would\\nquietly disable the double-booking guard). A recurring publish is\\n**all-or-nothing**: every occurrence is checked β€” against the slots already\\nstored *and* against the earlier occurrences of the same batch, which a window\\nlonger than a week overlaps itself β€” before a single row is written, so a\\nmid-series collision answers `409` and leaves no stray weeks behind. Delete one\\noccurrence with\\n`DELETE /appointments/slots/{id}`, the whole publish with `DELETE\\n/appointments/slots/series/{series}`.\\n\\n```json\\nPOST /appointments/slots\\n{ \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"repeat_weekly\\": true, \\"until\\": 1901209600000 }\\n\\n201 [ { \\"id\\": \\"01J8…A\\", \\"teacher\\": {\\"id\\": \\"01J8…T\\", \\"username\\": \\"ayse\\",\\n \\"display_name\\": \\"Ayşe YΔ±lmaz\\"},\\n \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"series\\": \\"01J8…S\\", \\"created_at\\": 1899… },\\n { \\"id\\": \\"01J8…B\\", …, \\"starts_at\\": 1900604800000, \\"series\\": \\"01J8…S\\" } ]\\n```\\n\\n`GET /appointments/slots` is two lists behind one path: a teacher+ reads\\n**their own** calendar, past occurrences included; everyone else reads the\\n**bookable** calendar β€” future slots only, earliest first. A teacher demoted\\nafter publishing leaves **inert** slots: their live role is re-read, so those\\nslots drop out of the bookable list and booking one is refused with a `409`.\\nThe list does not say whether a slot is already taken β€” booking a taken one\\nanswers `409`.\\n\\n**Booking.** `POST /appointments` (`{slot, reason}` β€” the reason is required,\\n≀ 1000 chars) is for **students and parents only**; staff arrange between\\nthemselves off this API. A parent books for *themselves* β€” this is the\\nparent-teacher conference, not a booking on behalf of a child. The request\\nlands `pending`, always: publishing availability is not consent to a\\nparticular person and a particular topic, so approve/reject still applies.\\n\\nA booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two\\nare **live** and hold the slot; rejecting or cancelling frees it for someone\\nelse immediately (the slot carries an `occupied` counter, taken by a booking\\nand handed back in the same transaction as the reject or cancel that settles\\nit, so the seat is decided by the database rather than by a count two\\nconcurrent bookings can both read as free). The decisions:\\n\\n- `PATCH /{id}/approve` β€” the slot's teacher (or manager+) confirms. Refused\\n (`409`) when the effective window has already started.\\n- `PATCH /{id}/reject` β€” turns it down; the slot frees up.\\n- `PATCH /{id}/cancel` β€” **the requester only**, from either live state.\\n Anyone else is a `403`, the slot's teacher and a manager/admin included (the\\n guard compares ids, not roles). A teacher ends a booking by **rejecting** it\\n while it is `pending`, and an approved one by counter-proposing another time\\n (`/reschedule`, which sends it back to `pending`) and then rejecting it β€” or\\n simply by rescheduling to a time that works. Refused (`409`) once the\\n meeting's window has started: a\\n meeting that already began is history, not a plan. The guard sits in the\\n domain's `cancel` itself, on a fresh read compared-and-set into the row, so\\n every way of cancelling β€” the decline below included β€” inherits it.\\n- `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) β€” the teacher\\n **counter-proposes**. The times land on the *same* row as\\n `proposed_starts_at`/`proposed_ends_at`, the status goes back to `pending`\\n and `decided_by` clears, because leaving it `approved` would silently move a\\n confirmed appointment. The slot stays held meanwhile. A window that has\\n already opened is refused (`409`): the 60-second grace on the times is for\\n clock skew, not for proposing into a meeting already underway β€” one nobody\\n could then cancel.\\n- `PATCH /{id}/reschedule/accept` β€” the **requester** only: this *is* approval\\n at the new time, so the overlap guard runs again β€” and so does the\\n already-started guard (`409`). Agreeing to a window that has begun does not\\n help: the meeting could never be cancelled. The booking stays `pending`, so\\n the teacher just proposes a time that can still happen.\\n- `PATCH /{id}/reschedule/decline` β€” the requester only, and it **cancels the\\n booking**: the proposal replaced the time that was asked for, so there is\\n nothing to fall back to. The row stays readable as `cancelled` with the\\n refused proposal still on it β€” book another slot instead. Declining *is* a\\n cancel, so it answers to the cancel deadline too (`409` once the effective\\n window has started).\\n\\n**Who settled it, and why.** Every settled booking carries its own audit trail\\non the row: `decided_by` (who approved or rejected β€” cleared again by a\\ncounter-proposal), `cancelled_by` (who called it off, stamped by `cancel` and by\\na declined counter-proposal), plus the optional free text that came with the\\ndecision β€” `reject_reason` on `PATCH /{id}/reject` and `cancel_reason` on\\n`PATCH /{id}/cancel` and `/reschedule/decline`. Both reasons are optional: the\\nwhole body may be omitted, a blank one records nothing (`null`), and a present\\none is validated like the booking's own reason (≀ 1000 chars, `400` past that)\\nbefore it reaches the row. They are **not public**: bookings are only ever\\nrendered to the person who requested them and to the slot's teacher (a\\nmanager/admin acting on one by id sees the response to their own call), so\\n\\"couldn't make it, sorry\\" goes no further than the two people it concerns. Rows\\nwritten before these fields existed simply read back `null`.\\n\\nA booking's effective window is the accepted counter-proposal when there is\\none and the slot's own window otherwise; that is what `starts_at`/`ends_at` on\\nan `AppointmentResponse` report, and what the cancel deadline is judged on.\\n\\n**No double-booking.** Two `approved` meetings may never overlap for the same\\nteacher *or* the same requester (`409`). The guard runs at approval β€” the\\nmoment anyone is actually committed β€” and again on accepting a counter-proposal,\\nbecause the time moved. Approval also refuses (`409`) an **effective window\\nthat has already started** (the proposal's when one stands, the slot's\\notherwise), for the same reason booking one is refused. Requesting is checked more loosely: a booking is\\nrefused up front only when the slot's window has already started (booking it\\nwould create a meeting `cancel` refuses to undo β€” the 60-second publish grace\\nis for clock skew, not for booking into the past), when the slot is already\\ntaken, or when the *requester* is already committed at that hour; a clash on the teacher's side is theirs to\\nresolve when they decide, since refusing a request against a window they\\nthemselves published would only confuse. Touching windows never conflict.\\n\\nDeletion follows the same rule as the rest of the codebase: a slot carrying a\\nlive (pending or approved) booking refuses to go (`409`) β€” reject or cancel\\nthat booking first β€” and a series delete is all-or-nothing, `409` if *any*\\noccurrence still carries one, so the person waiting is dealt with rather than\\nleft stranded on a stray week. Settled (rejected/cancelled) bookings cascade\\naway with their slot.\\n\\n`GET /appointments` is likewise two lists: a teacher+ sees the bookings aimed\\nat their own slots (their request inbox), everyone else the ones they\\nrequested, newest first, paged. Managers and admins read their own inbox here\\ntoo β€” they may still decide any booking by id.", "source": "README.md"}, {"id": "messaging", "title": "Messaging", "body": "One-to-one, mail-style (subject + body + an optional free-text `label` the UI\\nrenders as a badge β€” \\"EtΓΌt\\", \\"SΔ±nav\\"; no threads): any user writes to any\\nuser β€” student to teacher, parent to teacher, teacher to student; only\\nmessaging yourself is refused. A single stored message serves both parties,\\nbut each **owns their copy independently**: the recipient's moves through\\n`inbox` β†’ `archive`/`trash` and carries the `read` flag (the sender sees it\\nas a read receipt); the sender's moves through `sent` β†’ `archive`/`trash`. Filing or\\ndeleting your copy never changes the other side's view.\\n\\nEvery copy remembers where it was filed from, so it can go back there. Moving\\ninto `archive`/`trash` stamps the folder you left onto the copy's\\n`previous_folder`, and restoring is a `PATCH` of `folder` back to that value:\\nan inbox message you archive and then trash returns to `archive`, and from\\nthere to `inbox`. Two folders are never stamped β€” the trash itself (pulling a\\ncopy out of the trash must not leave it pointing back at the discard pile) and\\nthe folder you are already in β€” and moving back to `inbox`/`sent` clears the\\nstamp. `previous_folder` is therefore `null` for any copy sitting in its home\\nfolder, and for copies filed before the field existed; both mean \\"restore to\\n`inbox`\\" (`sent` for the sender's copy).\\n\\nListing is per folder β€” `GET /messages?folder=` with `inbox` (default),\\n`sent`, `archive`, or `trash` (trash shows both received and sent copies you\\ntrashed) β€” newest first, paged, with sender/recipient rendered as person refs\\nplus their role. `?read=false` narrows to unread (`true` to read), and since\\n`total` counts the filtered view, `?folder=inbox&read=false&limit=1` is the\\none-row unread-badge query. `PATCH /messages/{id}` flips `read` (recipient only) or\\nmoves your copy (`folder`), restoring included. `DELETE` is\\npermanent, allowed only while your copy sits in the trash (`409` otherwise),\\nand physically removes the row once both sides have deleted theirs. Replying\\nis just sending a new message back β€” the frontend prefixes the subject if it\\nwants an `Re:`.", "source": "README.md"}, {"id": "question-pool", "title": "Question pool", "body": "Students get stuck; the pool is where the school unsticks them β€” with a\\nmoderation gate so nothing unreviewed goes school-wide. `POST /questions`\\n(students only, exact role) creates the question `pending`: only the asker\\nand teacher+ can see it (anyone else gets a `404`, not a `403` β€” a pending\\nquestion's existence is nobody else's business), and `GET\\n/questions?status=pending` is a teacher's approval queue. The asker may\\nattach **one photo** of the problem (`POST /questions/{id}/image`,\\n`multipart/form-data` with a `file` part β€” raster types only, no SVG, ≀ the\\nschool's `max_file_bytes`), replace it, or remove it β€” while pending only.\\n\\n`POST /questions/{id}/approve` (teacher+) publishes it: the question becomes\\nreadable by every signed-in user above `parent`, and its content β€” title,\\nbody, photo β€” **freezes**, because an edit after approval would bypass the\\nmoderation that just happened. There is no rejected state and no edit\\nendpoint: to fix a typo the asker deletes and re-asks; to reject, a teacher+\\ndeletes. Approving twice is a `409`; the response records `approved_by`.\\n\\nAnyone in the school (student through admin β€” not parents) may then offer a\\n**solution**: `POST /questions/{id}/solutions` with a text body, listed\\noldest-first like a discussion thread (`GET`, paged). Solutions are the\\nunmoderated half of the pool, so nothing about them ever freezes: the author\\nβ€” and only the author, teacher+ included out β€” may edit the body (`PATCH\\n/questions/{id}/solutions/{sid}`) and attach one **photo** of the worked\\nsteps (`POST /questions/{id}/solutions/{sid}/image`, same raster-only rules\\nand `max_file_bytes` cap as the question's photo), replace it, or remove it,\\nat any time; moderation stays delete-only β€” a teacher+ removes a bad\\nsolution, never rewrites someone else's words. A solution is deleted by its\\nauthor or by teacher+, its photo blob going with it; deleting a question β€”\\nasker withdrawing, or teacher+ moderating β€” takes its solutions and every\\nphoto blob (its own and its solutions') with it. Each question row reports\\nits `solution_count`, and questions and solutions embed their people as\\nperson refs (`{id, username, display_name}`), so the UI never shows a raw\\nULID.", "source": "README.md"}, {"id": "per-school-policy-settings-terms", "title": "Per-school policy (settings & terms)", "body": "Every school runs differently; the parts that vary are data, not code. One\\neditable `settings` singleton (`GET /settings` for any signed-in user,\\n`PATCH /settings` for manager+) carries seven knobs:\\n\\n- **`exam_kinds`** β€” the accepted `kind` values for new exams, each an\\n object `{name, weight}`. The weight (`1`–`100`) is how many times an exam\\n of that kind counts into its course average β€” weighting is school policy,\\n set once per kind, never per exam. Defaults to `homework, quiz, midterm,\\n final, project, oral`, all weighing `1` (a plain average); replace the\\n list with whatever the school grades and weighs (`{\\"name\\": \\"final\\",\\n \\"weight\\": 3}`, …). Reports resolve weights live: editing a weight\\n re-weights every exam of that kind at once. For the same reason a kind\\n whose exams already carry marks cannot be removed from the list (`409`):\\n those marks would silently re-weight. An unmarked kind leaves freely, and\\n an exam keeping a since-removed kind counts with weight `1` β€” but it can no\\n longer be graded (`409`) until the school offers that kind again, which is\\n what keeps \\"a marked kind cannot be removed\\" true from both ends. The same\\n rule pointed at one exam: an exam that already carries marks keeps its\\n `kind` (`PATCH /exams/{id}` answers `409`), because re-pointing it would\\n re-weight those marks just as silently.\\n- **`attendance_statuses`** β€” what attendance marking accepts. The core four\\n (`present`, `absent`, `late`, `excused`) are mandatory because the\\n attendance rate is defined over them (`(present+late) /\\n (present+absent+late)`); school extras (say `online`) are **rate-neutral**\\n and tally under `custom` in the attendance reports.\\n- **`grade_bands`** β€” how numeric marks display: a list of `{min, label}`\\n bands (`85 β†’ \\"AA\\"`, `50 β†’ \\"CC\\"`, …). One band must start at `0` so every\\n mark maps; an empty list (the default) means numeric-only. Storage and\\n averaging stay `0`–`100` forever β€” bands only add `grade`,\\n `average_grade`, and `overall_grade` labels to the mark report, so a school\\n can switch display scales without touching a single stored mark.\\n- **`max_file_bytes`** β€” the per-file size cap for uploads (note files and\\n exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;\\n a server hard cap β€” uploads buffer in memory), default `5242880` (5 MiB).\\n Checked at upload time only: lowering it never touches already-stored files.\\n- **`chatbot_history_turns`** β€” how many prior **messages** of a thread the\\n chatbot is given as context, `1`–`50` (default `10`). The unit is messages,\\n not exchanges: a question and its answer are two, so the default remembers\\n five question/answer pairs. Every one of them is re-sent on every reply, so\\n the number is both what the bot remembers and what each answer costs.\\n- **`max_chatbot_threads`** β€” how many chatbot threads one user may\\n keep, `1`–`500` (default `50`); at the cap the user deletes an old one\\n first. Storage protection, not a usage quota β€” that is the per-minute\\n message limit.\\n- **`max_chatbot_message_len`** β€” character limit on one chat message,\\n `100`–`8000` (default `4000`); the ceiling is a server hard cap, because\\n the message and its history must fit one bridge frame.\\n\\nA `PATCH` replaces only the fields it carries, each wholesale, and validation\\nis all-or-nothing. Concurrent edits are safe: each save applies only if the\\npolicy still matches the snapshot it merged from (retrying over the fresh row\\notherwise), so two managers patching different fields both land instead of\\nthe later write silently reverting the earlier one. Editing a list never\\nrewrites history: an exam keeps its retired kind, a roll-call row keeps its\\nretired status β€” only **new writes** are held to the current lists (which is\\nwhy grading an exam whose kind has left the list is refused).\\n\\nThe kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see \\"Food program: menus, dishes, bookings & the ledger\\").\\n\\nAcademic structure is data too. **Terms** (`/terms`) model whatever calendar\\nthe school runs β€” semester, trimester, quarter systems are just rows with a\\nname and a date range. Courses may link to one via `term_id` (nullable), and\\ndeleting a term is refused with a `409` while any course still links to it β€”\\nunlink those courses (`PATCH /courses/{id}` with `\\"term_id\\": null`) or delete\\nthem first, so the calendar never disappears under them. Term dates may lie in the past,\\ndeliberately: a school adopting the app mid-year backfills its calendar β€”\\nunlike exam/lesson/event times, which reject backdating.\\n\\nWhat stays fixed is deliberate too: the four roles, the `0`–`100` mark scale,\\nvalidation bounds, and the UTC time policy are invariants, not preferences\\n(rename role labels in the frontend if a school says \\"principal\\" instead of\\n\\"manager\\"). Deployment knobs (ports, rate limits, admin seed, CORS) remain\\nenvironment variables β€” the model is **one school per deployment**, which\\nkeeps every school's data physically isolated.", "source": "README.md"}, {"id": "food-program-menus-dishes-bookings-attendance-the-ledger", "title": "Food program: menus, dishes, bookings, attendance & the ledger", "body": "The school publishes **one menu per calendar day and meal slot** (`POST\\n/meals/menus`). Two shapes there are deliberate:\\n\\n- **`date` is text**, `YYYY-MM-DD`, not a timestamp. \\"One menu per day and\\n slot\\" is an equality test on the school's own day, and a midnight-in-millis\\n day is only unique for one timezone. Fixed-width and zero-padded, so the\\n text sorts chronologically β€” which is what the inclusive `?from=&to=` range\\n filter and the newest-day-first ordering are built on.\\n- **`slot` is a snapshot**, not a link into settings. It must be one of the\\n school's `meal_slots` (`GET /settings`) *when the menu is written*, and it\\n is stored as text β€” so retiring a slot later never rewrites a menu already\\n published under it. The slot's `serving_minute` is *not* snapshotted: the\\n booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any\\n menu was published for cannot be removed from the list (`409`), same\\n contract exam kinds have with graded exams.\\n\\nThe day+slot pair is unique: a second publish for the same meal answers `409`\\nβ€” edit the first one instead. Only `capacity` is patchable (`null` = uncapped)\\nβ€” `date` and `slot` are immutable, because a menu on another day is another\\nmenu.\\n\\n**Dishes** hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, then\\n`PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional\\ndescription (blank or `null` clears it), dietary `tags` drawn from the\\nschool's `dietary_tags` list β€” an unknown tag is a `400`, never a stored\\nstring β€” and a `price_minor`.\\n\\n### Dietary profiles and conflicts\\n\\nA student carries a **dietary profile**: a list of tags plus a free-text note\\nfor the kitchen, one row per student (the record key *is* the student's id).\\nThe tags come from the *same* `dietary_tags` list a dish is tagged from β€”\\nthere is deliberately no second vocabulary, because one shared list is exactly\\nwhat makes \\"is this dish a problem for this student\\" answerable as a set\\nintersection, without the backend knowing any nutrition.\\n\\nWriting it is **manager+** (`PATCH /meals/profiles/{user}`, first write\\ncreates the row). A student does *not* edit their own allergen list: it is a\\nsafety record the school keeps on their behalf, and a mistyped β€” or quietly\\nremoved β€” allergy would otherwise reach the kitchen with the school's\\nauthority behind it. Reading is `GET /meals/profiles/me`, or\\n`GET /meals/profiles/{user}` under the usual per-student gate (own id always,\\notherwise teacher+ or a parent link). A student who was never recorded reads\\nback as an *empty* profile rather than a `404` β€” \\"nothing known\\" is an answer.\\n\\nEvery dish a menu read returns therefore carries a **`conflicts`** list: the\\nintersection of that dish's `tags` with the **calling user's** profile tags.\\nIt is empty when the two do not overlap, and empty for every reader without a\\nprofile β€” a manager reading a menu sees `conflicts: []`, which is correct and\\nnot a bug (the field answers \\"may *I* eat this\\", and there is no \\"conflicts\\nfor student X\\" parameter). The caller's profile is loaded **once per request**,\\nnot per dish, so the menu list stays at its fixed query count no matter how\\nmany menus or dishes the page holds.\\n\\n**Money is minor units** (kuruş) as an integer, at every layer: `4550` is\\n45,50 β‚Ί. This API never speaks decimals or floats about money, so no rounding\\nis ever introduced by transport or by a client's JSON number parser.\\n\\nReads are open to every authenticated user β€” a student has to see what is\\nbeing served β€” and every write is manager+. Deleting a menu takes its dishes\\nwith it: a dish has no meaning apart from the menu it was published on.\\n\\n**Bookings** are seats on a published menu (`POST\\n/meals/menus/{id}/bookings`). One row per (menu, student), keyed by a\\ndeterministic composite id, so booking twice is the same seat and never a\\nsecond one. A **student books only for themselves**; a **parent books for a\\nstudent they hold a link to** β€” the one write a `parent_link` authorises, since\\npaying for lunch is a parent's job. Nobody else books through this route: a\\nteacher or manager ordering a child's lunch is a `403`.\\n\\n- **Cancelling is a status flip, not a delete** (`DELETE\\n /meals/bookings/{bid}` answers `200` with the flipped row): the row survives\\n as `cancelled` with a `cancelled_at` stamp, so a freed seat stays auditable\\n against the money it moved. Only `booked` rows count against `capacity`,\\n which is what genuinely frees the seat β€” and re-booking is the same row\\n flipped back. The call is **idempotent**: cancelling an already-cancelled\\n seat answers `200` with the row as it stands *and replays the refund*, so a\\n cancel cut short between the flip and the reversal (the tab closed, a proxy\\n timed out) is recovered by sending it again. Refusing it as a `409` β€” as it\\n once did β€” made that state permanent: no route could append the missing\\n reversal, and the student stayed billed for a seat they no longer held.\\n- **The capacity check is serialized in-process.** Counting rows and then\\n writing one is write-skew: SurrealDB does not conflict-check a cross-record\\n count against a concurrent insert, so 24 students racing for 3 seats would\\n otherwise all pass the count. The whole check-then-write runs under the same\\n lock a menu publish takes, and the cap is re-read inside it.\\n- **One cutoff closes both ends.** Within the school's\\n `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new\\n booking nor a cancellation lands (`409`) β€” the kitchen's headcount has to\\n settle at some point. `null` (the default) means no cutoff at all. The\\n cutoff is measured back from the menu's `date` **plus the slot's\\n `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served\\n at `720` closes at 10:00 UTC that morning, not at 22:00 the night before.\\n **That minute is UTC**: `date` carries no timezone and the backend stores no\\n school timezone β€” deliberately, it is a rejected feature β€” so a UTC+3 school\\n enters `540` (09:00 UTC) for a meal served at noon locally. A slot with no\\n `serving_minute` falls back to **midnight UTC starting the meal's day**, the\\n behaviour every booking had before the field existed; the booking is never\\n refused for want of a serving time.\\n- **The serving time is read live, not snapshotted onto the menu.** The cutoff\\n minutes are already read live, so freezing the other half of the same\\n deadline would make one policy edit apply and its twin not; a kitchen that\\n moves lunch an hour later wants today's menus to move with it. The menu\\n still snapshots the slot *name* (that is what keeps a retired slot's history\\n readable), so a menu whose slot has since left the list simply has no\\n serving time and falls back to midnight UTC.\\n- A menu somebody still holds a seat on **cannot be unpublished** (`409`) β€”\\n cancel the bookings first, so nothing is left pointing at a deleted meal.\\n\\n`GET /meals/bookings/me` is the caller's own list: the seats held *for* them\\nplus, for a parent, the seats held for every student they **currently** hold a\\nlink to β€” so a parent's list is their children's meals. The links are re-read\\non every call rather than trusted from the booking's `booked_by` stamp: an\\nunlinked parent stops seeing the child's seats at once, including the ones\\nthey booked and paid for themselves, exactly like every other parent read. `GET /meals/menus/{id}/bookings` is the kitchen's list for\\none menu (manager+), cancelled rows included so the changes are visible.\\n\\n### Meal attendance\\n\\nWhoever stands at the canteen door records who actually ate:\\n`POST /meals/menus/{id}/attendance` with `{student_id, status}`, teacher+ (a\\nstudent never marks, not even themselves). The status is the fixed pair\\n`served` / `missed` β€” deliberately **not** the school's editable\\n`attendance_statuses`, since a canteen line has no \\"late\\" or \\"excused\\", and one\\nlist meaning two things would let a school change one by editing the other.\\nOne row per (menu, student) keyed by a composite id, so a correction re-marks\\nthe same row instead of stacking a second one.\\n\\n**Attendance has zero billing effect.** Booking is the sole charge trigger, so\\na student who booked and did not eat still pays β€” the kitchen bought the food.\\nThere is no no-show penalty, no refund-on-missed, and no auto-reversal:\\nnothing under `meal_attendance` writes to the ledger. A walk-in with no live\\nbooking *can* be marked `served` (the record is operationally true) and is\\nlikewise not charged for it β€” charging there would be a ledger write. The\\ntarget only has to *exist*: a canteen also feeds staff, so any user may be\\nmarked, not only a student. A mark is a record of what happened, not a check\\nof who was entitled, and since it moves no money it costs nobody anything.\\n\\n`GET /meals/menus/{id}/attendance` is the per-menu list (teacher+), and\\n`GET /meals/attendance/{user}` is one student's history, narrowable with\\n`?from=&to=` β€” inclusive `YYYY-MM-DD` bounds compared against the *menu's*\\nday, a lexical compare that is chronological for that format. Same gate as the\\nbalance and the ledger: the caller's own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`meal_ledger`): one line per `charge`,\\n`credit`, or `reversal`, every field `READONLY`, and **no code path anywhere\\nthat updates or deletes one**. A ledger line that can be edited or dropped\\nsilently rewrites a student's financial history with no trace of the rewrite β€”\\nthis is the one genuinely irreversible part of the food program, so a mistake\\nis corrected by appending the opposing line, which leaves both the mistake and\\nthe correction visible.\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer.\\nA *negative* balance means the student owes the school; a positive one is\\nmoney on account. Amounts are stored positive; the sign lives in the `kind`.\\n\\n- **Booking is what charges, at a price snapshot.** The menu's dishes are\\n summed the moment the seat is taken and that number is frozen onto the\\n charge. Editing a dish's price afterwards moves no existing charge β€” what a\\n student owes is what the menu cost the day they booked. The price is\\n snapshotted *before* the seat is given, so a menu that cannot be charged\\n refuses the booking rather than leaving a booked-but-unbilled row (`400`,\\n when the dishes sum past 10 000 000). A free menu writes no line at all β€”\\n but the booking row records that it *was* free, so \\"free when taken\\" is\\n never confused with \\"not billed yet\\": pricing the menu afterwards leaves\\n every seat already taken on it free.\\n- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its\\n money move together under one in-process lock, and the ledger id is derived\\n from the seat plus how many times it has been taken β€” so eight simultaneous\\n `POST`s of one seat write one charge, a retried cancel refunds once, and a\\n write that failed halfway heals when the request is repeated. Booking the\\n same seat twice bills once because the *identity* is the same, never\\n because a scan happened to see the first charge in time.\\n- **Cancelling appends a `reversal`** for the charge's exact amount, with\\n `source` pointing at the charge it undoes. The charge row itself stays. A\\n cancel past the cutoff is already a `409`, so a reversal only ever follows a\\n legal cancel β€” and repeating a cancel replays the reversal, which is what\\n makes the refund recoverable rather than a one-shot the network can lose.\\n Re-booking afterwards is a **fresh** charge at the then-current price.\\n- **The price snapshot is taken under the booking lock**, and dish\\n create/edit/delete take that same lock. Taken outside it, a dish added\\n between the sum and the seat would be frozen onto the row as \\"the menu was\\n free then\\" β€” and nothing heals it, since a seat already held is returned\\n as-is, never re-priced.\\n- **A no-show still pays.** Meal attendance has zero billing effect β€” nothing\\n in the ledger reads or writes it. The seat was reserved and the food was\\n cooked; there is no no-show penalty and no no-show refund.\\n- **`POST /meals/credits` is admin-only**, not manager: writing down cash\\n received is the highest-trust action in the app. It appends a `credit` for a\\n student with a positive `amount_minor` (≀ 10 000 000), an optional `method`\\n (\\"cash\\", \\"havale\\", …) and `note`, and records the admin as `recorded_by`.\\n There is no payment gateway and no card data, ever. An over-credit is\\n corrected with a compensating line, never a fix-up.\\n\\n`GET /meals/balance/me` is the caller's own balance. `GET\\n/meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line\\nfirst) read a student's: your own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student. A charge's `source` is the\\nbooking id it came from, a reversal's is the charge line it reverses, and a\\ncredit has none.", "source": "README.md"}, {"id": "payments-fee-plans-assignment-the-fee-ledger", "title": "Payments: fee plans, assignment & the fee ledger", "body": "School fees live in their own tables (`fee_plan`, `fee_plan_assignment`,\\n`payment_ledger`) and their own balance. **Meal money is separate** β€” two\\nledgers, two balances, and no route folds one into the other: what a family\\nowes the canteen and what it owes the school are different debts, and mixing\\nthem would make either statement unreadable.\\n\\nEvery write here is **manager+**. Reads are narrower than the other\\nper-student reports: the student themselves, a parent holding a live link to\\nthem, or manager+ β€” **a teacher gets a `403` on every `/payments` route**,\\nbecause what a family owes the school is not classroom information.\\n\\n### Fee plans and what turns them into money\\n\\nA **fee plan** (`POST /payments/plans`) is a name and 1 to 60 **installments**,\\neach `{amount_minor, due_at}` β€” minor units (kuruş) as an integer, and unix\\nmilliseconds. `due_at` **may be in the past**: a school adopting the app\\nmid-year assigns plans whose first installments were already due, so there is\\nno future-date rule here.\\n\\nWriting a plan bills nobody. **Assigning it does** (`POST\\n/payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call):\\nthat appends *every* installment as a `charge` line right away, each carrying\\nits own due date. There is no scheduler, no nightly sweep, and nothing that\\nwakes up when a date passes β€” the whole schedule is written once, and lateness\\nis read off it.\\n\\nAssignment is **replay-safe by identity**: the assignment row is keyed\\n(plan, student) and every charge it raises is keyed (plan, student,\\ninstallment), so re-assigning bills nothing a second time (that student comes\\nback `already_assigned`), and an assignment cut short after three of twelve\\ncharges landed completes itself when the call is simply repeated. Only\\nstudents carry a fee record, so any other target comes back `rejected` β€” one\\nbad id never loses the rest of the batch.\\n\\nA plan that has been assigned to anyone can no longer be edited or deleted\\n(`409`). Its charges are frozen copies of the installments as they stood, so\\nan edit would only make the plan and the money tell different stories β€” write\\na new plan instead.\\n\\nThat freeze is a **counter on the plan row** (`assignment_count`), incremented\\nin the *same transaction* as the assignment row it counts, and the edit and the\\ndelete are single-record conditional writes against it β€” the same shape as a\\nterm's `course_count`. It used to be a `SELECT` taken before the write, which a\\nconcurrent assign could land behind, leaving a plan edited *and* assigned, or\\ndeleted with a live assignment naming it. Now the two contend on one record: an\\nassign either freezes the plan first (and the edit or delete is a `409`) or\\narrives after it (and bills the edited plan β€” the installments a first\\nassignment charges are re-read from the *stored* plan at the instant it\\nfreezes, never from the copy the request first looked at). A plan deleted out\\nfrom under a running batch is `rejected` for that student on, in the same\\nper-student report as every other outcome β€” the students it already billed are\\nnever dropped from the answer. A `PATCH`\\ncarrying no field at all writes nothing, so it is not refused.\\n\\nBecause an assignment is never removed, the counter is only ever claimed and\\nnever released: once assigned, a plan stays frozen for good. Plans written\\nbefore the counter existed are seeded from their assignment rows at boot,\\nbefore the server accepts a request β€” an absent counter reads as zero, and a\\nzero would have re-opened every already-assigned plan on an existing volume.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`payment_ledger`), exactly like the\\nmeal one: every field `READONLY`, and **no code path anywhere that updates or\\ndeletes a line**. A ledger line that can be edited or dropped silently\\nrewrites a family's financial history with no trace of the rewrite, so a\\nmistake is corrected by appending the **opposing line**, which leaves both the\\nmistake and the correction visible.\\n\\nFour kinds, and the sign lives in the `kind` β€” amounts are always stored\\npositive:\\n\\n| Kind | Sign | What it records | `source` points at |\\n| ---------- | ---- | ------------------------------------------------ | ------------------ |\\n| `charge` | βˆ’1 | An installment billed by a plan assignment | the assignment |\\n| `credit` | +1 | Money received, against one named charge | the charge paid |\\n| `reversal` | +1 | A `charge` or `refund` entered in error, undone | the undone line |\\n| `refund` | βˆ’1 | Money handed back, against one named payment | the credit returned |\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge) - SUM(refund)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer. A\\n*negative* balance means the family owes the school; a positive one is money on\\naccount.\\n\\n- **A payment names the charge it settles.** `POST /payments/credits` takes\\n `{charge_id, amount_minor, method?, note?}`: allocation is *recorded*, never\\n inferred from a balance, so a statement can say which installment is still\\n open rather than only how much is outstanding. **Partial payments are the\\n norm** β€” several credits accumulate against one charge.\\n- **A refund names the payment it returns.** `POST /payments/refunds` takes\\n `{credit_id, …}`, partials allowed, capped by what that credit was worth.\\n This is also the **only** way a mistaken credit is corrected: a credit is\\n never reversed, so money leaving the school is always spelled the one way.\\n- **A retry is not a second payment β€” when the client says so.** Both routes\\n take an optional `request_key` (`[A-Za-z0-9-]`, 1 to 64 characters β€” `_` is\\n the separator inside a ledger id, so a key may not carry one). With\\n one, the line is keyed `<charge>_k_<key>` (a refund: `<credit>_kr_<key>`), so\\n a client retrying after a network timeout gets **the line the first attempt\\n wrote**, not a second charge on the family β€” idempotence by identity, the\\n same rule that keeps a replayed assignment from billing twice, never a \\"has\\n this been recorded yet?\\" scan two concurrent requests can both walk past. The\\n replay is answered **before** the over-payment cap is consulted, so a payment\\n that filled its charge to the penny still replays as itself instead of coming\\n back \\"already paid in full\\". Sending that key again with a **different**\\n `amount_minor` or a different target is a `409`, never the stored line: that\\n is a client bug, and a `201` would bury it. Omit the key and nothing changes\\n from before β€” two identical posts are two payments, which is exactly what a\\n desk taking the same amount twice means.\\n- **A reversal only undoes a `charge` or a `refund`**, for its exact amount and\\n nothing else (`400` on any other kind). It is keyed `<line>_r`, so a line has\\n at most one reversal however often the call is retried, and the reversed line\\n itself stays on the record beside it.\\n- **A refund frees the charge's room.** The cap on a payment is folded over the\\n target's whole source subtree, so refunding a payment gives that charge its\\n room back and the charge **can be paid again** β€” and reversing that refund\\n takes the room back with it. Money that came back out is not money the school\\n still holds.\\n- **The over-payment cap is not the database's.** The `409` past a charge's or\\n a credit's worth is a cross-record fold, which SurrealDB cannot enforce on\\n its own; it holds because the backend is one process and the fold, and the\\n append it authorizes, are taken under one lock. Should an over-payment ever\\n be recorded anyway it is not a crisis: this is human data entry at an office\\n desk, the outcome is an over-paid charge that is plainly visible in the\\n statement, and it is undone by appending a refund. Both lines are true\\n records of money that really arrived β€” refusing them would be the worse lie.\\n- **There is no payment gateway and no card data, ever**, and none is planned:\\n nothing here talks to a bank, a PSP, or a card network. `method` is free text\\n (\\"cash\\", \\"havale\\", …) describing how money that already arrived was handed\\n over, and `note` is whatever the office needs to remember (a receipt number,\\n say).\\n\\n### Statements, balances and `overdue`\\n\\n`GET /payments/ledger/{user}` is the raw lines, newest first, paged.\\n`GET /payments/statement/me` and `/payments/statement/{user}` are the\\n**per-charge rollup** (its rows paged by the usual opt-in `?limit=&offset=`,\\nin an `entries: {items, total, limit, offset}` envelope): one row per charge with its plan, the installment's\\namount and due date, what it collected, what went back out, what is still\\noutstanding, whether the charge itself was reversed (such a charge owes\\nnothing), and whether it is **`overdue`** β€” still owed, and its `due_at` has\\npassed.\\n\\nAll of that is folded from the raw lines **on every request and stored\\nnowhere**, `overdue` included. Paging windows the *returned rows* only, after\\nthat fold: `balance_minor` β€” and every row's own arithmetic β€” is identical on\\nevery page, because it is read from all of the student's lines either way. There is no overdue flag, no sweep that sets\\none, and no stored rollup: a stored rollup is a second version of the truth,\\nand the ledger is the first. `GET /payments/balance/me` and\\n`/payments/balance/{user}` are the same fold reduced to one number.", "source": "README.md"}, {"id": "exam-modes-attempts-retakes-rejoin-live-monitoring", "title": "Exam modes, attempts, retakes, rejoin & live monitoring", "body": "Preparing an exam is slow work, so an exam can be created as a **draft**\\n(`draft: true`): only the course's managers see it (to students it's a `404`\\nthat might as well not exist β€” lists, direct reads, and attempts all hide\\nit), nobody can sit it, and grading it is a `409`. The teacher builds the\\nquestions in peace and publishes with `PATCH /exams/{id}` `{\\"draft\\": false}`.\\nAn exam can go back into hiding the same way β€” but only while it has **no\\nattempts and no results**; after that, re-drafting is a `409` (students never\\nlose sight of an exam they've sat or been graded on). Existing exams (and\\nthose created without the flag) are published from the start.\\n\\nSeparately from drafts, a published exam without a `mode` (all schedule\\nfields `null`) is **offline-graded** β€” a paper exam whose marks are entered\\nby hand; students see it and their marks, but attempts on it are a `409`\\n(\\"nothing to sit\\"). Making an exam sittable means giving it a `mode`, as one\\nconsistent unit (validated together on create and after every `PATCH` merge):\\n\\n- `mode: \\"sync\\"` + `starts_at` + `ends_at` β€” everyone sits inside one window;\\n every attempt's deadline is `ends_at`.\\n- `mode: \\"async\\"` + `starts_at` + `ends_at` + `duration_ms` β€” each student\\n starts anywhere inside the window and gets\\n `min(started_at + duration_ms, ends_at)` as their personal deadline.\\n- `mode: \\"open\\"` β€” no window at all: students sit anytime. `duration_ms` is\\n *optional* β€” set it for a per-attempt countdown (`started_at +\\n duration_ms`), omit it for unlimited time (the attempt only ends by\\n submission).\\n- `duration_ms` is 1 minute to 24 hours wherever it appears, and for `async`\\n cannot exceed the `starts_at`..`ends_at` window (equal to it is fine).\\n `ends_at` must be strictly after `starts_at`, and neither may be *set* in\\n the past β€” on create or `PATCH` (kept values are exempt, so a running exam\\n stays editable). All instants are the usual UTC unix-milliseconds, judged\\n only by the server clock (`GET /time` for sync).\\n\\nTwo per-exam policy knobs ride along, both **live-editable** at any point:\\n\\n- `max_attempts` (default `1`, `0` = unlimited) β€” how many sittings each\\n student gets. Raising it mid-exam grants retakes on the spot; lowering it\\n never kills a running attempt, it only blocks future starts.\\n- `allow_rejoin` (default `true`) β€” whether a student who *left the exam room*\\n may come back in and keep answering (see the exam-room section).\\n- `allow_review` (default `false`) β€” opt-in door to the student self-review\\n reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A\\n student may review only when this is on **and** the teacher has marked them\\n (an `ExamResult` row exists); own-scoped, so no student reads another's sheet.\\n\\nA student **sits** an exam through attempts (sitting 1, 2, … β€” each row id is\\nthe composite `exam_user[_seq]` key, so a sitting exists at most once by\\nconstruction):\\n\\n- `POST /exams/{id}/attempt` starts, resumes, or retakes (students only β€”\\n staff never sit; enrolled; window open where one exists β€” `open` exams start\\n anytime). While the latest\\n sitting runs, re-posting returns it unchanged (`200`, not `201`):\\n reconnecting never resets the clock. Once it is submitted or expired,\\n re-posting mints the next sitting (`201`) **from a blank answer sheet** β€”\\n the previous sitting's answers are wiped β€” until `max_attempts` is spent\\n (`409` after that). Starting is the live-attendance signal.\\n- `GET /exams/{id}/attempt` is the student's exam screen: the latest sitting's\\n `status` (`in_progress` | `submitted` | `expired`), `attempt` (its number),\\n `attempts_used`/`max_attempts`, `deadline`/`remaining_ms` (`null` for an\\n untimed open exam), `left_at`, own `mark` once graded, and the server `now`.\\n- `POST /exams/{id}/attempt/finish` submits. After the deadline the attempt is\\n `expired` β€” a valid terminal state (the student used their full time), and\\n finishing answers `409`. Grading stays per exam+user (one mark), whatever\\n the sitting count β€” the sheet a grader sees is always the latest sitting's.\\n\\nDeadlines are **recomputed from the exam's current schedule on every read**,\\nnever stored: a teacher who `PATCH`es `ends_at` (or a `duration_ms`)\\nwhile the exam runs moves every running deadline instantly. What's frozen once\\nanyone has started is only `mode` (including back to unscheduled) β€” swapping\\nthe deadline rules mid-sitting would be a different exam (`409`).\\n\\nThe course's manager (its creator, or manager+) watches it all live:\\n`GET /exams/{id}/live` returns one snapshot β€”\\nthe enrolled roster joined with attempts and marks (`not_started` | `absent` |\\n`in_progress` | `submitted` | `expired`, per-student `attempt` /\\n`attempts_used` / `left_at` / `deadline` / `remaining_ms` / `mark`, always the\\nlatest sitting) plus summary counts, all judged at a single `now`. Once the\\nwindow closes, `not_started` hardens into `absent` β€” the no-shows, flagged\\nright in the roster (open exams have no window, so never an `absent`). The\\nflag is informational: an absent student still has no mark until the teacher\\nrecords one through `POST /exams/{id}/results`. Poll `GET /exams/{id}/live` to\\nkeep a monitor current β€” attendance, ticking clocks, submissions, and marks all\\nride in each snapshot.\\n\\nDeleting an exam (or its course) cascades attempts, questions, answers, and\\nquestion + answer images (blobs included) along with results; unenrolling mid-exam\\nhides the student from the monitor roster but keeps the attempt and mark\\nrows, mirroring the marks report.\\n\\n> **Upgrading a pre-course database**: `exam` rows created before courses\\n> existed lack the now-required `course` field and will fail to deserialize.\\n> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data,\\n> backfill manually with the SurrealDB CLI (server stopped), e.g.\\n> `UPDATE exam SET course = course:<id> WHERE course = NONE;`\\n> after creating a course to attach them to.\\n>\\n> **Upgrading to the attempts/rejoin build needs nothing manual**: the boot\\n> migration backfills `max_attempts = 1`, `allow_rejoin = true`, and attempt\\n> `seq = 1` on existing rows, and swaps the single-attempt unique index for\\n> the per-sitting one. Pre-upgrade attempts keep their record ids and count\\n> as sitting #1.\\n>\\n> **Upgrading to the kind-weight build is a clean break**: weights moved off\\n> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with\\n> no data migration. A database from an older build has string kinds and a\\n> per-exam `weight` column the code no longer understands β€” delete\\n> `./data/hezarfen.db` and reboot.", "source": "README.md"}, {"id": "taking-an-exam-questions-answers-the-exam-room", "title": "Taking an exam: questions, answers & the exam room", "body": "Teachers author a question list per exam; students answer inside their\\nattempt, autosaved as they go; choice questions are machine-checked as a\\n**suggestion** β€” the final mark stays a human call through the existing\\n`POST /exams/{id}/results`.\\n\\n**Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`,\\ncourse-management rights): each has a mandatory `subject_id` (one of the\\ncourse's subjects, `GET /courses/{id}/subjects` β€” the topic the question\\nbelongs to), `text` (≀ 2000 chars), `points` `1`–`100`\\n(its share of the auto-score), and a `kind`:\\n\\n- `kind: \\"choice\\"` β€” carries `choices` (2–10 options, each ≀ 500 chars) and\\n `correct`, the zero-based index of the right option. Auto-scorable.\\n- `kind: \\"text\\"` β€” free text, judged by the grader; carries neither.\\n\\nThe kind bundle is validated as a unit (create and after every `PATCH` merge):\\nswitching a question to `text` needs explicit `\\"choices\\": null, \\"correct\\":\\nnull`, switching to `choice` must bring both along. Presentation order is\\ncreation order. The whole list **freezes once anyone has started an attempt**\\n(`409` on create/edit/delete) β€” editing questions under a sitting student\\nwould fork what \\"the exam\\" means. Deleting a question cascades its answers\\nand images.\\n\\n**Question images**: any question may carry one **illustration** (`POST\\n/exams/{id}/questions/{qid}/image` β€” the map the prompt asks about, on\\n`choice` and `text` questions alike), and each option of a `choice` question\\nmay carry a **picture** of its own (`POST .../choices/{choice_id}/image` β€” so\\nthe options themselves can be images: four map crops, pick the right one).\\nUploads are `multipart/form-data` with a single `file` part, capped by the\\nschool's `max_file_bytes`; the declared content type must be `image/png`,\\n`image/jpeg`, `image/webp`, or `image/gif` (rasters only β€” SVG can script,\\nand these bytes render inline for the whole class). One image per slot:\\nre-uploading replaces, `DELETE` on the same paths removes, and replacing a\\nquestion's `choices` list drops all its option pictures (the illustration\\nstays β€” re-upload against the new list). Image writes follow question\\nauthoring exactly: course-management rights, frozen once attempts exist.\\nBoth question views (`GET /exams/{id}/questions` and the sitting view)\\nembed the metadata as `image: {content_type, size} | null` and\\n`choice_images: [...|null]` aligned with `choices`; the bytes come from the\\n`GET` endpoints above β€” course managers anytime, students through the same\\nenrollment + started-attempt wall as the sitting view (no early peek at the\\npictures either), served with `Cache-Control: private, no-store`.\\n\\n**Answering** (student, attempt `in_progress`, deadline judged by the server\\nclock on every save):\\n\\n- `GET /exams/{id}/attempt/questions` β€” the sitting view. Requires\\n enrollment (`403` β€” the questions are course content, so leaving the course\\n closes them) and an attempt (`404` before `POST /exams/{id}/attempt`; also\\n the anti-peek gate), never contains `correct`, and embeds the caller's own\\n saved answer per question (`{selected, text, updated_at}` or `null`). Still\\n readable after submitting/expiry, for review.\\n- `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` β€” an\\n upsert: one row per question+user, re-answering overwrites. The payload must\\n match the question's kind (`selected` indexing a choice, or `text`\\n ≀ 10 000 chars β€” empty clears the draft); mismatches are `400`s. Requires\\n the student role and enrollment (`403`): a promotion out of `student` or an\\n unenrollment mid-exam closes the sheet (the exam room's door checks,\\n re-applied to every save β€” finishing stays open). Once the\\n attempt is submitted or past its deadline every save is a `409` β€” likewise\\n while the student has left the exam room with `allow_rejoin` off; answers\\n saved in time survive untouched for grading. Each sitting keeps its own\\n answers, drawings, and mark, keyed by the attempt's `seq` β€” a retake starts\\n from a blank sheet without erasing the prior one, so the full per-attempt\\n history stays readable (see the grading view).\\n\\n**Answer images**: the student side mirrors the teacher's question images. A\\nstudent may attach one **drawing** to any question in their attempt β€” a\\nsketched answer or worked steps β€” via `POST\\n/exams/{id}/attempt/answers/{qid}/image` (`multipart/form-data`, one `file`\\npart, the same raster allowlist and `max_file_bytes` cap as question images).\\nOne image per question: re-uploading replaces, `DELETE` on the same path\\nremoves. Writes ride the exact `POST /exams/{id}/attempt/answers` gate β€” the\\nstudent role, enrollment, an `in_progress` attempt, and the rejoin door β€” so a\\ndrawing is just another autosaved answer; a drawing-only answer (nothing\\ntyped) still surfaces, and clearing it grooms the empty row away. The bytes\\ncome from `GET` on the same path (the caller's own, behind the sitting-view\\nwall) and, for the grader, `GET /exams/{id}/attempts/{user}/answers/{qid}/image`\\n(course-management rights); both serve inline with `Cache-Control: private,\\nno-store`. The metadata rides the answer as `answer_image: {content_type,\\nsize} | null` on both the sitting view and the grading sheet. To the backend\\nit is a normal raster PNG; the frontend piggybacks its editable stroke data in\\na PNG `tEXt` chunk, opaque here β€” stored on disk under `Config::files_path`\\nby a ULID, metadata in the `answer_image` table, structurally identical to\\nquestion images.\\n\\n**Grading view** (course-management rights): `GET /exams/{id}/attempts/{user}/answers` returns\\nthe student's **latest** sitting's sheet β€” every saved answer with `is_correct`\\n(`true`/`false` for choice, `null` for text: that's the grader's call) plus\\n`auto_score: {earned, possible}` summing the choice questions' points. It is a\\nsuggestion to read while grading, never written anywhere.\\n\\n**Per-attempt history** (course-management rights): prior sittings stay\\nreadable. `GET /exams/{id}/students/{user}/attempts` lists the sitting numbers\\na student has (every `seq` carrying answers or a mark, ascending);\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers` is the grading sheet\\nfor one of them (drawing bytes at\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image`); and\\n`GET /exams/{id}/students/{user}/marks` is the full per-sitting mark history,\\noldest first. Grading (`POST /exams/{id}/results`) always lands on the current\\nsitting, and the latest seq is the grade-of-record β€” the roster, report, and\\nstatistics reads all show it. Every result payload carries its `seq`, so a mark\\nlinks straight to that sitting's answer sheet β€” without it a marked retake's\\nanswers would be unreachable from the mark.\\n\\n**The exam room (WebSocket)** β€” `GET /exams/{id}/attempt/ws`, cookie-authed\\nlike everything else; REST above remains the full fallback. Gates run before\\nthe upgrade: unknown or draft exam `404`, unscheduled (no mode) `409`, not a\\nstudent `403`, not enrolled `403`, no attempt yet `404` (start it first),\\nsubmitted/expired `409`, left while rejoin is closed `409`. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| server β†’ | `{\\"type\\":\\"state\\", status, attempt, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save |\\n| client β†’ | `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"selected\\":1}` or `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"text\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` |\\n| server β†’ | `{\\"type\\":\\"saved\\", question_id, updated_at, client_seq?}` β€” the autosave ack |\\n| client β†’ | `{\\"type\\":\\"finish\\"}` β€” submit the attempt |\\n| server β†’ | `{\\"type\\":\\"finished\\", finished_at}`, then Close |\\n| server β†’ | `{\\"type\\":\\"expired\\"}`, then Close β€” a tick noticed the deadline |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", message, question_id?, client_seq?}` β€” bad JSON, wrong kind, deadline, … |\\n\\nAn `answer` may carry a `client_seq`: any number the client picks, echoed verbatim on\\nthat message's `saved` or `error` and on nothing else. The server never reads\\nit β€” no uniqueness, no ordering, no dedupe, all the client's business β€” and\\nomits the key entirely when the request omitted it, so leaving it out keeps\\ntoday's frames byte for byte. It exists because `question_id` is not an\\nidentity: save a question, time out, save it again, and two sends are\\noutstanding for the same id β€” the first reply would settle the second and the\\nUI would claim \\"Saved\\" for an answer the server never took. `question_id` on\\nan `error` is the separate, orthogonal question: whether the failure belongs\\nto that one question (payload or question) or to the room, in which case every\\nsave in flight is equally refused. An error can carry `client_seq` without\\n`question_id`.\\n\\nEvery tick and every save re-read the exam, so a mid-exam `ends_at` extension\\nmoves the room's countdown on the next tick, and no stale socket can write\\npast its real deadline β€” the socket shares the exact REST write path. Each\\nroom acts only on the sitting it was opened for: once that sitting is over,\\nits `answer`/`finish` are `error` frames, so a lingering socket can never\\nscribble on (or instantly submit) a retake started elsewhere.\\n\\nThe room is also the presence signal behind the **rejoin door**: connecting\\nclears the attempt's `left_at`, and the *last* socket of the sitting to close\\nwhile it is still running stamps it (visible on the live monitor β€” \\"left the\\nroom three minutes ago\\" at a glance). Closing one of two tabs is not leaving,\\nand a lingering socket from an already-finished sitting never marks a later\\nretake as left β€” each room is bound to the sitting it was opened for. With the exam's `allow_rejoin` off, a stamped\\n`left_at` refuses re-entry *and* any further saves, over the socket or REST,\\nuntil the teacher flips the door back open (`PATCH /exams/{id}\\n{\\"allow_rejoin\\": true}` β€” live, like the times). Finishing stays allowed: a\\nlocked-out student can always submit what they saved. The timer never pauses\\neither way. Students who only ever use REST never trip the door β€” the room is\\nwhat marks leaving.\\nExample client:\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/exams/${id}/attempt/ws`);\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"state\\") renderCountdown(m.remaining_ms, m.answered, m.question_count);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.question_id);\\n};\\nlet clientSeq = 0;\\nconst save = (question_id, selected) =>\\n ws.send(JSON.stringify({ type: \\"answer\\", question_id, selected, client_seq: ++clientSeq }));\\n```\\n\\nThe live monitor rides along: each roster row now carries `answered` and\\n`last_activity` (latest save instant), and the snapshot a top-level\\n`question_count`, so \\"stuck at 3/10 for five minutes\\" is visible at a glance.\\nThe student's own `GET /exams/{id}/attempt` echoes the same\\n`answered`/`question_count` pair.", "source": "README.md"}, {"id": "question-bank", "title": "Question bank", "body": "Writing good questions is slow, and the same one gets asked year after year, so\\nthe school keeps a reusable **question bank**. A bank question is an\\n`ExamQuestion` cut loose from any exam: it has the same shape (`subject_id`,\\n`text`, `kind`, `points`, and β€” for a `choice` β€” `choices` + `correct`), the\\nsame image slots (one illustration, plus a picture per option), and the same\\nnewtype validation, but it carries **no exam link**. Because nothing sits it,\\na bank row **never freezes** β€” its owner can edit or delete it forever.\\n\\n`POST /bank-questions` (teacher+) saves one, stamping the caller as its\\n**owner**. `subject_id` is origin metadata, but it must **exist** β€” an unknown\\nsubject is a `400` (create and PATCH alike). The reverse guard does **not**\\nhold here, unlike exam questions and homework: a template never blocks a\\nsubject delete, which simply clears `subject` off every template that carried\\nit (only a template's owner may re-tag it, so a `409` would be one a manager\\ncould never clear β€” and a private template raising it would leak its\\nexistence). Reads are school-wide: `GET /bank-questions` lists the\\nwhole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` β€” or\\n`?owner=me` β€” by owner) and `GET /bank-questions/{bid}` fetches one with\\n`correct` included β€” any teacher+ can browse and reuse what any colleague\\nbanked. Each response carries its **image metadata** β€” an `image` meta for the\\nillustration and a `choice_images` array aligned with `choices` (per-slot\\n`{content_type, size}`, `null` where a slot has no picture) β€” the same shape an\\nexam question's response uses; the bytes still come from the image endpoints.\\nMutation is **owner-only** (an `admin` bypasses): `PATCH /bank-questions/{bid}`\\nrevalidates the kind bundle as a unit, `DELETE /bank-questions/{bid}` drops the\\nrow and its image blobs. The illustration and option pictures work exactly like\\nan exam question's β€” `POST|GET|DELETE /bank-questions/{bid}/image` and\\n`…/choices/{choice_id}/image`, `multipart/form-data` with one `file` part, raster\\nonly (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` β€” reads school-wide,\\nwrites owner-only.\\n\\nThe bank feeds exams by **copying**, never linking. `POST\\n/exams/{id}/questions/from-bank/{bid}` instantiates a bank question into the\\nexam: it mints a **fresh** exam-scoped question (new id, its own answer rows,\\nits image blobs copied to new files), so later edits on either side never\\ntouch the other. The subject on the bank row is origin metadata only β€” the\\ncall takes its own `{subject_id}`, re-checked against the target course's\\nsubjects (`400` on a cross-course subject), and instantiating into an exam\\nthat already has attempts is a `409`, the same freeze that guards hand-authored\\nquestions. The instantiated question records the template it came from in\\n`source_bank`. The reverse, `POST /exams/{id}/questions/{qid}/to-bank`, copies\\nan existing exam question **into** the bank (new detached row, images copied to\\nnew files, owner = caller); the source question is left untouched, and the new\\ntemplate records the origin exam in `source_exam`. Both provenance fields are\\nnullable β€” a hand-authored question or template carries `null` β€” and one-way\\nmetadata (the copies stay fully detached). All bank routes are course-agnostic\\nand require teacher+.\\n\\nCopying means a template edit never reaches the copies, so there is one escape\\nhatch for that divergence: `POST /exams/{id}/questions/{qid}/refresh-from-bank`\\nre-copies the template's *current* content over one exam question β€” text,\\npoints, kind, choices (adopting the **template's** choice ids, so the option\\npictures re-land on the right options), `correct`, the illustration and the\\noption pictures. The question keeps its own id, its exam, its `subject` (the\\ntemplate's is unrelated origin metadata) and its provenance links; anything\\nedited on the copy is overwritten, deliberately. A question with no\\n`source_bank` β€” hand-authored, or its template deleted β€” is a `400`, a template\\nthe caller may not see is a `404` (never a 403), and the usual freeze applies:\\nonce any attempt exists, `409`. Every source blob is read before anything is\\nwritten, so a missing blob is a `500` with the question untouched rather than a\\nhalf-applied refresh.", "source": "README.md"}, {"id": "homework", "title": "Homework", "body": "A course hands out **homework**: `POST /courses/{id}/homework` with a title,\\nan optional description, a **required subject** (one of the course's own β€” and\\nthe same delete guard questions have: a subject with homework refuses deletion\\nwith a `409` until the homework is re-tagged via `PATCH /homework/{id}` or\\ndeleted), and a **required `due_at`** that must not lie in the past (same 60s\\ngrace as every schedule field; late *submissions* are fine β€” a late\\n*assignment* is not).\\n\\n**Audience.** By default the whole course, resolved live: whoever is enrolled\\n*when they act* β€” a student enrolled after the assignment sees and submits it\\nlike everyone else. `assigned` (at create or PATCH) instead pins a named\\nsubset of currently enrolled students (at most 200). The unnamed must not even\\nlearn a subset exists: lists omit it, and direct reads and submits answer\\n`404` β€” the same no-leak a hidden exam draft gets. Narrowing the subset later\\nis refused with a `409` that names the blockers while any submission or grade\\nbelongs to a student the new list would strand.\\n\\n**Submitting.** Students only β€” staff and parents never submit β€” enrolled and\\nin the audience, re-checked on every write. A submission is optional text plus\\nup to **10 files of any content type** (each ≀ the school's\\n`max_file_bytes`): text is replaced whole on each `POST` (omit to clear),\\nfiles are added and removed one by one, and a file upload with no prior\\nsubmission auto-creates an empty one, so a photo-only homework is a single\\nrequest. Two stamps tell the lateness story: `submitted_at` pins the **first**\\nhand-in forever, `updated_at` moves on every text edit and file add/remove,\\nand `late` is **computed on read** (`updated_at > due_at`), never stored β€” so\\ntouching work after the deadline flips it late, and a `due_at` edit re-grades\\nlateness for free. Late submissions are always accepted, only flagged. File\\nbytes always come back as a forced download (`Content-Disposition:\\nattachment`): homework accepts any content type, so rendering an uploaded\\nHTML/SVG inline would run it in the viewer's session.\\n\\n**Grading.** A course manager records a status β€” `done`, `incomplete`, or\\n`missing` β€” plus an optional 0–100 `mark` per student\\n(`POST /homework/{id}/results`, one upsert row per homework+student; the\\nexam walls apply: live students only, enrolled, in the audience, never the\\ngrader themselves). A stored grade **freezes** that submission β€” text edits,\\nfile changes, withdrawal all `409` β€” until\\n`DELETE /homework/{id}/results/{user}` removes it and reopens editing.\\nGrading before the due date, or before anything was submitted, is allowed β€”\\nthe latter is how never-handed-in work gets its `missing` verdict, and\\n`GET /homework/{id}/result` is where its student reads it (their submission\\nendpoints have nothing to show). The teacher-set `missing` **status** is a\\ndeliberate verdict; the roster and the report *also* compute a `missing`\\n**flag** for anyone unsubmitted past due β€” the two are independent. Homework\\nmarks stay out of `/marks`: the weighted course average remains exam-only\\n(the exam *kind* named `homework` still lives there), so nothing\\ndouble-counts.\\n\\n**Roster & report.** `GET /homework/{id}/submissions` (course manager) is the\\ngrading table: one row per audience student β€” plus any straggler outside the\\naudience who still owns a submission or grade (an unenrollment, a promotion,\\nor an audience change leaves work behind; it stays visible, flagged\\n`unenrolled`, though a stale student can neither submit nor be graded).\\n`GET /homework/report/{user}` is the fourth observer read beside marks,\\nattendance, and pomodoro: teacher+ (an exactly-teacher caller narrowed to the\\ncourses they manage), or a **parent linked** to the student β€” per-homework\\nrows of submitted/late/missing plus the grade; statuses and marks only,\\n**never the files**.\\n\\nEvery delete collects its garbage: withdrawing a submission, deleting a\\nhomework, and deleting the whole course each cascade the rows (submissions,\\nfiles, grades) and unlink the file blobs from disk. Role changes never sweep\\nhomework rows: a promoted student's work stays readable on the roster behind\\nthe `unenrolled` flag, while the live-role gates refuse fresh edits and\\ngrades.", "source": "README.md"}, {"id": "lesson-sessions-roll-call-the-work-log-pomodoro-attendance-reports", "title": "Lesson sessions, roll call, the work log, pomodoro & attendance reports", "body": "Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session\\nbelongs to a course and carries a `teacher` (defaults to whoever creates it;\\nany explicit `teacher_id` must hold teacher+ β€” a student cannot teach), an\\noptional `topic`, a required `starts_at`, and an optional `ends_at` (when both\\nare set, `ends_at` must not precede `starts_at`; neither may be set in the\\npast). Sessions are created, edited,\\nand deleted under course-management rights, exactly like exams; session lists\\nare ordered by `starts_at` (a timetable, not a creation log).\\n\\n**Roll call** (`/sessions/{id}/attendance`) deliberately differs from event\\nattendance: students never mark themselves. The session's teacher or a course\\nmanager marks **enrolled** students β€” only students attend classes, so a\\nnon-student or unenrolled target is a `400` β€” and the\\n**session teacher's own** presence row can only be written or removed by\\nmanager+ β€” staff presence is management's call, so a teacher can't declare\\nthemselves present. Listing the roll call follows the same rights as taking\\nit; a student reads their own tallies through the attendance report instead.\\nRe-marking overwrites: one row per session+user, by construction. Deleting a\\nsession (or its course) cascades its roll-call rows.\\n\\nThe **work log** (`/work`) is the staff timesheet, for teachers and above.\\n`POST /work/check-in` opens a stint and `POST /work/check-out` closes it, both\\nstamped by the **server clock** β€” a request never carries an instant, so a\\nwrong device clock (or a crafted request) can't forge presence. At most one\\nopen stint per user holds atomically: double check-ins and check-outs without\\nan open stint answer `409`, and a reconnecting double-click can't reset a\\nrunning clock. `GET /work/me` lists your stints newest-first (the open one has\\n`check_out: null`, closed ones a convenience `duration_ms`); manager+ reads\\nanyone's log (`GET /work/{user}`), corrects a **closed** stint's instants\\n(`PATCH /work/entries/{id}`, `409` while open β€” check out or delete instead),\\nand deletes entries.\\n\\nThe **pomodoro log** (`/pomodoro`) is the students' study-time twin of the\\nwork log. The frontend owns the timer β€” the visible countdown, the work/break\\nrhythm, the durations; the backend stores no timing policy and records only\\n**focus stints**, stamped by the server clock exactly like work stints.\\n`POST /pomodoro/start` opens a session and β€” unlike a work check-in β€” always\\nsucceeds for a student: a dangling unfinished session (a laptop closed\\nmid-timer) is **discarded and replaced**, because it recorded no focus and\\nmust not lock the student out of the next one. `POST /pomodoro/finish` closes\\nthe running session (`409` when nothing runs); breaks are never reported.\\nLogs return the usual page envelope plus `total_focus_ms`, the unpaged sum of\\nevery finished session's duration: `GET /pomodoro/me` for your own,\\n`GET /pomodoro/{user}` for teacher+ (study oversight). Only students start\\nsessions β€” pomodoro is the study tool, the work log is the staff timesheet.\\n\\n**Attendance reports** mirror the marks report: `GET /attendance/me` for any\\nlogged-in user, `GET /attendance/{user}` for teacher+ β€” narrowed to the\\ncourses the caller manages (manager+ sees every course; event tallies are\\nschool-wide either way). The report tallies event attendance and lesson roll\\ncall separately, plus a per-course breakdown:\\n\\n```json\\n{\\n \\"user\\": \\"01J…\\",\\n \\"events\\": { \\"present\\": 4, \\"absent\\": 1, \\"late\\": 0, \\"excused\\": 1, \\"total\\": 6, \\"rate\\": 0.8 },\\n \\"sessions\\": { \\"present\\": 9, \\"absent\\": 2, \\"late\\": 1, \\"excused\\": 0, \\"total\\": 12, \\"rate\\": 0.8333 },\\n \\"courses\\": [ { \\"course\\": { \\"id\\": \\"01J…\\", \\"title\\": \\"algebra\\", … }, \\"counts\\": { … } } ]\\n}\\n```\\n\\n`rate = (present + late) / (present + absent + late)`: arriving late still\\ncounts as attending, and an excused absence counts against no one (`rate` is\\n`null` when every row is excused, or there are none). Per-course blocks appear\\nfor every course the user has roll-call rows in β€” attendance is a historical\\nrecord, so unenrolling hides marks from the marks report but never hides an\\nabsence.", "source": "README.md"}, {"id": "quick-tour-curl", "title": "Quick tour (curl)", "body": "```sh\\nBASE=http://127.0.0.1:8080\\nJAR=/tmp/hz.cookies\\n\\ncurl -s $BASE/auth/register -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\ncurl -s -c $JAR $BASE/auth/login -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\n# notes\\ncurl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"first\\",\\"content\\":\\"hello\\"}'\\ncurl -s -b $JAR $BASE/notes\\n\\n# note files (multipart; -F sets filename + content type from the file)\\nNO=$(curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"with file\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nFI=$(curl -s -b $JAR $BASE/notes/$NO/files -F 'file=@plan.pdf' \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/notes/$NO/files # list metadata\\ncurl -s -b $JAR -OJ $BASE/notes/$NO/files/$FI # download, original filename\\n\\n# events + attendance\\n# Creating events needs teacher+; grant it first (see \\"Bootstrapping\\" above β€”\\n# e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403.\\nEV=$(curl -s -b $JAR $BASE/events -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"standup\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json' \\\\\\n -d '{\\"status\\":\\"present\\"}'\\ncurl -s -b $JAR $BASE/events/$EV/attendance\\n\\n# courses + weighted marks (as a teacher)\\n# optional, manager+: weigh midterms triple β€” school policy, per kind\\ncurl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \\\\\\n -d '{\\"exam_kinds\\":[{\\"name\\":\\"midterm\\",\\"weight\\":3},{\\"name\\":\\"quiz\\",\\"weight\\":1}]}'\\n# find the student to enroll (here: a registered user \\"veli\\"): fragment\\n# search over username/name, role-narrowed (teacher+)\\nSID=$(curl -s -b $JAR \\"$BASE/users/search?q=vel&role=student\\" \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nCO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"algebra\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\nEX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"midterm\\",\\"kind\\":\\"midterm\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"mark\\\\\\":90,\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\ncurl -s -b $JAR $BASE/exams/$EX/statistics\\n\\n# lesson sessions + roll call (course manager creates; the session's teacher\\n# or a course manager marks enrolled students)\\nSE=$(curl -s -b $JAR $BASE/courses/$CO/sessions -H 'content-type: application/json' \\\\\\n -d '{\\"topic\\":\\"limits\\",\\"starts_at\\":1900000000000}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/sessions/$SE/attendance -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"status\\\\\\":\\\\\\"present\\\\\\",\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\n\\n# staff work log (instants are server-stamped)\\ncurl -s -b $JAR -X POST $BASE/work/check-in\\ncurl -s -b $JAR -X POST $BASE/work/check-out\\ncurl -s -b $JAR $BASE/work/me\\n\\n# ...and as the student:\\ncurl -s -b $STUDENT_JAR $BASE/marks/me\\ncurl -s -b $STUDENT_JAR $BASE/attendance/me\\n# pomodoro: start when the timer starts, finish when it rings\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/finish\\ncurl -s -b $STUDENT_JAR $BASE/pomodoro/me\\n```", "source": "README.md"}, {"id": "ai-bridge-quic", "title": "AI bridge (QUIC)", "body": "The AI features are separate projects β€” separate repos, separate processes,\\nprobably not Rust. They talk to this backend over a QUIC bridge rather than\\nHTTP.\\n\\nWhy QUIC: stream multiplexing lives in the transport. Each request rides its\\nown **bidirectional stream** on the service's single long-lived connection, so\\nconcurrent requests need no correlation-id bookkeeping and never head-of-line\\nblock each other β€” a 30-second inference on one stream does not delay the\\nanswer on another. Connection setup (and the TLS handshake) happens once, not\\nper request.\\n\\n**The backend listens; the services dial in.** A service can therefore sit\\nbehind NAT, restart without the backend knowing its address, and scale out by\\nopening a second connection β€” each connection is an independent worker.\\n\\nOff by default: with `AI_QUIC_ADDR` unset the bridge never starts and the rest\\nof the API is unaffected.\\n\\n### Handshake\\n\\nThe service connects with ALPN `hab/1`, then opens the **control stream** (the\\nfirst client-initiated bidi stream) and writes one `Hello`:\\n\\n```json\\n{ \\"protocol\\": \\"hab/1\\", \\"service\\": \\"ocr\\", \\"capabilities\\": [\\"ocr.extract\\"],\\n \\"token\\": \\"<AI_SHARED_TOKEN>\\", \\"max_concurrent\\": 8 }\\n```\\n\\nThe backend answers one `Greeting` and leaves the stream open:\\n\\n```json\\n{ \\"type\\": \\"welcome\\", \\"worker_id\\": \\"01J...\\", \\"protocol\\": \\"hab/1\\" }\\n{ \\"type\\": \\"rejected\\", \\"code\\": \\"unauthorized\\", \\"message\\": \\"invalid token\\" }\\n```\\n\\nReject codes: `unsupported_protocol`, `unauthorized`, `no_capabilities`,\\n`malformed`. The token is compared in constant time; the handshake must\\ncomplete within 10s.\\n\\nThe control stream carries no further frames. **Its closure is the goodbye** β€”\\nthere is no heartbeat. A service that dies silently is dropped by the QUIC idle\\ntimeout (30s, with a 10s keepalive) and deregistered then.\\n\\n`max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests\\nbeyond it are refused with \\"busy\\" rather than queued.\\n\\n### Requests\\n\\nFor each request the **backend** opens a bidi stream, writes one `Request`,\\nfinishes its send side, and reads one `Response`:\\n\\n```json\\n{ \\"id\\": \\"01J...\\", \\"capability\\": \\"ocr.extract\\", \\"deadline_ms\\": 30000,\\n \\"payload\\": { \\"image\\": \\"<base64>\\" } }\\n```\\n\\n```json\\n{ \\"status\\": \\"ok\\", \\"id\\": \\"01J...\\", \\"payload\\": { \\"text\\": \\"...\\" } }\\n{ \\"status\\": \\"err\\", \\"id\\": \\"01J...\\", \\"code\\": \\"unsupported_image\\",\\n \\"message\\": \\"only png and jpeg\\" }\\n```\\n\\n`id` is a trace id for logs on both sides β€” correlation is the stream, not the\\nid. It must still be echoed: an answer carrying a different id means the\\nservice lost track of whose work it is, and the payload is refused. `payload`\\nis opaque to the transport; its shape belongs to the capability.\\n\\n`deadline_ms` is when the backend gives up. A service should abandon the work\\nrather than answer late. A handled failure is an `err` frame; a crash is just a\\ndropped stream.\\n\\n### Framing\\n\\n`u32` big-endian byte length, then that many bytes of JSON. One frame per\\nmessage. The length is validated against the 8 MiB cap **before** any buffer is\\nallocated. JSON rather than a binary codec so a service in any language can\\nspeak it in ~20 lines.\\n\\n### Routing\\n\\nRequests route by exact capability string to the **least-loaded** worker\\noffering it (ties broken by worker id). Least-inflight rather than\\nround-robin because AI request costs are wildly uneven β€” round-robin would\\npile a second long inference onto a busy worker while an idle one sits next\\nto it. Selection and the in-flight increment happen under one lock, so\\nconcurrent dispatches cannot overshoot `max_concurrent`.\\n\\nFailure modes the caller sees: `NoWorker` (nothing registered β€” retryable),\\n`Busy` (all at capacity β€” retryable), `Timeout` (may still be running on the\\nfar side, so it promises nothing), `Remote` (the service's considered no β€”\\nnot retryable), `Protocol` / `IdMismatch` (broken peer), `Transport`.\\n\\n### Conformance suite\\n\\n`tests/ai_protocol.rs` is the wire contract, enforced on every `cargo test`. It\\nspeaks `hab/1` with a client that imports none of the crate's protocol types β€”\\nframes built as byte literals, answers parsed as untyped JSON β€” so it fails on\\nexactly the changes a service in another language would notice: a renamed\\nfield, a re-tagged enum, a flipped length-prefix endianness, a newly-required\\n`Hello` field. (`tests/ai_bridge.rs` drives real QUIC clients too, but shares\\nthe Rust structs with the backend, so it cannot see those.)\\n\\nIt is also the reference implementation: its `raw` module is the whole client\\nside of the protocol in about a hundred lines β€” handshake, framing, request\\nloop β€” and is the shortest thing to port when writing a new service.\\n\\nGuarantees it pins beyond the frame shapes: unknown fields in `Hello` and in a\\nresponse are accepted (a newer service may run against an older backend);\\npayloads pass through byte-for-byte whatever their JSON shape; request ids are\\nunique; answers may come back in any order; a service that drops one request\\nstream fails only that request; a service that ignores `deadline_ms` finds its\\nstream torn down rather than delivering a late answer.\\n\\n### TLS, auth & finding the certificate\\n\\nQUIC has no plaintext mode. With `AI_TLS_CERT`/`AI_TLS_KEY` unset, a\\nself-signed certificate is generated at boot and its sha256 fingerprint logged\\nβ€” services pin that instead of installing a CA. The certificate authenticates\\n*the backend*; the shared token in `Hello` authenticates *the service*.\\n\\nSo a service does not have to be handed a file out of band, the certificate is\\npublished over HTTP:\\n\\n```\\nGET /ai/certificate # no auth; 404 when the bridge is disabled\\n{ \\"protocol\\": \\"hab/1\\",\\n \\"certificate_pem\\": \\"-----BEGIN CERTIFICATE-----\\\\n...\\",\\n \\"fingerprint_sha256\\": \\"6745e8...\\" }\\n```\\n\\nUnauthenticated on purpose: a server certificate is handed to every peer during\\nthe TLS handshake anyway, so publishing it discloses nothing. The private key\\nnever leaves the process, and the shared token β€” the thing that actually\\nauthenticates a service β€” is *not* served here.\\n\\n**A service must re-fetch this on every reconnect, not once at startup.** With\\nno PEM pair configured the bridge re-selfsigns at each boot, so a certificate\\npinned once goes stale the moment the backend restarts; a reconnect loop that\\nonly redials would then fail forever. The service startup sequence is: `GET\\n/ai/certificate` β†’ trust that PEM β†’ dial QUIC β†’ `Hello` β†’ serve; on any\\nconnection loss, start again from the fetch.\\n\\nNote what this is not: fetch-then-pin over plain HTTP is trust-on-first-use,\\nonly as trustworthy as that HTTP hop. On an untrusted network set\\n`AI_TLS_CERT`/`AI_TLS_KEY` to a real certificate and distribute it out of band\\nβ€” the endpoint then simply serves that, stable across restarts.", "source": "README.md"}, {"id": "chatbot", "title": "Chatbot", "body": "Every signed-in user β€” `parent` included β€” keeps private threads with an\\nAI service. The backend is a **relay**: it owns auth, the limits, the thread,\\nthe payload format, and the last look at the answer before anyone sees it; the\\nwords are the service's. There are deliberately **no rule, intent or\\ncanned-answer tables** β€” the thread is free-form, and a school that wants\\ndifferent behaviour changes its AI service, not this backend. A thread is\\nprivate to its owner: no teacher, no admin, nobody reads someone else's, and\\nanother user's thread is a `404`, never a `403`.\\n\\n### Sending is two-phase, and that is the point\\n\\n`POST /chatbot/threads/{id}/messages` answers `202 {message_id, status:\\n\\"pending\\"}` instead of the answer, because an inference outlives a normal\\nrequest (and the request-timeout layer that guards every handler). Before the\\nAI is even called, two rows are written: the user's turn, and an **empty\\n`pending` assistant row** β€” `message_id` is that row. That order is the whole\\ndesign: a reload, a dropped connection, a closed laptop can no longer lose an\\nanswer, because the place it will land already exists and the answering task\\noutlives the HTTP request.\\n\\nThe client then reads that row either way it likes:\\n\\n- **poll** `GET /chatbot/threads/{id}/messages/{mid}` β€” `pending` until it\\n settles, then `complete` with `content` or `failed` with `error_code`;\\n- **stream** `GET /chatbot/threads/{id}/messages/{mid}/stream` β€” the same\\n row over Server-Sent Events.\\n\\nBoth read the same row, so they can never disagree, in any state.\\n\\n### The SSE stream\\n\\n```\\nevent: delta\\ndata: {\\"text\\":\\"Newton'un ikinci yasasΔ± \\"}\\n\\nevent: delta\\ndata: {\\"text\\":\\"kuvvet ile ivme arasΔ±ndaki …\\"}\\n\\nevent: done\\ndata: {\\"message\\":{ …the message DTO… }}\\n```\\n\\nOne to eight `delta` events, then exactly one `done` carrying the finished\\nmessage; or, if the turn failed, a single `error` event\\n(`{\\"code\\":\\"timed_out\\",\\"message\\":\\"…\\"}`) and nothing else. Then the stream\\ncloses. A stream opened *after* the answer already landed still emits\\n`delta`s and a `done` β€” the replay is deliberate, so a client that connects\\nlate (or reconnects) never hangs waiting for events that already happened.\\n\\n**The deltas are sliced by the backend from the finished answer.** `hab/1` is\\nunary β€” the service returns the whole reply text, not tokens β€” so today the\\nchunking is cosmetic pacing, not real streaming. The event shape exists now so\\nthat the day a service streams, it becomes a drop-in change behind an\\nunchanged frontend.\\n\\n### The message DTO\\n\\n```json\\n{ \\"id\\": \\"01J8…\\", \\"thread_id\\": \\"01J8…\\", \\"role\\": \\"assistant\\",\\n \\"status\\": \\"complete\\", \\"content\\": \\"…\\", \\"truncated\\": false, \\"error_code\\": null,\\n \\"created_at\\": 1761820800000, \\"completed_at\\": 1761820803120 }\\n```\\n\\n`role` is `user` or `assistant`; `status` is `pending`, `complete`, or\\n`failed` (a user turn is always `complete`). `content` is empty while pending,\\n`error_code` is set only when failed, `completed_at` is `null` until the turn\\nsettles. `truncated` is `true` when `content` is only the first part of what\\nthe assistant answered β€” the rest was over `max_chatbot_message_len` and was cut;\\nit is always `false` for a user turn and for a failed one. Show it: a clipped\\nanswer that looks whole is worse than one the reader knows is clipped. The same\\nDTO is what the SSE `done` event carries, so the streaming and polling reads\\nagree about `truncated` exactly as they do about every other field.\\n\\n### Status codes\\n\\n| code | when |\\n| --- | --- |\\n| `202` | the turn was accepted; the answer is on its way |\\n| `400` | empty message, or longer than the school's `max_chatbot_message_len` |\\n| `404` | no such thread or message β€” or not the caller's |\\n| `409` | already at `max_chatbot_threads`; delete a thread first |\\n| `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |\\n| `503` | no connected service offers `chat.reply` β€” **nothing was written**, retry later |\\n\\nThe `503` ordering matters: availability is checked before the rows exist, so\\nan unavailable service leaves no dead `pending` row behind, and the rate limit\\nis charged before that, so a refused turn leaves no trace at all. The check is\\nthe backend's own worker registry, which owns the QUIC sockets and is therefore\\nthe whole truth about what can be answered.\\n\\n### A turn always settles\\n\\nOnce the two rows exist the answer never stays `pending` forever, through\\nthree independent mechanisms:\\n\\n- the task that owns the bridge round trip stamps `complete` or `failed` β€”\\n the normal path;\\n- a reader **projects** a `pending` row older than 300 seconds as\\n `failed`/`timed_out` (a read-time projection, not a write β€” the row is left\\n for the task that may still own it);\\n- a **boot sweep** flips every leftover `pending` past the 300-second horizon\\n to `failed`/`interrupted`, which is what a process death mid-inference looks\\n like. Younger rows are left alone, since one may still be in flight.\\n\\nA restart therefore loses a turn that was in flight: it settles\\n`failed`/`interrupted` rather than being answered. Accepted β€” the backend is a\\nsingle process with stop-the-world deploys, so there is no peer that could have\\ntaken it over.\\n\\nTwo more verdicts come from inspecting the answer: an **empty** reply is\\nreported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a\\nbug), and an **over-long** one is truncated to `max_chatbot_message_len` β€” a\\nclipped answer still helps, a discarded one does not β€” with `truncated: true`\\non the stored turn, so the clip is never passed off as the whole answer.\\n\\n`error_code` values a client may see: `unavailable` (no worker, or the bridge\\nis off), `busy`, `timed_out`, `transport`, `protocol`, `bad_reply` (the\\nservice's payload did not parse), `empty_reply`, `service_error`,\\n`interrupted`, `not_found`, `internal` β€” **or a code the AI service itself\\nreturned**, verbatim. Treat it as an open set: branch on the ones you handle,\\nfall back to the human-readable text for the rest.\\n\\n### The `chat.reply` capability (for AI-service authors)\\n\\nA chat service declares `chat.reply` in its `Hello` (see \\"AI bridge (QUIC)\\").\\nRequests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:\\n\\n```json\\n{ \\"message\\": \\"and the second law?\\",\\n \\"history\\": [ {\\"role\\":\\"user\\",\\"content\\":\\"what is the first law?\\"},\\n {\\"role\\":\\"assistant\\",\\"content\\":\\"an object at rest …\\"} ] }\\n```\\n\\n`history` is **oldest first** (index 0 is furthest back), optional (absent or\\n`[]` = a fresh thread), and **excludes** the new message β€” that one is\\n`message`. It carries the last `chatbot_history_turns` **settled messages** β€”\\nentries, not exchanges: the default `10` is five question/answer pairs, and\\n`history` is exactly that many entries long whenever the thread holds enough\\nof them. Only settled turns count: a failed answer is skipped and the window\\nreaches further back for a usable one, rather than coming up short. All of it\\nis re-sent on every request, which is why the service may be stateless: it can\\nrestart, scale out, or be replaced mid-thread without losing context.\\n\\nThe answer is a `Response::Ok` whose payload is:\\n\\n```json\\n{ \\"text\\": \\"the complete reply, not chunked, not partial\\" }\\n```\\n\\nFailures reuse the existing `Response::Err {code, message}` β€” one failure\\nshape on the bridge for every capability β€” and that `code` reaches the client\\nas the message's `error_code`.\\n\\n**Unknown extra keys are ignored on both sides, on purpose.** A service may\\nadd fields (a model name, token counts) and a future backend may send more\\ncontext without either end having to be redeployed in lockstep.", "source": "README.md"}, {"id": "collaborative-whiteboard", "title": "Collaborative whiteboard", "body": "A board is a shared canvas whose membership is an **ad-hoc invite list**: the\\ncreator names participant user ids at `POST /boards` and that is the whole\\nmodel β€” no course, no lesson session, no appointment. Any signed-in account\\n(a `parent` included) may open one. **Every participant draws; the creator\\nalone clears, locks, closes or deletes.**\\n\\n**Two doors, two statuses.** A caller who is not on a board gets a `404` on\\nevery route, its existence included β€” an outsider must never learn a board is\\nthere. A participant who is not the creator has already been told it exists, so\\nthe four creator-only commands answer them a `403`: hiding it at that point\\nwould be a lie their client cannot act on. Over the socket the same refusal is\\n`error{code:\\"forbidden\\"}` and the socket **stays open** β€” someone clicking a\\nbutton they don't own must not lose the canvas they were drawing on.\\n\\n**A clear deletes nothing.** Strokes are append-only. `POST /boards/{id}/clear`\\nbumps the board's `epoch` and appends a `clear` **marker** carrying the epoch\\nit closed, that epoch's final stroke count, who cleared and when β€” so the live\\ncanvas empties while every mark ever drawn stays stored and replayable. Those\\nmarkers *are* the epoch index, which is why there is no epochs table and why\\nthe open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.\\n`DELETE /boards/{id}` is the one operation here that really destroys marks.\\n\\n**Three caps, and only one of them is terminal** (all three published at `GET\\n/limits` under `board`):\\n\\n- `max_epoch_strokes` bounds the **live** canvas β€” `epoch_stroke_count`, which\\n every clear resets. Hitting it is **recoverable**: the creator clears, the\\n history is kept, drawing resumes.\\n- `max_board_strokes` bounds the board's **lifetime** storage β€”\\n `total_stroke_count`, which never resets, because a clear keeps its history.\\n Hitting it stamps `closed_at` and the board becomes **permanently\\n read-only**: still fully readable and replayable, never deleted, and there is\\n no reopen β€” open a new board. `POST /boards/{id}/close` is the manual form of\\n the same thing, and idempotent.\\n- `max_boards_per_creator` bounds how many boards one creator holds\\n (`board_count` on the user row). Deleting a board frees a seat; closing one\\n does not β€” a closed board is still stored.\\n\\n**Two ways to read the marks, and the difference matters most to a client\\nauthor.** A socket `join` replays the **current epoch only**; history never\\nrides the socket. History is an explicit paged REST read:\\n`GET /boards/{id}/history` (the board's whole life, oldest first, `clear`\\nmarkers included, `?epoch=` for a single one) and `GET /boards/{id}/epochs`\\n(the marker index β€” enough to offer \\"replay session 3\\" without scanning the\\nlog). `GET /boards/{id}/strokes` is the current epoch over REST, the catch-up\\nand fallback path for the same canvas the socket replays β€” with one deliberate\\ndifference: the REST read is *not* filtered by kind, while the socket serves\\n`kind: \\"stroke\\"` rows only. In the steady state that is a distinction without a\\ndifference, since a marker is written with the epoch it *closed* and the open\\nepoch has none; the case where it shows is a clear landing between the board\\nread and the row read, which surfaces that epoch's closing marker in the page.\\nFor a live canvas the socket is the authority.\\n\\n**The board room (WebSocket)** β€” `GET /boards/{id}/ws`, cookie-authed like\\neverything else and, like the exam room, outside the OpenAPI spec (an upgrade\\nis not describable there); REST remains the full fallback. The gate before the\\nupgrade is the same `404` door: not a participant, no room. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| client β†’ | `{\\"type\\":\\"join\\", \\"after\\":\\"<last stroke id>\\", \\"epoch\\":3}` β€” both optional; replay the current epoch |\\n| server β†’ | `{\\"type\\":\\"state\\", board, epoch, locked, closed_at, creator, participants, now}` on connect and every `ws_tick_secs` |\\n| server β†’ | `{\\"type\\":\\"strokes\\", epoch, strokes:[{id, author, payload}]}` β€” one replay chunk, repeated until the epoch is served |\\n| server β†’ | `{\\"type\\":\\"synced\\", epoch, cursor}` β€” the replay is complete; `cursor` is what to resume from |\\n| client β†’ | `{\\"type\\":\\"stroke\\", \\"payload\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` β€” any participant |\\n| server β†’ | `{\\"type\\":\\"saved\\", id, client_seq?}` β€” your stroke landed |\\n| server β†’ | `{\\"type\\":\\"stroke\\", id, author, payload, epoch}` β€” someone *else* drew |\\n| client β†’ | `{\\"type\\":\\"clear\\"}` / `{\\"type\\":\\"lock\\", \\"locked\\":true}` β€” **creator only** |\\n| server β†’ | `{\\"type\\":\\"cleared\\", …}` / `{\\"type\\":\\"locked\\", locked, by}` β€” the canvas was emptied / drawing was paused |\\n| server β†’ | `{\\"type\\":\\"closed\\", …}` / `{\\"type\\":\\"deleted\\"}` β€” the board is finished; both end the room |\\n| server β†’ | `{\\"type\\":\\"participants\\", creator, participants}` β€” the roster changed; a socket no longer on it is dropped |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", code, message, client_seq?}` |\\n\\nA `stroke` may carry a `client_seq` exactly as an exam-room `answer` does: any\\nvalue the client picks, echoed **verbatim** on that message's `saved` or\\n`error` and on nothing else, omitted entirely when the request omitted it. The\\nserver never reads it.\\n\\n`error` codes are a closed set: `epoch_full` (the live canvas is full β€” clear\\nit and keep drawing), `board_closed` (permanently read-only), `locked`,\\n`forbidden` (a creator-only command from a participant), `resync` (below),\\n`invalid` (bad JSON, an unknown frame, an over-long payload), `not_found`,\\n`unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\n**Persist, then publish.** A stroke is fanned out only after its row has\\nlanded, so the channel can never carry a mark the database refused (a locked\\nboard, a full epoch, a closed board). The database is the canvas; the channel\\nis a notification *about* it β€” which is why a client dedupes by stroke `id`,\\nwhy a resync deliberately re-serves marks it already drew, and why a frame is\\nnever the authority: every stroke, clear and lock re-reads the board and\\nre-checks the roster, so a socket that missed a `participants` or `locked`\\nframe is refused all the same. One consequence of the same read-then-write\\nshape: a stroke carries the epoch the server read for it, so a clear landing in\\nthat instant can file one stroke under the epoch it just closed β€” the stroke is\\nkept and stays replayable in `/history`, it simply is not on the new canvas.\\n\\n**Reconnecting.** `join` carries a cursor: `after`, the last stroke id already\\ndrawn, plus the `epoch` it belongs to. Same epoch and only what is newer is\\nreplayed; an older epoch β€” or no cursor at all β€” gets a `cleared` frame first\\nand then the whole current epoch, because a cursor into a closed epoch no\\nlonger means anything. If the room falls behind a slow socket the server sends\\n`error{code:\\"resync\\"}` and immediately replays the current epoch **out of the\\ndatabase**: the client does not re-join, it throws its canvas away and takes\\nwhat follows. The database is always the source of truth, never the channel.\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/boards/${id}/ws`);\\nlet epoch = null, cursor = null, seq = 0;\\nws.onopen = () => ws.send(JSON.stringify({ type: \\"join\\", after: cursor, epoch }));\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"cleared\\") wipeCanvas();\\n if (m.type === \\"strokes\\") m.strokes.forEach(draw); // dedupe by m.id\\n if (m.type === \\"synced\\") ({ epoch, cursor } = m);\\n if (m.type === \\"stroke\\") draw(m);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.id);\\n if (m.type === \\"error\\" && m.code === \\"resync\\") wipeCanvas();\\n};\\nconst send = (payload) =>\\n ws.send(JSON.stringify({ type: \\"stroke\\", payload, client_seq: ++seq }));\\n```", "source": "README.md"}, {"id": "concurrency-model", "title": "Concurrency model", "body": "The backend runs as **one process against one database**, and that buys less\\nthan it sounds like: every request is an async task, dozens are in flight at\\nonce, and each of them awaits the database in the middle of its work. So\\n\\"read, decide, write\\" is never safe on its own β€” SurrealDB does not\\nconflict-check a cross-record `count()` against a concurrent insert\\n(write-skew), and that fires between two tasks in one process exactly as it\\nwould between two machines. The mutex-only design this replaced was already\\nlosing races at one process. Every invariant is therefore guarded where the\\ndatabase itself decides the winner. Three tiers:\\n\\n1. **Single-row conditional writes** β€” compare-and-set (`save_if_unchanged`),\\n `UPDATE … WHERE`, stored counters (`domain::cap`). A single-record write is\\n atomic, so of N concurrent tasks exactly the allowed number get a non-empty\\n result: the database decides the winner, the loser retries\\n (`CAS_UPDATE_RETRIES`) or gets a 409.\\n2. **In-transaction `IF … THROW` gates** β€” the check runs inside the same\\n statement as the write it authorizes, so it is atomic with it. Used where\\n the rule reads the row being written (state machines, delete guards).\\n \\"Is anything still attached?\\" is answered the same way, by a counter on the\\n row being deleted rather than a `SELECT` over the children: a course is\\n deletable while its `enrollment_count` is zero, a term while its\\n `course_count` is (courses claim that reference *before* they write the\\n link, and give it back when the link moves or the course is deleted). A fee\\n plan reads the same way β€” editable *and* deletable while its\\n `assignment_count` is zero, and frozen for good once it is not, since an\\n assignment is never taken back.\\n Where the child also carries a deterministic id β€” one enrollment per\\n (course, user), one registration per (event, user), one fee-plan assignment\\n per (plan, student) β€” the seat and the row\\n are claimed in one transaction (`cap::claim_and_create`), so a duplicate\\n `CREATE` rolls its own seat back instead of costing a stranger their place.\\n3. **Two accepted races**, reviewed and deliberately left open:\\n - *Attempt-seq late save* β€” an exam-room socket writes into the sitting it\\n joined with, a choice made before any lock is taken, so a save racing a\\n retake can stamp an answer onto the just-terminal previous sitting.\\n Damage: one history row; the grade of record (latest `seq`) is never\\n touched.\\n - *Approved-overlap* β€” two approvals landing in the same instant can\\n double-book a teacher. Damage: one overlapping half-hour, visible to both\\n parties, fixable by cancelling either side.\\n\\nIn-process locks remain, and they are a *second* line, never the guarantee:\\n`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional\\n-write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is\\nthe cap β€” the lock only tames the retry loop, and keeps the tests' in-memory\\nengine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in\\nfront of a rule no single-record write can express. Removing one of them costs\\nthroughput or an accepted race; removing the conditional write behind it costs\\nthe invariant.\\n\\nBoot is unconditional: the schema batches, the backfills and the admin seed all\\nrun on every start, because exactly one process ever starts. Deployment is\\nstop-the-world β€” `podman compose down` then `up`, never overlapping β€” and a\\nrelease that adds or renames a stored counter *requires* it. An old binary\\nwrites rows without touching the new counter, the `= NONE` backfill guard\\n(correctly) refuses to re-seed, and the resulting permanent under-count lets a\\nguard approve exactly what it exists to refuse. In-flight work does not survive\\na restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.", "source": "README.md"}, {"id": "layout", "title": "Layout", "body": "```\\nsrc/\\n main.rs bootstrap: config, db, router, serve\\n lib.rs build_router: routes + OpenAPI/Swagger + CORS + /health\\n config.rs env-sourced Config\\n constant.rs validation limits\\n validate.rs field validators (used by every newtype's try_new)\\n error.rs ValidationError + AppError -> HTTP responses\\n database.rs SurrealDB server connect (ws) + SCHEMAFULL migration\\n migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,\\n MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them\\n rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier\\n state.rs AppState { db, files_path, cookie_secure, rate_limit,\\n chatbot_limit, exam_presence, board_hub, db_up, ai }\\n ai/ QUIC bridge to the out-of-process AI services\\n (see \\"AI bridge (QUIC)\\"; the HTTP half is web/ai.rs)\\n protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing\\n server.rs AiBridge: listener, handshake, dispatch over per-request streams\\n registry.rs connected workers, capability routing, least-inflight leases\\n tls.rs listener certificate (PEM or self-signed) + fingerprint\\n error.rs AiError\\n chat.rs the `chat.reply` payload contract (ChatRequestPayload/ChatReplyPayload)\\n domain/ validated newtypes + entities (derive SurrealValue),\\n each owning its persistence\\n user.rs UserId Β· Username Β· Password Β· PasswordHash Β· User (has role)\\n role.rs Role enum (student < teacher < manager < admin), at_least()\\n field_update.rs FieldUpdate: one UPDATE ... SET built from only the fields a\\n PATCH actually carried (an omitted field is never written)\\n monotonic_id.rs next_ulid: ids that sort in write order β€” one process-wide\\n Generator, so same-millisecond rows never scramble\\n key.rs sitting(): the deterministic per-sitting record key shared by\\n attempts, answers, answer images and results (seq 1 stays bare)\\n cap.rs claim()/release(): the count caps the database enforces β€” an\\n atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter\\n column of the parent row, replacing count-then-write mutexes\\n that could not see a concurrent insert;\\n claim_and_create() commits that seat and the child row in\\n one transaction, for children with a deterministic id\\n text_fold.rs case- and diacritic-insensitive folding for search, shared by\\n the Rust needle and the SurrealQL column (Turkish Δ°/Δ±, ΓΌ, â…)\\n session.rs SessionId Β· SessionToken Β· Session (7-day expiry)\\n timestamp.rs Timestamp (unix-millisecond instant)\\n note.rs NoteId Β· NoteTitle Β· NoteContent Β· Note\\n note_file.rs NoteFileId Β· FileName Β· FileContentType Β· NoteFile (metadata row;\\n blob on disk under FILES_PATH, named by the row's ULID)\\n event.rs EventId Β· EventTitle Β· EventDescription Β· Event\\n attendance.rs AttendanceId Β· AttendanceStatus Β· Attendance\\n course.rs CourseId Β· CourseTitle Β· CourseDescription Β· Course\\n course_session.rs CourseSessionId Β· SessionTopic Β· CourseSession (a course's lesson)\\n session_attendance.rs SessionAttendanceId Β· SessionAttendance (roll call; one row per session+user)\\n work_entry.rs WorkEntryId Β· WorkEntry (staff stint; one open per user by construction)\\n enrollment.rs EnrollmentId Β· Enrollment (one row per course+user)\\n exam.rs ExamId Β· ExamTitle Β· ExamDescription Β· ExamKind Β· ExamWeight Β·\\n ExamMode Β· ExamDuration Β· ExamSchedule Β· Exam (belongs to a course)\\n exam_attempt.rs ExamAttemptId Β· AttemptStatus Β· ExamAttempt (numbered sittings per exam+user, metered by max_attempts)\\n exam_question.rs ExamQuestionId Β· QuestionText Β· QuestionKind Β· QuestionPoints Β·\\n ChoiceText Β· QuestionSpec Β· ExamQuestion (choice|text, per exam)\\n exam_answer.rs ExamAnswerId Β· AnswerText Β· ExamAnswer (one row per question+user) Β·\\n auto_score (choice-question suggestion)\\n exam_result.rs ExamResultId Β· Mark Β· ExamResult (one row per exam+user)\\n question_image.rs QuestionImageId Β· QuestionImage (question/choice picture\\n metadata; bytes on disk under FILES_PATH)\\n answer_image.rs AnswerImageId Β· AnswerImage (student answer-drawing\\n metadata; bytes on disk under FILES_PATH)\\n bank_question.rs BankQuestionId Β· BankQuestion (school-wide reusable\\n question template, copied into exams; no exam FK)\\n bank_question_image.rs BankQuestionImageId Β· BankQuestionImage (bank\\n question/choice picture metadata; bytes on disk under FILES_PATH)\\n profile.rs PersonName Β· Email Β· Phone Β· BirthDate (personal-info newtypes)\\n preferences.rs Theme Β· Language Β· PaletteColor (own UI preferences)\\n message.rs MessageId Β· MessageSubject Β· MessageBody Β· MessageLabel Β·\\n Message (per-copy folders: inbox/sent/archive/trash)\\n parent_link.rs ParentLinkId Β· ParentLink (parent↔student tie = the parent's read grant)\\n registration.rs RegistrationId Β· Registration (a seat on a registration event's signup list)\\n subject.rs SubjectId Β· SubjectName Β· SubjectDescription Β· Subject (course curriculum)\\n term.rs TermId Β· TermName Β· Term (school term window)\\n menu.rs MenuId Β· MenuDate Β· MenuSlot Β· Menu (one published menu per\\n calendar day + meal slot; slot snapshotted as text)\\n menu_dish.rs MenuDishId Β· DishName Β· DishDescription Β· DishPrice Β·\\n DishTags Β· MenuDish (a dish on a menu; price in minor units)\\n dietary_profile.rs DietaryProfileId Β· DietaryTags Β· DietaryNote Β·\\n DietaryProfile (what one student may not eat; keyed by the\\n student, tagged from the same `dietary_tags` list a dish is)\\n meal_booking.rs MealBookingId Β· MealBookingStatus Β· MealBooking (one seat\\n per (menu, student); a cancel flips the status, never deletes)\\n meal_attendance.rs MealAttendanceId Β· MealAttendanceStatus Β· MealAttendance\\n (who actually ate; one row per (menu, student), reporting\\n only β€” it never touches the ledger)\\n meal_ledger.rs MealLedgerId Β· MealLedgerKind Β· LedgerAmount Β· LedgerMethod Β·\\n LedgerNote Β· MealLedger (append-only money; the balance is\\n always the fold, never a stored field)\\n fee_plan.rs FeePlanId Β· FeePlanName Β· Installment Β· FeePlan (a school fee\\n plan; installments embedded on the row, past due dates legal)\\n fee_plan_assignment.rs FeePlanAssignmentId Β· FeePlanAssignment (one plan on\\n one student, keyed `<plan>_<student>`; assigning appends\\n every installment charge, a replay appends nothing)\\n payment_ledger.rs PaymentLedgerId Β· PaymentLedgerKind Β· PaymentLedger\\n (append-only school fees: charge/credit/reversal/refund, a\\n credit names its charge and a refund its credit; the balance\\n is always the fold; over-payment cap is advisory)\\n settings.rs ExamKindDef Β· GradeBand Β· Settings (per-school policy)\\n chatbot_thread.rs ChatbotThreadId Β· ChatbotThreadTitle Β· ChatbotThread (one\\n chatbot thread, private to its owner)\\n chatbot_message.rs ChatbotMessageId Β· ChatContent Β· MessageRole Β· MessageStatus Β·\\n ChatbotMessage (one turn; the assistant row is written\\n `pending` before the AI call and settled after)\\n board.rs BoardId Β· BoardTitle Β· Board (a collaborative whiteboard:\\n creator + ad-hoc participant list, `epoch`, the two stroke\\n counters and `closed_at`)\\n board_stroke.rs BoardStrokeId Β· BoardStroke (the\\n append-only stroke log; a `clear` row is the marker that\\n closed an epoch, carrying its final count β€” nothing is\\n ever deleted)\\n appointment_slot.rs AppointmentSlotId Β· SlotSeries Β· SlotNote Β·\\n AppointmentSlot (a teacher's published availability; a\\n recurring publish is expanded into rows sharing a series id)\\n appointment.rs AppointmentId Β· AppointmentStatus Β· AppointmentReason Β·\\n Appointment (a booking on a slot; occupancy is the slot's\\n stored `occupied` cap-1 counter, overlap is derived under\\n APPOINTMENT_LOCK)\\n pomodoro.rs PomodoroSessionId Β· PomodoroSession (student focus log)\\n pool_question.rs PoolQuestionId Β· PoolQuestionTitle Β· PoolQuestionBody Β·\\n PoolQuestion (student-asked question; teacher-approved into\\n the school-wide pool; optional photo as metadata + disk blob)\\n solution.rs SolutionId Β· SolutionBody Β· Solution (discussion thread on an\\n approved pool question; dies with the question)\\n homework.rs HomeworkId Β· HomeworkTitle Β· HomeworkDescription Β· Homework\\n (per-course assignment; required subject; optional `assigned`\\n student subset β€” absent/empty = the whole enrolled course)\\n homework_submission.rs HomeworkSubmissionId Β· SubmissionText Β·\\n HomeworkSubmission (one row per homework+user; immutable\\n submitted_at + moving updated_at β€” `late` is computed)\\n homework_file.rs HomeworkFileId Β· HomeworkFile (submission attachment\\n metadata; any content type; bytes on disk under FILES_PATH)\\n homework_result.rs HomeworkResultId Β· HomeworkStatus Β· HomeworkResult\\n (teacher grade: done/incomplete/missing + optional Mark; one\\n row per homework+user β€” its existence freezes the submission)\\n web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +\\n auth extractors\\n extractor.rs CurrentUser Β· RequireTeacher Β· RequireManager Β· RequireAdmin\\n dto.rs shared UserResponse Β· CourseResponse Β· ExamResponse Β· SessionResponse schemas\\n exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)\\n board_ws.rs the collaborative board room WebSocket (join replay, strokes\\n fanned out to every participant, clear/lock)\\n room.rs the plumbing both rooms share: sending a frame, classifying\\n an incoming message, an AppError as a readable code, and a\\n client_seq echoed untouched\\n page.rs PageParams Β· Page<T> (shared pagination)\\n etag.rs conditional-GET middleware: ETag over a 200 JSON body,\\n If-None-Match β†’ 304 (GET only; SSE and blobs pass through)\\n auth.rs users.rs notes.rs messages.rs events.rs appointments.rs\\n courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs\\n bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs\\n settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs\\n boards.rs\\n limits.rs GET /limits: every constant.rs bound served as JSON\\n```\\n\\nTests: `cargo test` β€” unit (in-source), integration (`tower::oneshot` + in-memory\\ndb), rate-limit (both tiers, proxy-header and peer-address keying, shipped\\nlimits over every route, two limiters sharing one budget over one db), e2e\\n(real TCP + reqwest cookie jar), persistence\\n(tempfile file engine, including close + reopen), ai-bridge (real QUIC on\\nloopback against a fake AI service), ai-protocol (the `hab/1` wire contract,\\ndriven by a client that shares no code with the backend).", "source": "README.md"}];
9+INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "e68a65f85e3d7ee237d59c79c8f1dca0ea1a9ed2088eeede2a6732c6294ce561"}];
10+DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii;
11+DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25;
12+DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25;
13+REMOVE TABLE IF EXISTS endpoint;
14+INSERT INTO endpoint [{"id": "health", "routes": "| GET | `/health` | no | Liveness check |"}, {"id": "root", "routes": "| GET | `/` | no | Same as `/health` |"}, {"id": "time", "routes": "| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |"}, {"id": "limits", "routes": "| GET | `/limits` | no | Every fixed validation bound, grouped by resource \\u2014 see Validation limits |"}, {"id": "swagger", "routes": "| GET | `/swagger` | no | Interactive API docs (Swagger UI) |"}, {"id": "api-docs", "routes": "| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |"}, {"id": "ai", "routes": "| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |"}, {"id": "auth", "routes": "| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken \\u2014 see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |"}, {"id": "users", "routes": "| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` \\u2014 own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) \\u00b7 paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` \\u2014 find users by username/name fragment (pickers); refs only, no contact info \\u00b7 paged |\\n| GET | `/users` | admin | List all users \\u00b7 paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` \\u2014 set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` \\u2014 tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students \\u00b7 paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |"}, {"id": "notes", "routes": "| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes \\u00b7 paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) \\u2014 \\u2264 the school's `max_file_bytes`, \\u2264 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) \\u00b7 paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |"}, {"id": "messages", "routes": "| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` \\u2014 send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` \\u2014 the caller's folder, newest first; `?folder=inbox&read=false&limit=1` \\u2192 `total` is the unread badge \\u00b7 paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` \\u2014 read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** \\u2014 only from the trash (`409` elsewhere); the row vanishes once both sides deleted |"}, {"id": "events", "routes": "| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` \\u2014 `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` \\u2014 mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) \\u00b7 paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` \\u00b7 paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` \\u2014 seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |"}, {"id": "appointments", "routes": "| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` \\u2014 publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, \\u2264 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) \\u2014 a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar \\u2014 future slots only, demoted teachers' slots left out \\u00b7 paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` \\u2014 book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests \\u00b7 paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` \\u2014 call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included \\u2014 they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` \\u2014 counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal \\u2014 this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |"}, {"id": "courses", "routes": "| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` \\u2014 `kind` is `course` (default), `study` (et\\u00fct), or `club` (kul\\u00fcp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) \\u00b7 paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses \\u00b7 paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ \\u2014 **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` \\u2014 assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` \\u2014 enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u00b7 paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` \\u2014 add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` \\u2014 add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` \\u2014 add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) \\u00b7 paged |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` \\u2014 assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, \\u2264 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) \\u00b7 paged |"}, {"id": "subjects", "routes": "| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |"}, {"id": "sessions", "routes": "| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` \\u2014 roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) \\u00b7 paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |"}, {"id": "exams", "routes": "| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist \\u2014 the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` \\u2014 grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) \\u00b7 paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt \\u2014 students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) \\u00b7 paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question \\u2014 the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam \\u2014 copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** \\u2014 copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question \\u2014 text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` \\u2014 autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers \\u22c3 marks), ascending \\u2014 the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first \\u2014 the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** \\u2014 the answer key the caller checks their own sheet against (same review gate) \\u00b7 paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers \\u22c3 marks), ascending \\u2014 only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster \\u00d7 latest attempts \\u00d7 marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |"}, {"id": "bank-questions", "routes": "| GET | `/bank-questions` | teacher | The school-wide question bank \\u2014 `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) \\u00b7 paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist \\u2014 `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question \\u2014 the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |"}, {"id": "homework", "routes": "| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) \\u00b7 paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade \\u2014 the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades \\u2014 file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` \\u2014 hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part \\u2014 **any** content type, \\u2264 `max_file_bytes`, \\u2264 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) \\u2014 the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student \\u00d7 submission/files/grade + computed `late`/`missing`/`unenrolled` \\u2014 a straggler's stale work stays visible (course manager) \\u00b7 paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` \\u2014 grade `done`/`incomplete`/`missing` (+ optional 0\\u2013100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable \\u2014 that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) \\u2014 readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade \\u2014 un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows \\u2014 submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` \\u2014 full, statuses and marks only, never files \\u00b7 paged |"}, {"id": "questions", "routes": "| POST | `/questions` | student | `{title, body}` \\u2014 ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` \\u2014 the pool questions visible to the caller, each with its `solution_count` \\u00b7 paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question \\u2014 publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` \\u2014 offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first \\u2014 a discussion thread \\u00b7 paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` \\u2014 edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |"}, {"id": "marks", "routes": "| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "work", "routes": "| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) \\u00b7 paged |\\n| GET | `/work/{user}` | manager | A staff member's work log \\u00b7 paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` \\u2014 correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |"}, {"id": "pomodoro", "routes": "| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** \\u2014 a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` \\u00b7 paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape \\u00b7 paged; *or a `parent` linked to `{user}` |"}, {"id": "attendance", "routes": "| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "settings", "routes": "| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |"}, {"id": "terms", "routes": "| POST | `/terms` | manager | `{name, starts_at, ends_at}` \\u2014 past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first \\u00b7 paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term \\u2014 `409` while any course still links to it |"}, {"id": "meals", "routes": "| POST | `/meals/menus` | manager | `{date, slot, capacity?}` \\u2014 publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range \\u00b7 paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` \\u2014 the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` \\u2014 add a dish (\\u2264 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` \\u2014 record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` \\u2014 take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first \\u00b7 paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included \\u00b7 paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` \\u2014 mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu \\u00b7 paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day \\u00b7 paged \\u00b7 own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line |"}, {"id": "payments", "routes": "| POST | `/payments/plans` | manager | `{name, installments}` \\u2014 write a fee plan (1\\u201360 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first \\u00b7 paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it \\u2014 its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (\\u2264 200) \\u2014 place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first \\u00b7 paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` \\u2014 record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` \\u2014 hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` \\u2014 undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines \\u2014 charges, payments, refunds, reversals \\u2014 newest first \\u00b7 paged \\u00b7 own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |"}, {"id": "chatbot", "routes": "| POST | `/chatbot/threads` | student | `{title?}` \\u2014 start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first \\u00b7 paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` \\u2014 rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first \\u2014 user and assistant rows alike \\u00b7 paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (\\u2264 `max_chatbot_message_len`) \\u2014 send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` \\u2014 nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` \\u2014 or one `error` \\u2014 and close; an already-finished answer replays (see \\"Chatbot\\") |"}, {"id": "boards", "routes": "| POST | `/boards` | student | `{title, participant_ids?}` \\u2014 open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first \\u00b7 paged |\\n| GET | `/boards/{id}` | student | One board \\u2014 a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first \\u00b7 paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included \\u00b7 `?epoch=` for one epoch \\u00b7 paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) \\u00b7 paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` \\u2014 re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap \\u2014 nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board \\u2014 permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |"}];
15+SELECT sha256 FROM meta:readme;
16+SELECT VALUE sha256 FROM meta:readme;
17+REMOVE TABLE IF EXISTS doc;
18+REMOVE TABLE IF EXISTS meta;
19+INSERT INTO doc [{"id": "intro", "title": "intro", "body": "# hezarfen_backend\\n\\nNote, attendance, course + weighted exam mark backend. **Rust (edition 2024) Β· axum Β· SurrealDB 3 (server, WebSocket) Β· tokio.**\\n\\nSession-cookie auth with five hierarchical roles (`parent < student < teacher\\n< manager < admin`). A **`parent`** observes and changes nothing: admins tie\\nstudents to a parent account, and the parent reads those students' mark,\\nattendance, pomodoro, and homework reports β€” that's the whole role. Notes are per-user and carry **file attachments** (PDFs, documents,\\n…): blobs live on disk next to the database, metadata in the database, and the\\nper-file size cap is school policy in settings (`max_file_bytes`, default\\n5 MiB). Any two users can **message** each other, mail-style β€” subject +\\nbody into the recipient's inbox, each side filing its own copy through\\narchive/trash with a read flag the sender sees as a receipt (one of the two\\nplaces a `parent` writes β€” whiteboards below are the other). Attendance is event + attendees: create an event with an **audience**\\n(the whole school, one role, a course's enrollment, or a **registration**\\nsignup list β€” omit for school-wide), then teachers mark the expected attendees\\npresent / absent / late / excused (students never self-mark), and a **roster\\nreport** shows who was expected and who missed. Registration lists fill seat\\nby seat: teachers register students (never the other way round), staff\\nregister only themselves, an optional `capacity` caps the seats, and the list\\ncloses the moment the event starts (or, for an event with only an end time β€”\\na pure signup deadline β€” the moment that end passes). Every event stays visible to everyone β€”\\nthe audience is a roster, not a wall. Marks are course-shaped\\n(Google Classroom style): a teacher creates a course β€” kind **`course`** (a\\nregular class), **`study`** (a supervised study session β€” *etΓΌt*), or\\n**`club`** (a student club β€” *kulΓΌp*; same behavior, different label),\\noptionally capped by a `capacity` that refuses new enrolls once the roster is\\nfull β€” lays out its **subjects** (curriculum topics β€”\\nevery exam question must be tagged with one of its course's subjects, so\\nresults can later be read per topic), enrolls students, adds\\nexams inside it, and grades β€” enrolling, sitting exams, roll call, and marks are\\nall student-only, staff never take part. A course is run by whoever created it\\nplus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`):\\nan assigned teacher manages everything inside the course β€” exams, sessions,\\nsubjects, roster, grading β€” but can't delete it or change who else teaches it,\\nand a demotion below `teacher` sweeps their assignments away. Students read a per-course weighted average and\\nan overall average from their mark report β€” each exam weighted by its **kind**\\n(midterms can count double, orals once: weights are set per kind in settings,\\nnot per exam). Exams run **sync** (one\\nfixed window), **async** (start anytime inside the window, with a personal\\ntime budget), or **open** (sit anytime, optionally timed per attempt);\\nstudents *sit* them via attempts β€” retakes metered by a per-exam limit\\n(`0` = unlimited), each sitting keeping its own answers, drawings, and mark\\nso staff can read a student's full attempt history, leaving the exam room\\ngoverned by a teacher-controlled rejoin door. Writing an exam takes a while, so it can be saved as a\\n**draft** β€” invisible to students, unsittable, ungradable β€” and published\\nwhen it's ready. Questions can carry **images**: any question may hold one\\nillustration (a map above the prompt), and each option of a choice question\\nmay be a picture of its own (pick the right city off the map) β€” raster\\nuploads capped by the same `max_file_bytes` policy as note files. Good\\nquestions get reused, so a teacher+ can bank one in a school-wide **question\\nbank** β€” detached templates (with their own images) that any teacher copies\\ninto a fresh exam question across years, editable and deletable only by\\nwhoever saved them. Teachers\\nwatch attendance, per-student remaining time,\\nsittings, walk-outs, no-shows (`absent` once the window closes), submissions,\\nand marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out\\n**homework**: assigned to the whole class or a named subset (the unnamed never\\neven see it), tagged with a course subject, due by a required future `due_at`\\nβ€” students hand in text and/or **files of any type** (same size cap, 10 per\\nsubmission, served back only as forced downloads), editable until the teacher\\ngrades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark\\n(grading freezes the hand-in until the grade is removed); lateness is computed\\nfrom two stamps (first hand-in vs last touch), never stored, and homework\\nmarks stay out of the weighted `/marks` averages. Courses also carry **lesson\\nsessions** with teacher-taken roll call (students never self-mark a lesson),\\nstaff clock in/out on a server-stamped **work log**, students track study time\\nwith a server-stamped **pomodoro log** (the timer runs in the frontend; the\\nbackend records the focus stints, and teachers can read any student's log),\\nand every user has an\\n**attendance report** (event + per-course lesson tallies with rates).\\nA school-wide **question pool** runs on moderation: a student asks a question\\n(optionally attaching one photo of the problem β€” raster only, same\\n`max_file_bytes` cap), a teacher+ **approves** it into the pool (or deletes\\nit β€” rejection is deletion, there is no rejected state), and every approved\\nquestion is readable by the whole school with anyone free to offer\\n**solutions** under it (parents stay out) β€” text plus an optional photo of\\nthe worked steps, both editable by the solution's author anytime; pending\\nquestions show only to their asker and to teacher+, and approval freezes the\\ncontent so nothing unmoderated ever reaches the pool.\\nTeachers keep an **appointment calendar**: a teacher+ publishes availability\\nslots (one-off, or repeating weekly up to an `until` date as a series that\\ndeletes as one), and students and parents book a slot with a reason β€” the\\nbooking lands `pending` until the teacher approves it, rejects it, or\\ncounter-proposes another time (which sends it back to `pending` for the\\nrequester to accept or decline); the **requester** may cancel until the meeting\\nstarts β€” a teacher ends a booking by rejecting it, or by counter-proposing and\\nthen rejecting an approved one β€” one live booking holds a slot, a teacher's own\\npublished windows may not overlap each other, and no approved meeting may\\noverlap another for the teacher or the requester (see \\"Appointments\\").\\nSchool-varying policy is data, not code: exam kinds (each with its weight in\\ncourse averages), attendance statuses, grade-display bands, the note-file\\nsize limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms**\\nare plain rows courses can link to (see \\"Per-school policy\\"). Each account\\nalso carries its own **UI preferences** β€” theme (`light`/`dark`), language\\n(`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` β€”\\nany hex, deliberately not a fixed palette) β€” self-managed, admin-editable for\\nanyone, `null` until chosen so the client can fall back to the device\\npreference (or, for the accent, its own default).\\nThe **AI features live in separate projects**, so the backend also opens a\\nQUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in,\\nregister the capabilities they serve, and each request rides its own QUIC\\nstream on that one connection β€” no correlation ids, no head-of-line blocking.\\nThe bridge's certificate is published at `GET /ai/certificate` so a service can\\npin it before dialling (see \\"AI bridge (QUIC)\\").\\nThe first thing riding that bridge is the **chatbot**: every signed-in user\\n(`parent` included) keeps private threads with an AI service, free-form β€”\\nno rule tables, no canned answers, the backend only owns auth, limits,\\npersistence and the payload format. Sending is asynchronous because an\\ninference outlives a request: the turn plus an empty `pending` answer are\\nwritten *first*, the call goes out after, so a reload never loses an answer;\\nthe client then polls the message or reads it off an SSE stream (see\\n\\"Chatbot\\").\\nAny signed-in account (a `parent` included) can also open a **collaborative\\nwhiteboard**: a titled board whose membership is an **ad-hoc invite list** β€”\\nthe creator names participant user ids, and no course, session or appointment\\nis involved. Every participant draws over a WebSocket, the creator alone\\nclears, locks, closes or deletes, and someone who is not on a board gets a\\n`404` for it on every route, existence included. Strokes are **append-only and\\na clear deletes nothing** β€” it bumps the board's epoch, so the live canvas\\nempties while every mark ever drawn stays stored and replayable through the\\nhistory reads (see \\"Collaborative whiteboard\\").\\nThe school's **food program** is published here too: a manager puts up one\\n**menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot`\\ndrawn from the school's `meal_slots`, unique per pair), lists its **dishes**\\nwith dietary tags from the school's own list, and prices them in **minor\\nunits** (kuruş) as integers β€” this API never speaks decimals or floats about\\nmoney. A student's own **dietary profile** is tagged from that same list\\n(manager-written β€” an allergen list is a school record, not a self-service\\npreference), so every dish a menu read returns names the tags it `conflicts`\\nwith for whoever is reading. Every authenticated user reads what is being\\nserved; students (or their parents) book a seat, and every seat writes a line into an\\n**append-only** meal ledger whose balance is derived and never stored (see\\n\\"Food program: menus, dishes, bookings & the ledger\\").\\nSchool **fees** are tracked the same way, in a ledger of their own: a manager\\nwrites a **fee plan** (a name and 1–60 installments, each an amount in minor\\nunits and a due date that may sit in the past) and **assigns** it to students,\\nwhich appends every installment as a `charge` at once β€” there is no scheduler,\\nand \\"overdue\\" is derived at read time. Payments are recorded against one named\\ncharge, refunds against one named payment, and nothing is ever edited or\\ndeleted: a mistake is corrected by appending the opposing line. **There is no\\nonline payment integration and none is planned** β€” no gateway, no card data,\\n`method` is free text. Teachers see no money at all (see \\"Payments\\").\\n\\nEvery field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)\\nconstructed only after its restrictions pass β€” invalid input can't be\\nrepresented. Those restrictions are published rather than left to be guessed:\\n**`GET /limits`** (no auth) serves every fixed bound and closed value set the\\nAPI enforces, read straight from the constants the newtypes use, so a frontend\\nvalidates against the server's own rules instead of a hand-kept copy (see\\n\\"Validation limits\\"). Those same types derive `surrealdb::types::SurrealValue`, so one\\ntyped value flows from HTTP request into the `SCHEMAFULL` database. Record ids\\nare ULIDs (time-sortable).", "source": "README.md"}, {"id": "run", "title": "Run", "body": "```sh\\nsurreal start --user root --pass root surrealkv:./data/hezarfen.db # the DB server\\ncp .env.example .env # optional\\ncargo run\\n```\\n\\nBoots on `http://127.0.0.1:8080`, talking to the SurrealDB server at\\n`DB_URL` (default `ws://127.0.0.1:8000`, root credentials via\\n`DB_USER`/`DB_PASS`) and storing uploaded note files in\\n`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs\\n(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at\\n`/api-docs/openapi.json`.", "source": "README.md"}, {"id": "run-in-a-container-podman", "title": "Run in a container (podman)", "body": "```sh\\npodman compose up -d --build # build + start, http://127.0.0.1:8080\\npodman compose logs -f backend\\npodman compose down # stop (data survives in the volume)\\n```\\n\\nThe `Containerfile` is a two-stage build (Rust builder with cargo cache\\nmounts, `debian:trixie-slim` runtime, non-root user). Two services: the\\n`surrealdb` server (official image, surrealkv storage) and the backend, which\\nwaits for the server's healthcheck and connects over `ws://surrealdb:8000`.\\nEach has its own named volume β€” `surreal-data` holds the database,\\n`hezarfen-data` the uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the\\ncontainer so the published port works. Production knobs (`COOKIE_SECURE`,\\n`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in\\n`compose.yaml` β€” uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset\\nmeans dev mirror mode without credentials; a cookie-using browser frontend\\nmust be allowlisted explicitly. Works with `docker compose` too.\\n\\nThe backend survives the database going away, at boot and at runtime.\\n\\nAt boot it retries the connection (1s doubling to 5s) until the server\\nanswers, rather than exiting. Exiting looks tidier but is worse: the container\\nruntime restarts the process, it fails again in milliseconds, and a few\\nseconds of startup skew burns the whole restart budget and leaves the backend\\ndown for good.\\n\\nAt runtime a keepalive query every 5s doubles as a liveness probe. This\\nmatters more than it sounds: a query issued while the socket is down does\\n*not* fail β€” the SDK's reconnect loop stops draining its request queue, so the\\nquery parks until the database returns and only *then* runs. Left alone, a\\nrequest waits out the entire outage and any write it carries lands long after\\nthe caller gave up.\\n\\nSo while the probe says the socket is down, requests are refused at the edge\\nwith `503` and `Retry-After: 1`, before they can reach the database. Nothing\\nis queued, which is what makes that retry safe. Requests that slip through in\\nthe window between the socket dying and the probe noticing are capped at 30s\\nand answer `503` *without* `Retry-After`, with a message saying the write may\\nor may not have applied β€” they were already queued, so retrying them could\\napply the same write twice. WebSocket and SSE routes are unaffected: both\\nreturn their response immediately and stream afterwards.\\n\\nWithout compose:\\n\\n```sh\\npodman build -t hezarfen-backend .\\npodman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backend\\n```", "source": "README.md"}, {"id": "auth-model", "title": "Auth model", "body": "Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, stored\\nserver-side). Send it back on later requests. Every endpoint below whose `Auth`\\ncolumn names a role requires a valid session; the ones marked `no` (`/health`,\\nthe docs pages, `register` / `login` / `logout`) don't (`logout` is idempotent β€”\\nit clears the session if one is present). Set `COOKIE_SECURE=true` when serving\\nbehind TLS to add the cookie's `Secure` attribute.\\n\\n**Register never reveals whether a username is taken.** `POST /auth/register`\\nanswers `201` either way with the *same* body β€” `{username, role}`, the echoed\\nname and the `student` role every fresh account gets. Both outcomes return one\\nvalue built before the insert is even attempted, so they are byte-identical by\\nconstruction. This is deliberate: the route is unauthenticated, so a `409` (or a\\nfaster reply) would let anyone enumerate the school's users. The password is\\nhashed *before* the availability check so both outcomes cost the same ~33ms.\\n\\nThe reply carries **no `id`**: on the taken path there is no row to name, and a\\nfabricated one would leave the client holding an id that matches nothing. Log\\nin and read `GET /auth/me` to learn who you are. The accepted cost: a caller who\\ncollides with an existing account gets no distinct error and simply cannot log\\nin with that password β€” they pick another name. Do not \\"fix\\" this back to a\\n`409`, and do not add an `id` back.", "source": "README.md"}, {"id": "time-policy", "title": "Time policy", "body": "Timezones and clock differences cannot corrupt data, by construction:\\n\\n- **Every instant is a UTC unix-millisecond `i64`** (`domain::timestamp::Timestamp`),\\n stored as an `int`, sent as a plain number. Nothing stores or parses a\\n timezone, so the server's `TZ`, the container's clock config, and the\\n client's locale are all irrelevant β€” clients convert millis to local time\\n for display only.\\n- **One clock choke point.** `Timestamp::now()` is the only wall-clock read.\\n `clippy.toml` bans every other source (`chrono::Local`/`Utc::now`,\\n `SystemTime::now`, `time::OffsetDateTime::now_*`, absolute cookie\\n `Expires`) and `[lints.clippy]` raises that to a hard `cargo clippy` error,\\n so local-time bugs can't be reintroduced.\\n- **Expiry is server-authoritative.** Sessions expire by comparing the stored\\n millis against the server clock; the cookie carries a relative `Max-Age`\\n (never an absolute `Expires`), so a wrong client clock changes nothing.\\n- **Pacing uses the monotonic clock.** The rate limiter runs on `Instant`,\\n immune to NTP steps and wall-clock jumps.\\n- **Calendar dates get a timezone grace.** A birth date is a calendar date on\\n the writer's wall, not an instant: validation accepts up to UTC-tomorrow,\\n since a client ahead of UTC (up to UTC+14) legitimately writes a date the\\n server's UTC calendar hasn't reached yet.\\n- **Times-of-day are UTC too, and staff enter them that way.** A meal slot's\\n `serving_minute` (minutes past midnight, `0`–`1439`) is the one clock-face\\n value a school types in, and it is read as UTC on the menu's `date` β€” there\\n is deliberately **no school-timezone setting** (a rejected feature), so a\\n UTC+3 school enters `540` (09:00 UTC) for a meal served at noon locally.\\n- **Nothing schedules in the past.** A request-supplied schedule instant β€” an\\n exam window, a lesson's `starts_at`/`ends_at`, an event time β€” must not lie\\n before the server's now, on create and on every `PATCH` that sets it: a\\n deadline that starts in the past is dead on arrival, so it's a `400`. A\\n 60-second grace absorbs request latency and client-clock skew (\\"starts now\\"\\n survives its own round trip). Values a `PATCH` merely keeps are exempt β€” a\\n running exam's `starts_at` is legitimately past, and a rename or deadline\\n extension must not trip over it. (Work-log corrections are records of past\\n work, not schedules, and stay free.)\\n- **Frontends can sync to the server clock.** `GET /time` (no auth) returns\\n `{\\"now\\": <UTC unix-millis>}`. Fetch once, keep\\n `offset = now - Date.now()`, and use `Date.now() + offset` for countdowns\\n and past/future checks instead of trusting the device clock.\\n\\nKeep the single server's clock NTP-synced; that's the only clock that matters.", "source": "README.md"}, {"id": "validation-limits", "title": "Validation limits", "body": "Every fixed bound the API enforces is published at `GET /limits` (no auth), so\\na client never has to hard-code a copy that drifts the day a constant moves.\\nThe handler reads `src/constant.rs` directly β€” a changed constant changes the\\nresponse in the same commit.\\n\\n```json\\n{\\n \\"user\\": { \\"min_username_len\\": 3, \\"max_username_len\\": 32,\\n \\"username_separators\\": [\\".\\", \\"_\\", \\"-\\"],\\n \\"reserved_usernames\\": [\\"admin\\", \\"…\\"],\\n \\"min_password_len\\": 6, \\"max_password_len\\": 128,\\n \\"max_name_len\\": 100, \\"max_email_len\\": 254,\\n \\"min_phone_digits\\": 7, \\"max_phone_digits\\": 15,\\n \\"roles\\": [\\"parent\\", \\"student\\", \\"teacher\\", \\"manager\\", \\"admin\\"],\\n \\"themes\\": [\\"light\\", \\"dark\\"], \\"languages\\": [\\"tr\\", \\"en\\"],\\n \\"palette_color_pattern\\": \\"^#[0-9a-fA-F]{6}$\\", \\"palette_color_len\\": 7,\\n \\"session_duration_days\\": 7 },\\n \\"note\\": { \\"max_title_len\\": 200, \\"max_content_len\\": 10000, \\"max_files\\": 10 },\\n \\"file\\": { \\"max_name_len\\": 255, \\"max_content_type_len\\": 100,\\n \\"min_max_file_bytes\\": 1024, \\"max_max_file_bytes\\": 26214400,\\n \\"default_max_file_bytes\\": 5242880,\\n \\"image_content_types\\": [\\"image/png\\", \\"image/jpeg\\", \\"image/webp\\", \\"image/gif\\"] },\\n \\"message\\": { \\"max_subject_len\\": 200, \\"max_body_len\\": 10000, \\"max_label_len\\": 50 },\\n \\"event\\": { \\"max_title_len\\": 200, \\"max_description_len\\": 2000 },\\n \\"course\\": { \\"kinds\\": [\\"course\\", \\"study\\", \\"club\\"], \\"max_title_len\\": 200, \\"…\\": 0 },\\n \\"exam\\": { \\"modes\\": [\\"sync\\", \\"async\\", \\"open\\"],\\n \\"question_kinds\\": [\\"choice\\", \\"text\\"],\\n \\"min_duration_ms\\": 60000, \\"max_duration_ms\\": 86400000,\\n \\"max_attempts\\": 100, \\"unlimited_attempts\\": 0,\\n \\"min_mark\\": 0, \\"max_mark\\": 100, \\"…\\": 0 },\\n \\"homework\\": { \\"statuses\\": [\\"done\\", \\"incomplete\\", \\"missing\\"],\\n \\"max_files_per_submission\\": 10, \\"max_assigned\\": 200, \\"…\\": 0 },\\n \\"question_pool\\": { \\"max_title_len\\": 200, \\"max_body_len\\": 10000, \\"max_solution_body_len\\": 10000 },\\n \\"appointment\\": { \\"max_note_len\\": 500, \\"max_reason_len\\": 1000, \\"max_slot_occurrences\\": 52 },\\n \\"chatbot\\": { \\"max_message_len\\": 8000, \\"max_thread_title_len\\": 200,\\n \\"min_max_message_len\\": 100, \\"…\\": 0 },\\n \\"board\\": { \\"max_title_len\\": 200, \\"max_participants\\": 50,\\n \\"max_stroke_payload_len\\": 4096,\\n \\"max_epoch_strokes\\": 5000, \\"max_board_strokes\\": 50000,\\n \\"max_boards_per_creator\\": 200,\\n \\"stroke_kinds\\": [\\"stroke\\", \\"clear\\"],\\n \\"ws_tick_secs\\": 15, \\"ws_max_board_id_len\\": 64 },\\n \\"settings\\": { \\"max_list_len\\": 20, \\"max_item_len\\": 50,\\n \\"min_exam_kind_weight\\": 1, \\"max_exam_kind_weight\\": 100,\\n \\"max_grade_bands\\": 20, \\"max_grade_label_len\\": 20,\\n \\"required_attendance_statuses\\": [\\"present\\", \\"absent\\", \\"late\\", \\"excused\\"] },\\n \\"request\\": { \\"max_page_limit\\": 500, \\"schedule_past_grace_ms\\": 60000,\\n \\"request_timeout_secs\\": 30 },\\n \\"rate\\": { \\"window_secs\\": 60, \\"auth_per_minute\\": 10,\\n \\"api_per_minute\\": 300, \\"chatbot_per_minute\\": 20 }\\n}\\n```\\n\\nThe `rate` group is the one part that is **not** compile-time: those tiers are\\nenvironment-tunable, so the endpoint serves *this* server's live values (read\\nfrom its running limiters), not the shipped defaults. `0` means the tier is\\noff. A client should read its budget here rather than discovering it by\\ncollecting a `429`.\\n\\n### Two surfaces, one source\\n\\nThe bounds are published twice, on purpose, because clients consume them two\\ndifferent ways:\\n\\n| Surface | Shape | Use it when |\\n|---------|-------|-------------|\\n| `GET /limits` | One JSON document, grouped by resource, closed value sets included | Runtime fetch. No codegen step, survives a deploy skew, and carries things OpenAPI holds awkwardly (`reserved_usernames`, `image_content_types`) |\\n| `/api-docs/openapi.json` | Per-field `maxLength` / `minLength` / `minimum` / `maximum` / `maxItems` on the request schemas | Build-time codegen β€” `openapi-typescript`, `orval`, and friends turn these into types *and* validators automatically |\\n\\nBoth are generated from the same `src/constant.rs`, and **neither is allowed to\\ndrift from it**, which is enforced rather than asked for:\\n\\n- `tests/limits_completeness.rs` parses every `pub const` out of `constant.rs`\\n and fails unless each one is either referenced by `src/web/limits.rs` or\\n listed as a deliberate exclusion *with a reason*. A new constant breaks the\\n suite until someone decides, consciously, whether clients need it.\\n- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 161 published\\n bounds back out of the emitted JSON, and asserts each equals its constant.\\n This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal\\n only** β€” a `const` there does not compile β€” so the annotations are\\n unavoidably a second copy of each number. The test is what makes that copy\\n safe. It also pins the `limit` query parameter's `maximum` to\\n `MAX_PAGE_LIMIT`, a duplication `constant.rs` previously only *asked* a human\\n to maintain.\\n- A third check in `limits_completeness.rs` refuses to let a validation bound\\n be declared **outside** `constant.rs` at all. Without it a limit can hide in\\n a domain module and reach neither surface β€” which is exactly where\\n `MAX_CHATBOT_THREAD_TITLE_LEN` was found sitting, private and unpublished.\\n\\nNotes:\\n\\n- **No auth.** The registration and login forms need the username and password\\n bounds before a session exists, and none of these are secrets β€” they are the\\n same rules a `400` already spells out in prose.\\n- **Answers during a database outage.** `/limits` touches no row, so it is\\n exempt from the guard that answers `503` while the database reconnects β€” a\\n frontend booting against a degraded backend is exactly when it needs the\\n contract. Every route that does read the database still refuses.\\n- **Fetch once.** The values are compile-time constants, so the response only\\n changes with a deploy. Cache it for the session; the `ETag`/`304` path makes\\n a revalidation cheap if you'd rather re-check.\\n- **`/limits` is not `/settings`.** School-adjustable policy β€” the exam kinds\\n and their weights, the attendance statuses, the grade bands, the live\\n `max_file_bytes` and chatbot knobs β€” is on `GET /settings` and changes when a\\n manager edits it. What `/limits` carries for those knobs is the fixed range a\\n manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the\\n attendance statuses no school may remove.\\n- **Open sets travel as a pattern.** `palette_color` accepts any hex accent\\n color, so `/limits` publishes `palette_color_pattern` (a regular expression)\\n and `palette_color_len` instead of a value list β€” validate the shape, not\\n membership in a palette. The pattern describes what the server *accepts*, so\\n it matches either case; the stored (and returned) value is lowercased, which\\n is the one place a response may differ in case from the request.\\n- **Closed value sets ride along.** `roles`, `themes`, `languages`, course\\n `kinds`, exam `modes`, `question_kinds`, homework `statuses`, board\\n `stroke_kinds`, and the\\n uploadable `image_content_types` are the exact accepted spellings β€” build\\n pickers from these rather than from a literal list.", "source": "README.md"}, {"id": "rate-limiting", "title": "Rate limiting", "body": "Requests are limited per client IP over a fixed 60-second window, in two tiers:\\n`/auth/login` + `/auth/register` get a strict budget\\n(`RATE_LIMIT_AUTH_PER_MINUTE`, default 10) against credential brute-force,\\nand every route β€” Swagger included β€” shares a generous catch-all\\n(`RATE_LIMIT_API_PER_MINUTE`, default 300). Exceeding either answers `429` with\\na `Retry-After` header (seconds). Set a limit to `0` to disable that tier β€”\\nuseful for load tests.\\n\\nSending a chatbot message adds a third tier, and it is keyed by **user id**,\\nnot by IP (`RATE_LIMIT_CHATBOT_PER_MINUTE`, default 20), because an inference\\ncosts the school real money and a shared-IP classroom must not spend one\\nstudent's budget on another's. `0` disables it like the other two. It is\\ncharged before anything is written, so a `429` leaves no trace (see\\n\\"Chatbot\\").\\n\\nAll three tiers admit from memory β€” no request ever waits on the database to be\\nlet in β€” but the window **outlives the process**. A background task folds each\\ntier's new admits into one shared `rate_limit` row per tier + client + minute\\nevery 2 seconds, then caps the in-memory bucket by the total that comes back,\\nso a restart mid-minute does not hand every client a fresh budget. One caveat:\\na just-started process can spend up to the tier's budget in the 2 seconds\\nbefore its first fold tightens it. If the database is down the tiers simply\\nfall back to their own local budgets β€” nobody is refused for it.\\n\\nBehind a reverse proxy every connection carries the proxy's address, so also\\nset `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry\\n(the one the proxy itself appends). Leave it off when clients reach the server\\ndirectly β€” the header is client-forged in that case.", "source": "README.md"}, {"id": "cors", "title": "CORS", "body": "Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin`\\n(browsers refuse it on credentialed requests), so origins listed in the\\ncomma-separated `CORS_ALLOWED_ORIGINS` allowlist are echoed back with\\n`Access-Control-Allow-Credentials: true`. When the allowlist is unset the\\nserver reflects the request's `Origin` β€” dev-friendly β€” but **without**\\ncredentials: mirroring with credentials would let any website ride a\\nvisitor's session cookie. A browser frontend that needs the session cookie\\ncross-origin must therefore be allowlisted explicitly.", "source": "README.md"}, {"id": "roles-access-control", "title": "Roles & access control", "body": "Every user has one of five roles, ranked lowest to highest:\\n\\n```\\nparent < student < teacher < manager < admin\\n```\\n\\nThe check is **hierarchical** β€” a higher role satisfies any lower requirement\\n(an admin can do anything a teacher can). New accounts always register as\\n`student`; a role read is re-checked on every request, so a role change takes\\neffect on the user's very next call (no re-login).\\n\\n`parent` is the read-only observer at the bottom of the ladder: an admin ties\\nany number of students to a parent account (`POST /users/{id}/students`), and\\nthe tie is the parent's whole power β€” they list their students\\n(`GET /users/me/students`) and read each one's mark, attendance, pomodoro,\\nand homework reports in full. Student-only checks are exact (`role == student`), so a\\nparent can never enroll, sit an exam, be graded, or land on a roll call; and\\nsitting below every staff bar, they can't touch anything else either β€” except\\nmessages, which any role sends and receives (that's how a parent reaches a\\nteacher). A role\\nchange off either end of a tie (the parent stops being a `parent`, the\\nstudent stops being a `student`) drops the tie, exactly like promotion drops\\ncourse enrollments.\\n\\n| Action | Minimum role | Notes |\\n|------------------------------------------|--------------|-----------------------------------------------|\\n| Register / login / view own account | (any) | Registration always creates a `student` |\\n| View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves |\\n| Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included β€” the role's one write); each party only ever touches their own copy |\\n| Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark β€” a teacher+ may mark anyone expected, themselves included |\\n| Create events | teacher | The audience (school / role / course / registration) is set at creation and editable later |\\n| Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** β€” never for another staff member. Unregistering mirrors the same rule |\\n| List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report |\\n| Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |\\n| View a course's sessions | student | Only inside **visible** courses: enrolled, creator, assigned teacher, or `manager`+ |\\n| List a session's roll call | teacher | The **session's teacher**, or anyone with course-management rights |\\n| Create / edit / delete a course session | teacher | Course-management rights (course creator, an assigned teacher, or `manager`+) |\\n| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights; only students sit on a roster |\\n| Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call β€” the teacher can't self-mark |\\n| Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied |\\n| View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries |\\n| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session |\\n| View **any** user's pomodoro log | teacher | Study oversight β€” same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' |\\n| Ask into the school question pool | student | **Students only** (exact); born `pending` β€” visible to the asker + teacher+ only; the asker may attach/replace/remove one photo while pending |\\n| Read the pool; offer / edit / withdraw own solutions | student | Every `approved` question is school-wide (parents stay out); a solution's author edits its body and photo anytime (solutions never freeze) and deletes it, teacher+ delete any |\\n| Approve a pending pool question; delete any question or solution | teacher | Approval publishes school-wide and **freezes** the content; rejection = deletion β€” moderation never edits, so teacher+ cannot rewrite a solution |\\n| Read the school **question bank**; save / instantiate bank questions | teacher | Every bank row is school-wide (reads + copy into an exam); saving one makes the caller its owner |\\n| Edit / delete a bank question (and its images) | teacher | **Owner only** (admin bypass); bank rows carry no exam link, so they never freeze |\\n| Read **own** attendance report | student | |\\n| Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created + assigned; `manager`+: all); exam **drafts** show only to the course's managers |\\n| Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** β€” staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |\\n| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |\\n| Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |\\n| Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights β€” one teacher can't read another's answer key |\\n| Watch an exam's live monitor (poll the snapshot) | teacher | Course-management rights |\\n| Create courses | teacher | The creator manages the course, and owns it for good |\\n| Assign / unassign a course's teachers | manager | Staffing is the office's call β€” a course's own creator cannot hand rights to peers; the assignee must be `teacher`+ |\\n| Delete a course | teacher | Only the **creator**, or a `manager`+ β€” an assigned teacher runs the course but doesn't own it |\\n| Manage inside a course: edit it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | The **course creator**, a teacher **assigned** to it, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions or homework won't delete (`409`) |\\n| View a course's roster, an exam's result list / statistics | teacher | Course-management rights |\\n| Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself |\\n| Assign / edit / delete homework; grade it; read its roster | teacher | Course-management rights; an `assigned` subset (≀ 200 enrolled students) can't be narrowed over existing work (`409`); a grade (`done`/`incomplete`/`missing` + optional mark) freezes the submission until removed |\\n| Submit **own** homework (text + files); read own submission and grade | student | **Students only** β€” staff never submit; enrolled + in the audience; editable until graded; ≀ 10 files of any type, each ≀ `max_file_bytes`, always downloaded as attachments |\\n| Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full β€” statuses/marks/flags, never files |\\n| Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields |\\n| Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen β€” the client then follows the device preference |\\n| List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports β€” a parent changes nothing, anywhere |\\n| Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |\\n| Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call |\\n| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role |\\n\\n### Bootstrapping the first admin\\n\\nThere is no self-service path to `admin` β€” registration always creates a\\n`student`. The first admin comes from the startup seed: set both\\n\\n```sh\\nADMIN_USERNAME=admin\\nADMIN_PASSWORD=admin123 # local-dev default used by compose.yaml; change it\\n```\\n\\nand on boot the account is created with the `admin` role **if the username\\ndoesn't exist yet**. The seed is idempotent and deliberately conservative: it\\nnever promotes or rewrites an existing account (if the name is taken by a\\nnon-admin it logs a warning and leaves it alone β€” promoting someone else's\\naccount would be an escalation). Setting only one of the two variables aborts\\nstartup. `compose.yaml` ships with the credentials above for local dev.\\n\\nThat admin can then promote everyone else through `PATCH /users/{id}/role`.\\n\\nManual fallback (also the recovery path if the seeded name was squatted or the\\nsole admin locked themselves out): run\\n\\n```surql\\nUPDATE user SET role = 'admin' WHERE username = 'ada';\\n```\\n\\nagainst the SurrealDB server β€” e.g.\\n`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db hezarfen`\\n(in the container setup, `podman exec -it hezarfen-surrealdb /surreal sql ...`).", "source": "README.md"}, {"id": "endpoints", "title": "Endpoints", "body": "`Auth` is the minimum role; `no` means no session required, `student` means any\\nlogged-in user.\\n\\nA course is a regular class (kind `course`, the default), an *etΓΌt* (kind\\n`study` β€” a supervised study session), or a *kulΓΌp* (kind `club` β€” a student\\nclub). The three kinds behave identically everywhere β€” enrollment, exams,\\nsessions, marks β€” the kind is a label the UI renders differently, settable at\\ncreation and editable later. A course may also carry a `capacity`: once the\\nroster reaches it, new enrolls are refused with `409` (members already on the\\nroster are unaffected, even if the cap is later lowered below them; `null`\\nlifts the cap).\\n\\n**Who runs a course.** Its **creator** owns it for good β€” only they (or a\\nmanager+) may delete it. On top of that, a manager can **assign** any\\n`teacher`+ to the course with `POST /courses/{id}/teachers` (`{user_id}`,\\nidempotent) and drop them again with `DELETE /courses/{id}/teachers/{user}`.\\nAn assigned teacher gets full **course-management rights** β€” edit the course,\\nenroll and unenroll students, add exams, sessions and subjects, grade, take\\nroll call β€” but *not* the two owner powers: they cannot delete the course, and\\nthey cannot change who else teaches it. Staffing is deliberately the office's\\ncall, so a course's own creator cannot hand rights to their peers; only\\nmanager+ may touch the list. Every course response carries its `teachers`\\narray alongside `creator`, and a user demoted below `teacher` is swept off\\nevery course they were assigned to (the mirror of promotion dropping\\nenrollments).\\n\\nCourse data is walled per course. A course, its exams, its sessions, and its\\nsubjects are\\n**visible** only to its enrolled users, its creator, its assigned teachers,\\nand manager+ β€” a student\\nsees just the classes they were added to, and the `/courses` / `/exams`\\ncatalogs are filtered accordingly. Teacher-level reads *inside* a course\\n(roster, results, statistics, the question list, answer sheets, the live\\nmonitor) additionally need **course-management rights** (creator, an assigned\\nteacher, or manager+):\\none teacher cannot look into another teacher's course, and the per-user\\nmarks/attendance reports narrow to the courses the caller manages.\\n\\n**Paging.** Every list endpoint below (the rows tagged **Β· paged**) accepts\\n`?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope\\nrather than a bare array. `total` is the full row count *before* the window, so\\na frontend can show \\"100 of 256\\" and page with `offset`. Paging is **opt-in**:\\nomit `limit` and you get every remaining row (the echoed `limit` is then\\n`null`), so a caller that sends no parameters still receives the whole list β€”\\nnothing silently truncates. `limit` must be `1`–`500`, `offset` defaults to `0`\\nand must be β‰₯ 0 (bad values are `400`), and an `offset` at or past the end\\nreturns an empty `items` (not an error). Deliberately **not** paged β€” these keep\\ntheir existing shapes: the student exam-room reads\\n`/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and\\n`/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`.\\n\\n**Schedule window (`GET /events`, `GET /exams`).** Both lists additionally\\naccept `?starts_after=` and `?ends_after=`, UTC unix-millis, both optional and\\nindependent (AND-ed when both are sent). `ends_after=T` keeps rows whose window\\nhas not finished β€” `ends_at > T`, falling back to `starts_at > T` when `ends_at`\\nis `null`; `starts_after=T` keeps rows with `starts_at > T`. A row with no\\nschedule at all (an event without times, an exam with no `mode` or in `open`\\nmode) is excluded by either parameter. Supplying either one flips the order to\\n**ascending by schedule** (`starts_at`, falling back to `ends_at`; ties by id),\\nso `?ends_after=<now>&limit=20` gives the twenty *soonest* rows instead of the\\ntwenty newest-created β€” with neither parameter the list is byte-for-byte the\\nnewest-first list it always was. `total` is the count after visibility *and*\\nwindow filtering, before paging; negative values are a `400` naming the field.\\n\\n| Method | Path | Auth | Description |\\n|--------|----------------------------------|---------|---------------------------------|\\n| GET | `/health` | no | Liveness check |\\n| GET | `/` | no | Same as `/health` |\\n| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |\\n| GET | `/limits` | no | Every fixed validation bound, grouped by resource β€” see Validation limits |\\n| GET | `/swagger` | no | Interactive API docs (Swagger UI) |\\n| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |\\n| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |\\n| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken β€” see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |\\n| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` β€” own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) Β· paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` β€” find users by username/name fragment (pickers); refs only, no contact info Β· paged |\\n| GET | `/users` | admin | List all users Β· paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` β€” set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` β€” tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students Β· paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |\\n| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes Β· paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) β€” ≀ the school's `max_file_bytes`, ≀ 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) Β· paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |\\n| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` β€” send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` β€” the caller's folder, newest first; `?folder=inbox&read=false&limit=1` β†’ `total` is the unread badge Β· paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` β€” read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** β€” only from the trash (`409` elsewhere); the row vanishes once both sides deleted |\\n| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` β€” `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` β€” mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) Β· paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` Β· paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` β€” seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |\\n| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` β€” publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, ≀ 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) β€” a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar β€” future slots only, demoted teachers' slots left out Β· paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` β€” book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests Β· paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` β€” call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included β€” they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` β€” counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal β€” this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |\\n| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` β€” `kind` is `course` (default), `study` (etΓΌt), or `club` (kulΓΌp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) Β· paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses Β· paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ β€” **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` β€” assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` β€” enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) Β· paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β€” add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β€” add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |\\n| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` β€” roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) Β· paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` β€” add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) Β· paged |\\n| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist β€” the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` β€” grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) Β· paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt β€” students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) Β· paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question β€” the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam β€” copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** β€” copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question β€” text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` β€” autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers ⋃ marks), ascending β€” the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first β€” the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** β€” the answer key the caller checks their own sheet against (same review gate) Β· paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers ⋃ marks), ascending β€” only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster Γ— latest attempts Γ— marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |\\n| GET | `/bank-questions` | teacher | The school-wide question bank β€” `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) Β· paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist β€” `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question β€” the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` β€” assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≀ 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) Β· paged |\\n| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) Β· paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade β€” the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades β€” file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` β€” hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part β€” **any** content type, ≀ `max_file_bytes`, ≀ 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) β€” the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student Γ— submission/files/grade + computed `late`/`missing`/`unenrolled` β€” a straggler's stale work stays visible (course manager) Β· paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` β€” grade `done`/`incomplete`/`missing` (+ optional 0–100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable β€” that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) β€” readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade β€” un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows β€” submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` β€” full, statuses and marks only, never files Β· paged |\\n| POST | `/questions` | student | `{title, body}` β€” ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` β€” the pool questions visible to the caller, each with its `solution_count` Β· paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question β€” publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` β€” offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first β€” a discussion thread Β· paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` β€” edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |\\n| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) Β· paged |\\n| GET | `/work/{user}` | manager | A staff member's work log Β· paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` β€” correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |\\n| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** β€” a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` Β· paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape Β· paged; *or a `parent` linked to `{user}` |\\n| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |\\n| POST | `/terms` | manager | `{name, starts_at, ends_at}` β€” past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first Β· paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course still links to it |\\n| POST | `/meals/menus` | manager | `{date, slot, capacity?}` β€” publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first Β· `?from=&to=` inclusive `YYYY-MM-DD` range Β· paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` β€” the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` β€” add a dish (≀ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` β€” record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` β€” take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first Β· paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included Β· paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent β€” cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` β€” mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu Β· paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history Β· `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day Β· paged Β· own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` β€” record money received; **admin only**, appends a `credit` line |\\n| POST | `/payments/plans` | manager | `{name, installments}` β€” write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it β€” its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (≀ 200) β€” place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first Β· paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` β€” record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` β€” hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` β€” undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines β€” charges, payments, refunds, reversals β€” newest first Β· paged Β· own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |\\n| POST | `/chatbot/threads` | student | `{title?}` β€” start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first Β· paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` β€” rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first β€” user and assistant rows alike Β· paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≀ `max_chatbot_message_len`) β€” send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` β€” nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β€” or one `error` β€” and close; an already-finished answer replays (see \\"Chatbot\\") |\\n| POST | `/boards` | student | `{title, participant_ids?}` β€” open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first Β· paged |\\n| GET | `/boards/{id}` | student | One board β€” a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |\\n\\n`status` must be one of the school's attendance statuses (`GET /settings`);\\nthe core four `present | absent | late | excused` always exist, plus whatever\\nthe school added.\\n`kind` must be one of the school's exam kinds (`GET /settings`; defaults:\\n`homework | quiz | midterm | final | project | oral`). The kind carries the\\nexam's weight in the course average β€” an integer `1`–`100` set per **kind** in\\nsettings (defaults all `1`), resolved when a report is read; an exam whose\\nkind was later removed from settings counts with weight `1`.\\nA course may carry a `term_id` (`null` = unassigned); on `PATCH\\n/courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`\\nclears it.\\n`role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are\\nULIDs. `parent` accounts are made by an admin (register as `student`, then\\n`PATCH /users/{id}/role`) and observe only the students an admin tied to them\\nβ€” see \\"Roles & access control\\".\\nAn exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row,\\nnever in a `note`. Students never grade anyone β€” grading is teacher+ with\\ncourse-management rights, and the target must be enrolled in the exam's course;\\na student reads just their own mark via `GET /exams/{id}/result`.\\nA course average is `Ξ£(markΓ—weight) / Ξ£(weight)` over the student's **graded**\\nexams in that course (`null` while nothing is graded β€” ungraded exams are\\nskipped, not zeroed). The overall average is the plain mean of the non-null\\ncourse averages. Unenrolling keeps result rows: the marks drop out of the\\nreport until re-enrollment, but stay visible on the exam itself. A course\\nwith anyone still on its roster refuses deletion (`409`) β€” empty the roster\\nfirst; once empty, deleting it cascades its exams, their results, its\\nsessions and roll call, and its subjects.\\nA **subject** is one topic of a course's curriculum (`name` ≀ 200 chars,\\noptional `description` ≀ 2000): every exam question carries a mandatory\\n`subject_id` naming one of *its own course's* subjects (an unknown or\\nforeign-course subject is a `400`), so exam content is always attributable to\\na topic. A subject's course link is fixed at creation, and a subject still\\nreferenced by questions refuses deletion with a `409` β€” re-tag (PATCH the\\nquestions' `subject_id`) or delete those questions first. Questions written\\nbefore subjects existed are **destroyed on boot** (answers first) β€” the clean\\nbreak instead of inventing a placeholder topic.\\nEvent `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both\\nare given, `ends_at` must not precede `starts_at`, and neither may be set in\\nthe past (else `400`). On `PATCH`, an omitted time keeps its value and an\\nexplicit `null` clears it.\\nAn event's `audience` is a tagged object β€” `{\\"kind\\": \\"school\\"}` (the default),\\n`{\\"kind\\": \\"role\\", \\"role\\": \\"student\\"}` (that exact role, no \\"and above\\"),\\n`{\\"kind\\": \\"course\\", \\"course\\": \\"<id>\\"}` (the course's current enrollment), or\\n`{\\"kind\\": \\"registration\\", \\"capacity\\": 30}` (a signup list; `capacity` optional,\\n`null` = unlimited) β€” and is the event's **expected-attendee roster**, resolved\\nlive at read time: role changes, (un)enrollments, and (un)registrations move\\npeople in and out by themselves. It never hides the event β€” everyone sees every\\nevent. Only audience members can be marked; `GET /events/{id}/roster` joins the\\nlive roster with the recorded marks (`status: null` = expected but never\\nmarked). Attendance rows for people a later audience edit (or unenrollment /\\nrole change) dropped stay stored and listed under `/events/{id}/attendance`,\\nbut leave the roster report.\\nA registration list fills through `POST /events/{id}/register`: teachers place\\nstudents (a student never registers, not even themselves) and take seats only\\nfor themselves β€” registering another staff member is refused. Re-registering\\nsomeone is a no-op, a full list is a `409`, and the list freezes the moment\\nthe event starts β€” or, when only `ends_at` is set (a pure signup deadline),\\nthe moment it passes (register and unregister both). Signup rows survive an\\naudience switch inertly and resurface if the event returns to the registration\\nkind; deleting the event deletes them. Pre-existing hand-picked (`users`)\\naudiences convert on boot: each listed user becomes a signup row credited to\\nthe event's creator, and the audience becomes an uncapped registration list.\\nReading a child collection of a missing parent (`/events/{id}/attendance`,\\n`/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`,\\n`/courses/{id}/sessions`, `/courses/{id}/subjects`, `/courses/{id}/homework`,\\n`/homework/{id}/submissions`, `/sessions/{id}/attendance`) is a `404`, not an\\nempty list.\\nPersonal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same\\noptional set on every account, whatever the role, and is `null` until filled\\nin. On `PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) each field\\nis independent: omitted (or `null`) keeps the current value, an empty string\\n`\\"\\"` clears it, anything else is validated β€” email must look like\\n`name@example.com`, phone is 7–15 digits with an optional `+` and cosmetic\\nseparators, `birth_date` is a real `YYYY-MM-DD` calendar date not in the\\nfuture. Names allow unicode; usernames are strict: lowercase letters and\\ndigits plus non-consecutive interior `.`, `_`, `-` separators, starting and\\nending with a letter or digit (3–32 chars). Staff-looking names (`admin`,\\n`administrator`, `root`, `support`, `system`, `moderator`, `staff`) are\\nrejected at `/auth/register` only β€” the `ADMIN_USERNAME` bootstrap may still\\nseed them.\\nUI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`,\\n`palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the\\nsame account row and come back on every user response (`/auth/me` included).\\n`PATCH /users/me/preferences` (or the admin `PATCH /users/{id}/preferences`)\\nuses the same field semantics as the profile patch: omitted keeps, `\\"\\"` clears\\nback to `null` (\\"never chose\\" β€” the client then follows the device\\npreference, or its own default accent), anything else must be valid or the\\nwhole patch is a `400`. `palette_color` is the one **open** set: any valid hex\\npasses (mixed case in, stored and returned lowercase), so a new frontend\\npalette needs no backend change β€” `/limits` publishes its pattern rather than a\\nlist of colors.", "source": "README.md"}, {"id": "appointments", "title": "Appointments", "body": "Office hours and parent-teacher conferences, booked instead of arranged by\\nmessage. A teacher+ **publishes availability**; a student or a parent\\n**books** one of those windows with a reason; the teacher **decides**. Two\\nrows carry it: an `appointment_slot` (the offer) and an `appointment` (the\\nbooking sitting on it) β€” a slot is never \\"half booked\\", and a refused request\\nstays readable instead of vanishing.\\n\\nA slot is a window on one teacher's calendar: `starts_at`/`ends_at` (unix\\nmilliseconds, `starts_at` strictly before `ends_at`, neither in the past β€” the\\nusual 60-second grace) plus an optional `note` (≀ 500 chars) shown to\\nrequesters (\\"office hours\\", \\"veli gΓΆrüşmesi\\"). Windows are **half-open**, so\\n10:00–10:30 and 10:30–11:00 are two slots, not a collision. A window that *does*\\noverlap one the same teacher has already published is refused with a `409` β€” the\\nguard is **per-teacher** (two teachers may hold office hours at the same hour)\\nand boundary-touching windows are legal by that same half-open rule, which is\\nhow an hour gets carved into back-to-back slots. `POST\\n/appointments/slots` publishes on the caller's *own* calendar (managers and\\nadmins included β€” the calendar always belongs to whoever posted) and **always\\nanswers an array**: one element for a one-off, one per occurrence for a\\nrecurring publish.\\n\\n`repeat_weekly: true` with an `until` expands the same window every seven days\\nup to and including `until`, server-side, into **concrete rows** sharing a\\n`series` id β€” no recurrence rule is stored, so one week can be cancelled\\nwithout touching the rest. At most 52 occurrences (a year); asking for more is\\na `400`, as is `repeat_weekly` without `until` β€” and so is a window sitting so\\nfar ahead that shifting it by a week would run off the end of representable\\ntime (the shift is checked, never wrapped: a wrapped end would land *before*\\nits start, and an inverted window can never overlap anything, which would\\nquietly disable the double-booking guard). A recurring publish is\\n**all-or-nothing**: every occurrence is checked β€” against the slots already\\nstored *and* against the earlier occurrences of the same batch, which a window\\nlonger than a week overlaps itself β€” before a single row is written, so a\\nmid-series collision answers `409` and leaves no stray weeks behind. Delete one\\noccurrence with\\n`DELETE /appointments/slots/{id}`, the whole publish with `DELETE\\n/appointments/slots/series/{series}`.\\n\\n```json\\nPOST /appointments/slots\\n{ \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"repeat_weekly\\": true, \\"until\\": 1901209600000 }\\n\\n201 [ { \\"id\\": \\"01J8…A\\", \\"teacher\\": {\\"id\\": \\"01J8…T\\", \\"username\\": \\"ayse\\",\\n \\"display_name\\": \\"Ayşe YΔ±lmaz\\"},\\n \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"series\\": \\"01J8…S\\", \\"created_at\\": 1899… },\\n { \\"id\\": \\"01J8…B\\", …, \\"starts_at\\": 1900604800000, \\"series\\": \\"01J8…S\\" } ]\\n```\\n\\n`GET /appointments/slots` is two lists behind one path: a teacher+ reads\\n**their own** calendar, past occurrences included; everyone else reads the\\n**bookable** calendar β€” future slots only, earliest first. A teacher demoted\\nafter publishing leaves **inert** slots: their live role is re-read, so those\\nslots drop out of the bookable list and booking one is refused with a `409`.\\nThe list does not say whether a slot is already taken β€” booking a taken one\\nanswers `409`.\\n\\n**Booking.** `POST /appointments` (`{slot, reason}` β€” the reason is required,\\n≀ 1000 chars) is for **students and parents only**; staff arrange between\\nthemselves off this API. A parent books for *themselves* β€” this is the\\nparent-teacher conference, not a booking on behalf of a child. The request\\nlands `pending`, always: publishing availability is not consent to a\\nparticular person and a particular topic, so approve/reject still applies.\\n\\nA booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two\\nare **live** and hold the slot; rejecting or cancelling frees it for someone\\nelse immediately (the slot carries an `occupied` counter, taken by a booking\\nand handed back in the same transaction as the reject or cancel that settles\\nit, so the seat is decided by the database rather than by a count two\\nconcurrent bookings can both read as free). The decisions:\\n\\n- `PATCH /{id}/approve` β€” the slot's teacher (or manager+) confirms. Refused\\n (`409`) when the effective window has already started.\\n- `PATCH /{id}/reject` β€” turns it down; the slot frees up.\\n- `PATCH /{id}/cancel` β€” **the requester only**, from either live state.\\n Anyone else is a `403`, the slot's teacher and a manager/admin included (the\\n guard compares ids, not roles). A teacher ends a booking by **rejecting** it\\n while it is `pending`, and an approved one by counter-proposing another time\\n (`/reschedule`, which sends it back to `pending`) and then rejecting it β€” or\\n simply by rescheduling to a time that works. Refused (`409`) once the\\n meeting's window has started: a\\n meeting that already began is history, not a plan. The guard sits in the\\n domain's `cancel` itself, on a fresh read compared-and-set into the row, so\\n every way of cancelling β€” the decline below included β€” inherits it.\\n- `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) β€” the teacher\\n **counter-proposes**. The times land on the *same* row as\\n `proposed_starts_at`/`proposed_ends_at`, the status goes back to `pending`\\n and `decided_by` clears, because leaving it `approved` would silently move a\\n confirmed appointment. The slot stays held meanwhile. A window that has\\n already opened is refused (`409`): the 60-second grace on the times is for\\n clock skew, not for proposing into a meeting already underway β€” one nobody\\n could then cancel.\\n- `PATCH /{id}/reschedule/accept` β€” the **requester** only: this *is* approval\\n at the new time, so the overlap guard runs again β€” and so does the\\n already-started guard (`409`). Agreeing to a window that has begun does not\\n help: the meeting could never be cancelled. The booking stays `pending`, so\\n the teacher just proposes a time that can still happen.\\n- `PATCH /{id}/reschedule/decline` β€” the requester only, and it **cancels the\\n booking**: the proposal replaced the time that was asked for, so there is\\n nothing to fall back to. The row stays readable as `cancelled` with the\\n refused proposal still on it β€” book another slot instead. Declining *is* a\\n cancel, so it answers to the cancel deadline too (`409` once the effective\\n window has started).\\n\\n**Who settled it, and why.** Every settled booking carries its own audit trail\\non the row: `decided_by` (who approved or rejected β€” cleared again by a\\ncounter-proposal), `cancelled_by` (who called it off, stamped by `cancel` and by\\na declined counter-proposal), plus the optional free text that came with the\\ndecision β€” `reject_reason` on `PATCH /{id}/reject` and `cancel_reason` on\\n`PATCH /{id}/cancel` and `/reschedule/decline`. Both reasons are optional: the\\nwhole body may be omitted, a blank one records nothing (`null`), and a present\\none is validated like the booking's own reason (≀ 1000 chars, `400` past that)\\nbefore it reaches the row. They are **not public**: bookings are only ever\\nrendered to the person who requested them and to the slot's teacher (a\\nmanager/admin acting on one by id sees the response to their own call), so\\n\\"couldn't make it, sorry\\" goes no further than the two people it concerns. Rows\\nwritten before these fields existed simply read back `null`.\\n\\nA booking's effective window is the accepted counter-proposal when there is\\none and the slot's own window otherwise; that is what `starts_at`/`ends_at` on\\nan `AppointmentResponse` report, and what the cancel deadline is judged on.\\n\\n**No double-booking.** Two `approved` meetings may never overlap for the same\\nteacher *or* the same requester (`409`). The guard runs at approval β€” the\\nmoment anyone is actually committed β€” and again on accepting a counter-proposal,\\nbecause the time moved. Approval also refuses (`409`) an **effective window\\nthat has already started** (the proposal's when one stands, the slot's\\notherwise), for the same reason booking one is refused. Requesting is checked more loosely: a booking is\\nrefused up front only when the slot's window has already started (booking it\\nwould create a meeting `cancel` refuses to undo β€” the 60-second publish grace\\nis for clock skew, not for booking into the past), when the slot is already\\ntaken, or when the *requester* is already committed at that hour; a clash on the teacher's side is theirs to\\nresolve when they decide, since refusing a request against a window they\\nthemselves published would only confuse. Touching windows never conflict.\\n\\nDeletion follows the same rule as the rest of the codebase: a slot carrying a\\nlive (pending or approved) booking refuses to go (`409`) β€” reject or cancel\\nthat booking first β€” and a series delete is all-or-nothing, `409` if *any*\\noccurrence still carries one, so the person waiting is dealt with rather than\\nleft stranded on a stray week. Settled (rejected/cancelled) bookings cascade\\naway with their slot.\\n\\n`GET /appointments` is likewise two lists: a teacher+ sees the bookings aimed\\nat their own slots (their request inbox), everyone else the ones they\\nrequested, newest first, paged. Managers and admins read their own inbox here\\ntoo β€” they may still decide any booking by id.", "source": "README.md"}, {"id": "messaging", "title": "Messaging", "body": "One-to-one, mail-style (subject + body + an optional free-text `label` the UI\\nrenders as a badge β€” \\"EtΓΌt\\", \\"SΔ±nav\\"; no threads): any user writes to any\\nuser β€” student to teacher, parent to teacher, teacher to student; only\\nmessaging yourself is refused. A single stored message serves both parties,\\nbut each **owns their copy independently**: the recipient's moves through\\n`inbox` β†’ `archive`/`trash` and carries the `read` flag (the sender sees it\\nas a read receipt); the sender's moves through `sent` β†’ `archive`/`trash`. Filing or\\ndeleting your copy never changes the other side's view.\\n\\nEvery copy remembers where it was filed from, so it can go back there. Moving\\ninto `archive`/`trash` stamps the folder you left onto the copy's\\n`previous_folder`, and restoring is a `PATCH` of `folder` back to that value:\\nan inbox message you archive and then trash returns to `archive`, and from\\nthere to `inbox`. Two folders are never stamped β€” the trash itself (pulling a\\ncopy out of the trash must not leave it pointing back at the discard pile) and\\nthe folder you are already in β€” and moving back to `inbox`/`sent` clears the\\nstamp. `previous_folder` is therefore `null` for any copy sitting in its home\\nfolder, and for copies filed before the field existed; both mean \\"restore to\\n`inbox`\\" (`sent` for the sender's copy).\\n\\nListing is per folder β€” `GET /messages?folder=` with `inbox` (default),\\n`sent`, `archive`, or `trash` (trash shows both received and sent copies you\\ntrashed) β€” newest first, paged, with sender/recipient rendered as person refs\\nplus their role. `?read=false` narrows to unread (`true` to read), and since\\n`total` counts the filtered view, `?folder=inbox&read=false&limit=1` is the\\none-row unread-badge query. `PATCH /messages/{id}` flips `read` (recipient only) or\\nmoves your copy (`folder`), restoring included. `DELETE` is\\npermanent, allowed only while your copy sits in the trash (`409` otherwise),\\nand physically removes the row once both sides have deleted theirs. Replying\\nis just sending a new message back β€” the frontend prefixes the subject if it\\nwants an `Re:`.", "source": "README.md"}, {"id": "question-pool", "title": "Question pool", "body": "Students get stuck; the pool is where the school unsticks them β€” with a\\nmoderation gate so nothing unreviewed goes school-wide. `POST /questions`\\n(students only, exact role) creates the question `pending`: only the asker\\nand teacher+ can see it (anyone else gets a `404`, not a `403` β€” a pending\\nquestion's existence is nobody else's business), and `GET\\n/questions?status=pending` is a teacher's approval queue. The asker may\\nattach **one photo** of the problem (`POST /questions/{id}/image`,\\n`multipart/form-data` with a `file` part β€” raster types only, no SVG, ≀ the\\nschool's `max_file_bytes`), replace it, or remove it β€” while pending only.\\n\\n`POST /questions/{id}/approve` (teacher+) publishes it: the question becomes\\nreadable by every signed-in user above `parent`, and its content β€” title,\\nbody, photo β€” **freezes**, because an edit after approval would bypass the\\nmoderation that just happened. There is no rejected state and no edit\\nendpoint: to fix a typo the asker deletes and re-asks; to reject, a teacher+\\ndeletes. Approving twice is a `409`; the response records `approved_by`.\\n\\nAnyone in the school (student through admin β€” not parents) may then offer a\\n**solution**: `POST /questions/{id}/solutions` with a text body, listed\\noldest-first like a discussion thread (`GET`, paged). Solutions are the\\nunmoderated half of the pool, so nothing about them ever freezes: the author\\nβ€” and only the author, teacher+ included out β€” may edit the body (`PATCH\\n/questions/{id}/solutions/{sid}`) and attach one **photo** of the worked\\nsteps (`POST /questions/{id}/solutions/{sid}/image`, same raster-only rules\\nand `max_file_bytes` cap as the question's photo), replace it, or remove it,\\nat any time; moderation stays delete-only β€” a teacher+ removes a bad\\nsolution, never rewrites someone else's words. A solution is deleted by its\\nauthor or by teacher+, its photo blob going with it; deleting a question β€”\\nasker withdrawing, or teacher+ moderating β€” takes its solutions and every\\nphoto blob (its own and its solutions') with it. Each question row reports\\nits `solution_count`, and questions and solutions embed their people as\\nperson refs (`{id, username, display_name}`), so the UI never shows a raw\\nULID.", "source": "README.md"}, {"id": "per-school-policy-settings-terms", "title": "Per-school policy (settings & terms)", "body": "Every school runs differently; the parts that vary are data, not code. One\\neditable `settings` singleton (`GET /settings` for any signed-in user,\\n`PATCH /settings` for manager+) carries seven knobs:\\n\\n- **`exam_kinds`** β€” the accepted `kind` values for new exams, each an\\n object `{name, weight}`. The weight (`1`–`100`) is how many times an exam\\n of that kind counts into its course average β€” weighting is school policy,\\n set once per kind, never per exam. Defaults to `homework, quiz, midterm,\\n final, project, oral`, all weighing `1` (a plain average); replace the\\n list with whatever the school grades and weighs (`{\\"name\\": \\"final\\",\\n \\"weight\\": 3}`, …). Reports resolve weights live: editing a weight\\n re-weights every exam of that kind at once. For the same reason a kind\\n whose exams already carry marks cannot be removed from the list (`409`):\\n those marks would silently re-weight. An unmarked kind leaves freely, and\\n an exam keeping a since-removed kind counts with weight `1` β€” but it can no\\n longer be graded (`409`) until the school offers that kind again, which is\\n what keeps \\"a marked kind cannot be removed\\" true from both ends. The same\\n rule pointed at one exam: an exam that already carries marks keeps its\\n `kind` (`PATCH /exams/{id}` answers `409`), because re-pointing it would\\n re-weight those marks just as silently.\\n- **`attendance_statuses`** β€” what attendance marking accepts. The core four\\n (`present`, `absent`, `late`, `excused`) are mandatory because the\\n attendance rate is defined over them (`(present+late) /\\n (present+absent+late)`); school extras (say `online`) are **rate-neutral**\\n and tally under `custom` in the attendance reports.\\n- **`grade_bands`** β€” how numeric marks display: a list of `{min, label}`\\n bands (`85 β†’ \\"AA\\"`, `50 β†’ \\"CC\\"`, …). One band must start at `0` so every\\n mark maps; an empty list (the default) means numeric-only. Storage and\\n averaging stay `0`–`100` forever β€” bands only add `grade`,\\n `average_grade`, and `overall_grade` labels to the mark report, so a school\\n can switch display scales without touching a single stored mark.\\n- **`max_file_bytes`** β€” the per-file size cap for uploads (note files and\\n exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;\\n a server hard cap β€” uploads buffer in memory), default `5242880` (5 MiB).\\n Checked at upload time only: lowering it never touches already-stored files.\\n- **`chatbot_history_turns`** β€” how many prior **messages** of a thread the\\n chatbot is given as context, `1`–`50` (default `10`). The unit is messages,\\n not exchanges: a question and its answer are two, so the default remembers\\n five question/answer pairs. Every one of them is re-sent on every reply, so\\n the number is both what the bot remembers and what each answer costs.\\n- **`max_chatbot_threads`** β€” how many chatbot threads one user may\\n keep, `1`–`500` (default `50`); at the cap the user deletes an old one\\n first. Storage protection, not a usage quota β€” that is the per-minute\\n message limit.\\n- **`max_chatbot_message_len`** β€” character limit on one chat message,\\n `100`–`8000` (default `4000`); the ceiling is a server hard cap, because\\n the message and its history must fit one bridge frame.\\n\\nA `PATCH` replaces only the fields it carries, each wholesale, and validation\\nis all-or-nothing. Concurrent edits are safe: each save applies only if the\\npolicy still matches the snapshot it merged from (retrying over the fresh row\\notherwise), so two managers patching different fields both land instead of\\nthe later write silently reverting the earlier one. Editing a list never\\nrewrites history: an exam keeps its retired kind, a roll-call row keeps its\\nretired status β€” only **new writes** are held to the current lists (which is\\nwhy grading an exam whose kind has left the list is refused).\\n\\nThe kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see \\"Food program: menus, dishes, bookings & the ledger\\").\\n\\nAcademic structure is data too. **Terms** (`/terms`) model whatever calendar\\nthe school runs β€” semester, trimester, quarter systems are just rows with a\\nname and a date range. Courses may link to one via `term_id` (nullable), and\\ndeleting a term is refused with a `409` while any course still links to it β€”\\nunlink those courses (`PATCH /courses/{id}` with `\\"term_id\\": null`) or delete\\nthem first, so the calendar never disappears under them. Term dates may lie in the past,\\ndeliberately: a school adopting the app mid-year backfills its calendar β€”\\nunlike exam/lesson/event times, which reject backdating.\\n\\nWhat stays fixed is deliberate too: the four roles, the `0`–`100` mark scale,\\nvalidation bounds, and the UTC time policy are invariants, not preferences\\n(rename role labels in the frontend if a school says \\"principal\\" instead of\\n\\"manager\\"). Deployment knobs (ports, rate limits, admin seed, CORS) remain\\nenvironment variables β€” the model is **one school per deployment**, which\\nkeeps every school's data physically isolated.", "source": "README.md"}, {"id": "food-program-menus-dishes-bookings-attendance-the-ledger", "title": "Food program: menus, dishes, bookings, attendance & the ledger", "body": "The school publishes **one menu per calendar day and meal slot** (`POST\\n/meals/menus`). Two shapes there are deliberate:\\n\\n- **`date` is text**, `YYYY-MM-DD`, not a timestamp. \\"One menu per day and\\n slot\\" is an equality test on the school's own day, and a midnight-in-millis\\n day is only unique for one timezone. Fixed-width and zero-padded, so the\\n text sorts chronologically β€” which is what the inclusive `?from=&to=` range\\n filter and the newest-day-first ordering are built on.\\n- **`slot` is a snapshot**, not a link into settings. It must be one of the\\n school's `meal_slots` (`GET /settings`) *when the menu is written*, and it\\n is stored as text β€” so retiring a slot later never rewrites a menu already\\n published under it. The slot's `serving_minute` is *not* snapshotted: the\\n booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any\\n menu was published for cannot be removed from the list (`409`), same\\n contract exam kinds have with graded exams.\\n\\nThe day+slot pair is unique: a second publish for the same meal answers `409`\\nβ€” edit the first one instead. Only `capacity` is patchable (`null` = uncapped)\\nβ€” `date` and `slot` are immutable, because a menu on another day is another\\nmenu.\\n\\n**Dishes** hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, then\\n`PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional\\ndescription (blank or `null` clears it), dietary `tags` drawn from the\\nschool's `dietary_tags` list β€” an unknown tag is a `400`, never a stored\\nstring β€” and a `price_minor`.\\n\\n### Dietary profiles and conflicts\\n\\nA student carries a **dietary profile**: a list of tags plus a free-text note\\nfor the kitchen, one row per student (the record key *is* the student's id).\\nThe tags come from the *same* `dietary_tags` list a dish is tagged from β€”\\nthere is deliberately no second vocabulary, because one shared list is exactly\\nwhat makes \\"is this dish a problem for this student\\" answerable as a set\\nintersection, without the backend knowing any nutrition.\\n\\nWriting it is **manager+** (`PATCH /meals/profiles/{user}`, first write\\ncreates the row). A student does *not* edit their own allergen list: it is a\\nsafety record the school keeps on their behalf, and a mistyped β€” or quietly\\nremoved β€” allergy would otherwise reach the kitchen with the school's\\nauthority behind it. Reading is `GET /meals/profiles/me`, or\\n`GET /meals/profiles/{user}` under the usual per-student gate (own id always,\\notherwise teacher+ or a parent link). A student who was never recorded reads\\nback as an *empty* profile rather than a `404` β€” \\"nothing known\\" is an answer.\\n\\nEvery dish a menu read returns therefore carries a **`conflicts`** list: the\\nintersection of that dish's `tags` with the **calling user's** profile tags.\\nIt is empty when the two do not overlap, and empty for every reader without a\\nprofile β€” a manager reading a menu sees `conflicts: []`, which is correct and\\nnot a bug (the field answers \\"may *I* eat this\\", and there is no \\"conflicts\\nfor student X\\" parameter). The caller's profile is loaded **once per request**,\\nnot per dish, so the menu list stays at its fixed query count no matter how\\nmany menus or dishes the page holds.\\n\\n**Money is minor units** (kuruş) as an integer, at every layer: `4550` is\\n45,50 β‚Ί. This API never speaks decimals or floats about money, so no rounding\\nis ever introduced by transport or by a client's JSON number parser.\\n\\nReads are open to every authenticated user β€” a student has to see what is\\nbeing served β€” and every write is manager+. Deleting a menu takes its dishes\\nwith it: a dish has no meaning apart from the menu it was published on.\\n\\n**Bookings** are seats on a published menu (`POST\\n/meals/menus/{id}/bookings`). One row per (menu, student), keyed by a\\ndeterministic composite id, so booking twice is the same seat and never a\\nsecond one. A **student books only for themselves**; a **parent books for a\\nstudent they hold a link to** β€” the one write a `parent_link` authorises, since\\npaying for lunch is a parent's job. Nobody else books through this route: a\\nteacher or manager ordering a child's lunch is a `403`.\\n\\n- **Cancelling is a status flip, not a delete** (`DELETE\\n /meals/bookings/{bid}` answers `200` with the flipped row): the row survives\\n as `cancelled` with a `cancelled_at` stamp, so a freed seat stays auditable\\n against the money it moved. Only `booked` rows count against `capacity`,\\n which is what genuinely frees the seat β€” and re-booking is the same row\\n flipped back. The call is **idempotent**: cancelling an already-cancelled\\n seat answers `200` with the row as it stands *and replays the refund*, so a\\n cancel cut short between the flip and the reversal (the tab closed, a proxy\\n timed out) is recovered by sending it again. Refusing it as a `409` β€” as it\\n once did β€” made that state permanent: no route could append the missing\\n reversal, and the student stayed billed for a seat they no longer held.\\n- **The capacity check is serialized in-process.** Counting rows and then\\n writing one is write-skew: SurrealDB does not conflict-check a cross-record\\n count against a concurrent insert, so 24 students racing for 3 seats would\\n otherwise all pass the count. The whole check-then-write runs under the same\\n lock a menu publish takes, and the cap is re-read inside it.\\n- **One cutoff closes both ends.** Within the school's\\n `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new\\n booking nor a cancellation lands (`409`) β€” the kitchen's headcount has to\\n settle at some point. `null` (the default) means no cutoff at all. The\\n cutoff is measured back from the menu's `date` **plus the slot's\\n `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served\\n at `720` closes at 10:00 UTC that morning, not at 22:00 the night before.\\n **That minute is UTC**: `date` carries no timezone and the backend stores no\\n school timezone β€” deliberately, it is a rejected feature β€” so a UTC+3 school\\n enters `540` (09:00 UTC) for a meal served at noon locally. A slot with no\\n `serving_minute` falls back to **midnight UTC starting the meal's day**, the\\n behaviour every booking had before the field existed; the booking is never\\n refused for want of a serving time.\\n- **The serving time is read live, not snapshotted onto the menu.** The cutoff\\n minutes are already read live, so freezing the other half of the same\\n deadline would make one policy edit apply and its twin not; a kitchen that\\n moves lunch an hour later wants today's menus to move with it. The menu\\n still snapshots the slot *name* (that is what keeps a retired slot's history\\n readable), so a menu whose slot has since left the list simply has no\\n serving time and falls back to midnight UTC.\\n- A menu somebody still holds a seat on **cannot be unpublished** (`409`) β€”\\n cancel the bookings first, so nothing is left pointing at a deleted meal.\\n\\n`GET /meals/bookings/me` is the caller's own list: the seats held *for* them\\nplus, for a parent, the seats held for every student they **currently** hold a\\nlink to β€” so a parent's list is their children's meals. The links are re-read\\non every call rather than trusted from the booking's `booked_by` stamp: an\\nunlinked parent stops seeing the child's seats at once, including the ones\\nthey booked and paid for themselves, exactly like every other parent read. `GET /meals/menus/{id}/bookings` is the kitchen's list for\\none menu (manager+), cancelled rows included so the changes are visible.\\n\\n### Meal attendance\\n\\nWhoever stands at the canteen door records who actually ate:\\n`POST /meals/menus/{id}/attendance` with `{student_id, status}`, teacher+ (a\\nstudent never marks, not even themselves). The status is the fixed pair\\n`served` / `missed` β€” deliberately **not** the school's editable\\n`attendance_statuses`, since a canteen line has no \\"late\\" or \\"excused\\", and one\\nlist meaning two things would let a school change one by editing the other.\\nOne row per (menu, student) keyed by a composite id, so a correction re-marks\\nthe same row instead of stacking a second one.\\n\\n**Attendance has zero billing effect.** Booking is the sole charge trigger, so\\na student who booked and did not eat still pays β€” the kitchen bought the food.\\nThere is no no-show penalty, no refund-on-missed, and no auto-reversal:\\nnothing under `meal_attendance` writes to the ledger. A walk-in with no live\\nbooking *can* be marked `served` (the record is operationally true) and is\\nlikewise not charged for it β€” charging there would be a ledger write. The\\ntarget only has to *exist*: a canteen also feeds staff, so any user may be\\nmarked, not only a student. A mark is a record of what happened, not a check\\nof who was entitled, and since it moves no money it costs nobody anything.\\n\\n`GET /meals/menus/{id}/attendance` is the per-menu list (teacher+), and\\n`GET /meals/attendance/{user}` is one student's history, narrowable with\\n`?from=&to=` β€” inclusive `YYYY-MM-DD` bounds compared against the *menu's*\\nday, a lexical compare that is chronological for that format. Same gate as the\\nbalance and the ledger: the caller's own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`meal_ledger`): one line per `charge`,\\n`credit`, or `reversal`, every field `READONLY`, and **no code path anywhere\\nthat updates or deletes one**. A ledger line that can be edited or dropped\\nsilently rewrites a student's financial history with no trace of the rewrite β€”\\nthis is the one genuinely irreversible part of the food program, so a mistake\\nis corrected by appending the opposing line, which leaves both the mistake and\\nthe correction visible.\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer.\\nA *negative* balance means the student owes the school; a positive one is\\nmoney on account. Amounts are stored positive; the sign lives in the `kind`.\\n\\n- **Booking is what charges, at a price snapshot.** The menu's dishes are\\n summed the moment the seat is taken and that number is frozen onto the\\n charge. Editing a dish's price afterwards moves no existing charge β€” what a\\n student owes is what the menu cost the day they booked. The price is\\n snapshotted *before* the seat is given, so a menu that cannot be charged\\n refuses the booking rather than leaving a booked-but-unbilled row (`400`,\\n when the dishes sum past 10 000 000). A free menu writes no line at all β€”\\n but the booking row records that it *was* free, so \\"free when taken\\" is\\n never confused with \\"not billed yet\\": pricing the menu afterwards leaves\\n every seat already taken on it free.\\n- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its\\n money move together under one in-process lock, and the ledger id is derived\\n from the seat plus how many times it has been taken β€” so eight simultaneous\\n `POST`s of one seat write one charge, a retried cancel refunds once, and a\\n write that failed halfway heals when the request is repeated. Booking the\\n same seat twice bills once because the *identity* is the same, never\\n because a scan happened to see the first charge in time.\\n- **Cancelling appends a `reversal`** for the charge's exact amount, with\\n `source` pointing at the charge it undoes. The charge row itself stays. A\\n cancel past the cutoff is already a `409`, so a reversal only ever follows a\\n legal cancel β€” and repeating a cancel replays the reversal, which is what\\n makes the refund recoverable rather than a one-shot the network can lose.\\n Re-booking afterwards is a **fresh** charge at the then-current price.\\n- **The price snapshot is taken under the booking lock**, and dish\\n create/edit/delete take that same lock. Taken outside it, a dish added\\n between the sum and the seat would be frozen onto the row as \\"the menu was\\n free then\\" β€” and nothing heals it, since a seat already held is returned\\n as-is, never re-priced.\\n- **A no-show still pays.** Meal attendance has zero billing effect β€” nothing\\n in the ledger reads or writes it. The seat was reserved and the food was\\n cooked; there is no no-show penalty and no no-show refund.\\n- **`POST /meals/credits` is admin-only**, not manager: writing down cash\\n received is the highest-trust action in the app. It appends a `credit` for a\\n student with a positive `amount_minor` (≀ 10 000 000), an optional `method`\\n (\\"cash\\", \\"havale\\", …) and `note`, and records the admin as `recorded_by`.\\n There is no payment gateway and no card data, ever. An over-credit is\\n corrected with a compensating line, never a fix-up.\\n\\n`GET /meals/balance/me` is the caller's own balance. `GET\\n/meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line\\nfirst) read a student's: your own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student. A charge's `source` is the\\nbooking id it came from, a reversal's is the charge line it reverses, and a\\ncredit has none.", "source": "README.md"}, {"id": "payments-fee-plans-assignment-the-fee-ledger", "title": "Payments: fee plans, assignment & the fee ledger", "body": "School fees live in their own tables (`fee_plan`, `fee_plan_assignment`,\\n`payment_ledger`) and their own balance. **Meal money is separate** β€” two\\nledgers, two balances, and no route folds one into the other: what a family\\nowes the canteen and what it owes the school are different debts, and mixing\\nthem would make either statement unreadable.\\n\\nEvery write here is **manager+**. Reads are narrower than the other\\nper-student reports: the student themselves, a parent holding a live link to\\nthem, or manager+ β€” **a teacher gets a `403` on every `/payments` route**,\\nbecause what a family owes the school is not classroom information.\\n\\n### Fee plans and what turns them into money\\n\\nA **fee plan** (`POST /payments/plans`) is a name and 1 to 60 **installments**,\\neach `{amount_minor, due_at}` β€” minor units (kuruş) as an integer, and unix\\nmilliseconds. `due_at` **may be in the past**: a school adopting the app\\nmid-year assigns plans whose first installments were already due, so there is\\nno future-date rule here.\\n\\nWriting a plan bills nobody. **Assigning it does** (`POST\\n/payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call):\\nthat appends *every* installment as a `charge` line right away, each carrying\\nits own due date. There is no scheduler, no nightly sweep, and nothing that\\nwakes up when a date passes β€” the whole schedule is written once, and lateness\\nis read off it.\\n\\nAssignment is **replay-safe by identity**: the assignment row is keyed\\n(plan, student) and every charge it raises is keyed (plan, student,\\ninstallment), so re-assigning bills nothing a second time (that student comes\\nback `already_assigned`), and an assignment cut short after three of twelve\\ncharges landed completes itself when the call is simply repeated. Only\\nstudents carry a fee record, so any other target comes back `rejected` β€” one\\nbad id never loses the rest of the batch.\\n\\nA plan that has been assigned to anyone can no longer be edited or deleted\\n(`409`). Its charges are frozen copies of the installments as they stood, so\\nan edit would only make the plan and the money tell different stories β€” write\\na new plan instead.\\n\\nThat freeze is a **counter on the plan row** (`assignment_count`), incremented\\nin the *same transaction* as the assignment row it counts, and the edit and the\\ndelete are single-record conditional writes against it β€” the same shape as a\\nterm's `course_count`. It used to be a `SELECT` taken before the write, which a\\nconcurrent assign could land behind, leaving a plan edited *and* assigned, or\\ndeleted with a live assignment naming it. Now the two contend on one record: an\\nassign either freezes the plan first (and the edit or delete is a `409`) or\\narrives after it (and bills the edited plan β€” the installments a first\\nassignment charges are re-read from the *stored* plan at the instant it\\nfreezes, never from the copy the request first looked at). A plan deleted out\\nfrom under a running batch is `rejected` for that student on, in the same\\nper-student report as every other outcome β€” the students it already billed are\\nnever dropped from the answer. A `PATCH`\\ncarrying no field at all writes nothing, so it is not refused.\\n\\nBecause an assignment is never removed, the counter is only ever claimed and\\nnever released: once assigned, a plan stays frozen for good. Plans written\\nbefore the counter existed are seeded from their assignment rows at boot,\\nbefore the server accepts a request β€” an absent counter reads as zero, and a\\nzero would have re-opened every already-assigned plan on an existing volume.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`payment_ledger`), exactly like the\\nmeal one: every field `READONLY`, and **no code path anywhere that updates or\\ndeletes a line**. A ledger line that can be edited or dropped silently\\nrewrites a family's financial history with no trace of the rewrite, so a\\nmistake is corrected by appending the **opposing line**, which leaves both the\\nmistake and the correction visible.\\n\\nFour kinds, and the sign lives in the `kind` β€” amounts are always stored\\npositive:\\n\\n| Kind | Sign | What it records | `source` points at |\\n| ---------- | ---- | ------------------------------------------------ | ------------------ |\\n| `charge` | βˆ’1 | An installment billed by a plan assignment | the assignment |\\n| `credit` | +1 | Money received, against one named charge | the charge paid |\\n| `reversal` | +1 | A `charge` or `refund` entered in error, undone | the undone line |\\n| `refund` | βˆ’1 | Money handed back, against one named payment | the credit returned |\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge) - SUM(refund)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer. A\\n*negative* balance means the family owes the school; a positive one is money on\\naccount.\\n\\n- **A payment names the charge it settles.** `POST /payments/credits` takes\\n `{charge_id, amount_minor, method?, note?}`: allocation is *recorded*, never\\n inferred from a balance, so a statement can say which installment is still\\n open rather than only how much is outstanding. **Partial payments are the\\n norm** β€” several credits accumulate against one charge.\\n- **A refund names the payment it returns.** `POST /payments/refunds` takes\\n `{credit_id, …}`, partials allowed, capped by what that credit was worth.\\n This is also the **only** way a mistaken credit is corrected: a credit is\\n never reversed, so money leaving the school is always spelled the one way.\\n- **A retry is not a second payment β€” when the client says so.** Both routes\\n take an optional `request_key` (`[A-Za-z0-9-]`, 1 to 64 characters β€” `_` is\\n the separator inside a ledger id, so a key may not carry one). With\\n one, the line is keyed `<charge>_k_<key>` (a refund: `<credit>_kr_<key>`), so\\n a client retrying after a network timeout gets **the line the first attempt\\n wrote**, not a second charge on the family β€” idempotence by identity, the\\n same rule that keeps a replayed assignment from billing twice, never a \\"has\\n this been recorded yet?\\" scan two concurrent requests can both walk past. The\\n replay is answered **before** the over-payment cap is consulted, so a payment\\n that filled its charge to the penny still replays as itself instead of coming\\n back \\"already paid in full\\". Sending that key again with a **different**\\n `amount_minor` or a different target is a `409`, never the stored line: that\\n is a client bug, and a `201` would bury it. Omit the key and nothing changes\\n from before β€” two identical posts are two payments, which is exactly what a\\n desk taking the same amount twice means.\\n- **A reversal only undoes a `charge` or a `refund`**, for its exact amount and\\n nothing else (`400` on any other kind). It is keyed `<line>_r`, so a line has\\n at most one reversal however often the call is retried, and the reversed line\\n itself stays on the record beside it.\\n- **A refund frees the charge's room.** The cap on a payment is folded over the\\n target's whole source subtree, so refunding a payment gives that charge its\\n room back and the charge **can be paid again** β€” and reversing that refund\\n takes the room back with it. Money that came back out is not money the school\\n still holds.\\n- **The over-payment cap is not the database's.** The `409` past a charge's or\\n a credit's worth is a cross-record fold, which SurrealDB cannot enforce on\\n its own; it holds because the backend is one process and the fold, and the\\n append it authorizes, are taken under one lock. Should an over-payment ever\\n be recorded anyway it is not a crisis: this is human data entry at an office\\n desk, the outcome is an over-paid charge that is plainly visible in the\\n statement, and it is undone by appending a refund. Both lines are true\\n records of money that really arrived β€” refusing them would be the worse lie.\\n- **There is no payment gateway and no card data, ever**, and none is planned:\\n nothing here talks to a bank, a PSP, or a card network. `method` is free text\\n (\\"cash\\", \\"havale\\", …) describing how money that already arrived was handed\\n over, and `note` is whatever the office needs to remember (a receipt number,\\n say).\\n\\n### Statements, balances and `overdue`\\n\\n`GET /payments/ledger/{user}` is the raw lines, newest first, paged.\\n`GET /payments/statement/me` and `/payments/statement/{user}` are the\\n**per-charge rollup** (its rows paged by the usual opt-in `?limit=&offset=`,\\nin an `entries: {items, total, limit, offset}` envelope): one row per charge with its plan, the installment's\\namount and due date, what it collected, what went back out, what is still\\noutstanding, whether the charge itself was reversed (such a charge owes\\nnothing), and whether it is **`overdue`** β€” still owed, and its `due_at` has\\npassed.\\n\\nAll of that is folded from the raw lines **on every request and stored\\nnowhere**, `overdue` included. Paging windows the *returned rows* only, after\\nthat fold: `balance_minor` β€” and every row's own arithmetic β€” is identical on\\nevery page, because it is read from all of the student's lines either way. There is no overdue flag, no sweep that sets\\none, and no stored rollup: a stored rollup is a second version of the truth,\\nand the ledger is the first. `GET /payments/balance/me` and\\n`/payments/balance/{user}` are the same fold reduced to one number.", "source": "README.md"}, {"id": "exam-modes-attempts-retakes-rejoin-live-monitoring", "title": "Exam modes, attempts, retakes, rejoin & live monitoring", "body": "Preparing an exam is slow work, so an exam can be created as a **draft**\\n(`draft: true`): only the course's managers see it (to students it's a `404`\\nthat might as well not exist β€” lists, direct reads, and attempts all hide\\nit), nobody can sit it, and grading it is a `409`. The teacher builds the\\nquestions in peace and publishes with `PATCH /exams/{id}` `{\\"draft\\": false}`.\\nAn exam can go back into hiding the same way β€” but only while it has **no\\nattempts and no results**; after that, re-drafting is a `409` (students never\\nlose sight of an exam they've sat or been graded on). Existing exams (and\\nthose created without the flag) are published from the start.\\n\\nSeparately from drafts, a published exam without a `mode` (all schedule\\nfields `null`) is **offline-graded** β€” a paper exam whose marks are entered\\nby hand; students see it and their marks, but attempts on it are a `409`\\n(\\"nothing to sit\\"). Making an exam sittable means giving it a `mode`, as one\\nconsistent unit (validated together on create and after every `PATCH` merge):\\n\\n- `mode: \\"sync\\"` + `starts_at` + `ends_at` β€” everyone sits inside one window;\\n every attempt's deadline is `ends_at`.\\n- `mode: \\"async\\"` + `starts_at` + `ends_at` + `duration_ms` β€” each student\\n starts anywhere inside the window and gets\\n `min(started_at + duration_ms, ends_at)` as their personal deadline.\\n- `mode: \\"open\\"` β€” no window at all: students sit anytime. `duration_ms` is\\n *optional* β€” set it for a per-attempt countdown (`started_at +\\n duration_ms`), omit it for unlimited time (the attempt only ends by\\n submission).\\n- `duration_ms` is 1 minute to 24 hours wherever it appears, and for `async`\\n cannot exceed the `starts_at`..`ends_at` window (equal to it is fine).\\n `ends_at` must be strictly after `starts_at`, and neither may be *set* in\\n the past β€” on create or `PATCH` (kept values are exempt, so a running exam\\n stays editable). All instants are the usual UTC unix-milliseconds, judged\\n only by the server clock (`GET /time` for sync).\\n\\nTwo per-exam policy knobs ride along, both **live-editable** at any point:\\n\\n- `max_attempts` (default `1`, `0` = unlimited) β€” how many sittings each\\n student gets. Raising it mid-exam grants retakes on the spot; lowering it\\n never kills a running attempt, it only blocks future starts.\\n- `allow_rejoin` (default `true`) β€” whether a student who *left the exam room*\\n may come back in and keep answering (see the exam-room section).\\n- `allow_review` (default `false`) β€” opt-in door to the student self-review\\n reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A\\n student may review only when this is on **and** the teacher has marked them\\n (an `ExamResult` row exists); own-scoped, so no student reads another's sheet.\\n\\nA student **sits** an exam through attempts (sitting 1, 2, … β€” each row id is\\nthe composite `exam_user[_seq]` key, so a sitting exists at most once by\\nconstruction):\\n\\n- `POST /exams/{id}/attempt` starts, resumes, or retakes (students only β€”\\n staff never sit; enrolled; window open where one exists β€” `open` exams start\\n anytime). While the latest\\n sitting runs, re-posting returns it unchanged (`200`, not `201`):\\n reconnecting never resets the clock. Once it is submitted or expired,\\n re-posting mints the next sitting (`201`) **from a blank answer sheet** β€”\\n the previous sitting's answers are wiped β€” until `max_attempts` is spent\\n (`409` after that). Starting is the live-attendance signal.\\n- `GET /exams/{id}/attempt` is the student's exam screen: the latest sitting's\\n `status` (`in_progress` | `submitted` | `expired`), `attempt` (its number),\\n `attempts_used`/`max_attempts`, `deadline`/`remaining_ms` (`null` for an\\n untimed open exam), `left_at`, own `mark` once graded, and the server `now`.\\n- `POST /exams/{id}/attempt/finish` submits. After the deadline the attempt is\\n `expired` β€” a valid terminal state (the student used their full time), and\\n finishing answers `409`. Grading stays per exam+user (one mark), whatever\\n the sitting count β€” the sheet a grader sees is always the latest sitting's.\\n\\nDeadlines are **recomputed from the exam's current schedule on every read**,\\nnever stored: a teacher who `PATCH`es `ends_at` (or a `duration_ms`)\\nwhile the exam runs moves every running deadline instantly. What's frozen once\\nanyone has started is only `mode` (including back to unscheduled) β€” swapping\\nthe deadline rules mid-sitting would be a different exam (`409`).\\n\\nThe course's manager (its creator, or manager+) watches it all live:\\n`GET /exams/{id}/live` returns one snapshot β€”\\nthe enrolled roster joined with attempts and marks (`not_started` | `absent` |\\n`in_progress` | `submitted` | `expired`, per-student `attempt` /\\n`attempts_used` / `left_at` / `deadline` / `remaining_ms` / `mark`, always the\\nlatest sitting) plus summary counts, all judged at a single `now`. Once the\\nwindow closes, `not_started` hardens into `absent` β€” the no-shows, flagged\\nright in the roster (open exams have no window, so never an `absent`). The\\nflag is informational: an absent student still has no mark until the teacher\\nrecords one through `POST /exams/{id}/results`. Poll `GET /exams/{id}/live` to\\nkeep a monitor current β€” attendance, ticking clocks, submissions, and marks all\\nride in each snapshot.\\n\\nDeleting an exam (or its course) cascades attempts, questions, answers, and\\nquestion + answer images (blobs included) along with results; unenrolling mid-exam\\nhides the student from the monitor roster but keeps the attempt and mark\\nrows, mirroring the marks report.\\n\\n> **Upgrading a pre-course database**: `exam` rows created before courses\\n> existed lack the now-required `course` field and will fail to deserialize.\\n> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data,\\n> backfill manually with the SurrealDB CLI (server stopped), e.g.\\n> `UPDATE exam SET course = course:<id> WHERE course = NONE;`\\n> after creating a course to attach them to.\\n>\\n> **Upgrading to the attempts/rejoin build needs nothing manual**: the boot\\n> migration backfills `max_attempts = 1`, `allow_rejoin = true`, and attempt\\n> `seq = 1` on existing rows, and swaps the single-attempt unique index for\\n> the per-sitting one. Pre-upgrade attempts keep their record ids and count\\n> as sitting #1.\\n>\\n> **Upgrading to the kind-weight build is a clean break**: weights moved off\\n> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with\\n> no data migration. A database from an older build has string kinds and a\\n> per-exam `weight` column the code no longer understands β€” delete\\n> `./data/hezarfen.db` and reboot.", "source": "README.md"}, {"id": "taking-an-exam-questions-answers-the-exam-room", "title": "Taking an exam: questions, answers & the exam room", "body": "Teachers author a question list per exam; students answer inside their\\nattempt, autosaved as they go; choice questions are machine-checked as a\\n**suggestion** β€” the final mark stays a human call through the existing\\n`POST /exams/{id}/results`.\\n\\n**Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`,\\ncourse-management rights): each has a mandatory `subject_id` (one of the\\ncourse's subjects, `GET /courses/{id}/subjects` β€” the topic the question\\nbelongs to), `text` (≀ 2000 chars), `points` `1`–`100`\\n(its share of the auto-score), and a `kind`:\\n\\n- `kind: \\"choice\\"` β€” carries `choices` (2–10 options, each ≀ 500 chars) and\\n `correct`, the zero-based index of the right option. Auto-scorable.\\n- `kind: \\"text\\"` β€” free text, judged by the grader; carries neither.\\n\\nThe kind bundle is validated as a unit (create and after every `PATCH` merge):\\nswitching a question to `text` needs explicit `\\"choices\\": null, \\"correct\\":\\nnull`, switching to `choice` must bring both along. Presentation order is\\ncreation order. The whole list **freezes once anyone has started an attempt**\\n(`409` on create/edit/delete) β€” editing questions under a sitting student\\nwould fork what \\"the exam\\" means. Deleting a question cascades its answers\\nand images.\\n\\n**Question images**: any question may carry one **illustration** (`POST\\n/exams/{id}/questions/{qid}/image` β€” the map the prompt asks about, on\\n`choice` and `text` questions alike), and each option of a `choice` question\\nmay carry a **picture** of its own (`POST .../choices/{choice_id}/image` β€” so\\nthe options themselves can be images: four map crops, pick the right one).\\nUploads are `multipart/form-data` with a single `file` part, capped by the\\nschool's `max_file_bytes`; the declared content type must be `image/png`,\\n`image/jpeg`, `image/webp`, or `image/gif` (rasters only β€” SVG can script,\\nand these bytes render inline for the whole class). One image per slot:\\nre-uploading replaces, `DELETE` on the same paths removes, and replacing a\\nquestion's `choices` list drops all its option pictures (the illustration\\nstays β€” re-upload against the new list). Image writes follow question\\nauthoring exactly: course-management rights, frozen once attempts exist.\\nBoth question views (`GET /exams/{id}/questions` and the sitting view)\\nembed the metadata as `image: {content_type, size} | null` and\\n`choice_images: [...|null]` aligned with `choices`; the bytes come from the\\n`GET` endpoints above β€” course managers anytime, students through the same\\nenrollment + started-attempt wall as the sitting view (no early peek at the\\npictures either), served with `Cache-Control: private, no-store`.\\n\\n**Answering** (student, attempt `in_progress`, deadline judged by the server\\nclock on every save):\\n\\n- `GET /exams/{id}/attempt/questions` β€” the sitting view. Requires\\n enrollment (`403` β€” the questions are course content, so leaving the course\\n closes them) and an attempt (`404` before `POST /exams/{id}/attempt`; also\\n the anti-peek gate), never contains `correct`, and embeds the caller's own\\n saved answer per question (`{selected, text, updated_at}` or `null`). Still\\n readable after submitting/expiry, for review.\\n- `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` β€” an\\n upsert: one row per question+user, re-answering overwrites. The payload must\\n match the question's kind (`selected` indexing a choice, or `text`\\n ≀ 10 000 chars β€” empty clears the draft); mismatches are `400`s. Requires\\n the student role and enrollment (`403`): a promotion out of `student` or an\\n unenrollment mid-exam closes the sheet (the exam room's door checks,\\n re-applied to every save β€” finishing stays open). Once the\\n attempt is submitted or past its deadline every save is a `409` β€” likewise\\n while the student has left the exam room with `allow_rejoin` off; answers\\n saved in time survive untouched for grading. Each sitting keeps its own\\n answers, drawings, and mark, keyed by the attempt's `seq` β€” a retake starts\\n from a blank sheet without erasing the prior one, so the full per-attempt\\n history stays readable (see the grading view).\\n\\n**Answer images**: the student side mirrors the teacher's question images. A\\nstudent may attach one **drawing** to any question in their attempt β€” a\\nsketched answer or worked steps β€” via `POST\\n/exams/{id}/attempt/answers/{qid}/image` (`multipart/form-data`, one `file`\\npart, the same raster allowlist and `max_file_bytes` cap as question images).\\nOne image per question: re-uploading replaces, `DELETE` on the same path\\nremoves. Writes ride the exact `POST /exams/{id}/attempt/answers` gate β€” the\\nstudent role, enrollment, an `in_progress` attempt, and the rejoin door β€” so a\\ndrawing is just another autosaved answer; a drawing-only answer (nothing\\ntyped) still surfaces, and clearing it grooms the empty row away. The bytes\\ncome from `GET` on the same path (the caller's own, behind the sitting-view\\nwall) and, for the grader, `GET /exams/{id}/attempts/{user}/answers/{qid}/image`\\n(course-management rights); both serve inline with `Cache-Control: private,\\nno-store`. The metadata rides the answer as `answer_image: {content_type,\\nsize} | null` on both the sitting view and the grading sheet. To the backend\\nit is a normal raster PNG; the frontend piggybacks its editable stroke data in\\na PNG `tEXt` chunk, opaque here β€” stored on disk under `Config::files_path`\\nby a ULID, metadata in the `answer_image` table, structurally identical to\\nquestion images.\\n\\n**Grading view** (course-management rights): `GET /exams/{id}/attempts/{user}/answers` returns\\nthe student's **latest** sitting's sheet β€” every saved answer with `is_correct`\\n(`true`/`false` for choice, `null` for text: that's the grader's call) plus\\n`auto_score: {earned, possible}` summing the choice questions' points. It is a\\nsuggestion to read while grading, never written anywhere.\\n\\n**Per-attempt history** (course-management rights): prior sittings stay\\nreadable. `GET /exams/{id}/students/{user}/attempts` lists the sitting numbers\\na student has (every `seq` carrying answers or a mark, ascending);\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers` is the grading sheet\\nfor one of them (drawing bytes at\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image`); and\\n`GET /exams/{id}/students/{user}/marks` is the full per-sitting mark history,\\noldest first. Grading (`POST /exams/{id}/results`) always lands on the current\\nsitting, and the latest seq is the grade-of-record β€” the roster, report, and\\nstatistics reads all show it. Every result payload carries its `seq`, so a mark\\nlinks straight to that sitting's answer sheet β€” without it a marked retake's\\nanswers would be unreachable from the mark.\\n\\n**The exam room (WebSocket)** β€” `GET /exams/{id}/attempt/ws`, cookie-authed\\nlike everything else; REST above remains the full fallback. Gates run before\\nthe upgrade: unknown or draft exam `404`, unscheduled (no mode) `409`, not a\\nstudent `403`, not enrolled `403`, no attempt yet `404` (start it first),\\nsubmitted/expired `409`, left while rejoin is closed `409`. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| server β†’ | `{\\"type\\":\\"state\\", status, attempt, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save |\\n| client β†’ | `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"selected\\":1}` or `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"text\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` |\\n| server β†’ | `{\\"type\\":\\"saved\\", question_id, updated_at, client_seq?}` β€” the autosave ack |\\n| client β†’ | `{\\"type\\":\\"finish\\"}` β€” submit the attempt |\\n| server β†’ | `{\\"type\\":\\"finished\\", finished_at}`, then Close |\\n| server β†’ | `{\\"type\\":\\"expired\\"}`, then Close β€” a tick noticed the deadline |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", message, question_id?, client_seq?}` β€” bad JSON, wrong kind, deadline, … |\\n\\nAn `answer` may carry a `client_seq`: any number the client picks, echoed verbatim on\\nthat message's `saved` or `error` and on nothing else. The server never reads\\nit β€” no uniqueness, no ordering, no dedupe, all the client's business β€” and\\nomits the key entirely when the request omitted it, so leaving it out keeps\\ntoday's frames byte for byte. It exists because `question_id` is not an\\nidentity: save a question, time out, save it again, and two sends are\\noutstanding for the same id β€” the first reply would settle the second and the\\nUI would claim \\"Saved\\" for an answer the server never took. `question_id` on\\nan `error` is the separate, orthogonal question: whether the failure belongs\\nto that one question (payload or question) or to the room, in which case every\\nsave in flight is equally refused. An error can carry `client_seq` without\\n`question_id`.\\n\\nEvery tick and every save re-read the exam, so a mid-exam `ends_at` extension\\nmoves the room's countdown on the next tick, and no stale socket can write\\npast its real deadline β€” the socket shares the exact REST write path. Each\\nroom acts only on the sitting it was opened for: once that sitting is over,\\nits `answer`/`finish` are `error` frames, so a lingering socket can never\\nscribble on (or instantly submit) a retake started elsewhere.\\n\\nThe room is also the presence signal behind the **rejoin door**: connecting\\nclears the attempt's `left_at`, and the *last* socket of the sitting to close\\nwhile it is still running stamps it (visible on the live monitor β€” \\"left the\\nroom three minutes ago\\" at a glance). Closing one of two tabs is not leaving,\\nand a lingering socket from an already-finished sitting never marks a later\\nretake as left β€” each room is bound to the sitting it was opened for. With the exam's `allow_rejoin` off, a stamped\\n`left_at` refuses re-entry *and* any further saves, over the socket or REST,\\nuntil the teacher flips the door back open (`PATCH /exams/{id}\\n{\\"allow_rejoin\\": true}` β€” live, like the times). Finishing stays allowed: a\\nlocked-out student can always submit what they saved. The timer never pauses\\neither way. Students who only ever use REST never trip the door β€” the room is\\nwhat marks leaving.\\nExample client:\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/exams/${id}/attempt/ws`);\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"state\\") renderCountdown(m.remaining_ms, m.answered, m.question_count);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.question_id);\\n};\\nlet clientSeq = 0;\\nconst save = (question_id, selected) =>\\n ws.send(JSON.stringify({ type: \\"answer\\", question_id, selected, client_seq: ++clientSeq }));\\n```\\n\\nThe live monitor rides along: each roster row now carries `answered` and\\n`last_activity` (latest save instant), and the snapshot a top-level\\n`question_count`, so \\"stuck at 3/10 for five minutes\\" is visible at a glance.\\nThe student's own `GET /exams/{id}/attempt` echoes the same\\n`answered`/`question_count` pair.", "source": "README.md"}, {"id": "question-bank", "title": "Question bank", "body": "Writing good questions is slow, and the same one gets asked year after year, so\\nthe school keeps a reusable **question bank**. A bank question is an\\n`ExamQuestion` cut loose from any exam: it has the same shape (`subject_id`,\\n`text`, `kind`, `points`, and β€” for a `choice` β€” `choices` + `correct`), the\\nsame image slots (one illustration, plus a picture per option), and the same\\nnewtype validation, but it carries **no exam link**. Because nothing sits it,\\na bank row **never freezes** β€” its owner can edit or delete it forever.\\n\\n`POST /bank-questions` (teacher+) saves one, stamping the caller as its\\n**owner**. `subject_id` is origin metadata, but it must **exist** β€” an unknown\\nsubject is a `400` (create and PATCH alike). The reverse guard does **not**\\nhold here, unlike exam questions and homework: a template never blocks a\\nsubject delete, which simply clears `subject` off every template that carried\\nit (only a template's owner may re-tag it, so a `409` would be one a manager\\ncould never clear β€” and a private template raising it would leak its\\nexistence). Reads are school-wide: `GET /bank-questions` lists the\\nwhole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` β€” or\\n`?owner=me` β€” by owner) and `GET /bank-questions/{bid}` fetches one with\\n`correct` included β€” any teacher+ can browse and reuse what any colleague\\nbanked. Each response carries its **image metadata** β€” an `image` meta for the\\nillustration and a `choice_images` array aligned with `choices` (per-slot\\n`{content_type, size}`, `null` where a slot has no picture) β€” the same shape an\\nexam question's response uses; the bytes still come from the image endpoints.\\nMutation is **owner-only** (an `admin` bypasses): `PATCH /bank-questions/{bid}`\\nrevalidates the kind bundle as a unit, `DELETE /bank-questions/{bid}` drops the\\nrow and its image blobs. The illustration and option pictures work exactly like\\nan exam question's β€” `POST|GET|DELETE /bank-questions/{bid}/image` and\\n`…/choices/{choice_id}/image`, `multipart/form-data` with one `file` part, raster\\nonly (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` β€” reads school-wide,\\nwrites owner-only.\\n\\nThe bank feeds exams by **copying**, never linking. `POST\\n/exams/{id}/questions/from-bank/{bid}` instantiates a bank question into the\\nexam: it mints a **fresh** exam-scoped question (new id, its own answer rows,\\nits image blobs copied to new files), so later edits on either side never\\ntouch the other. The subject on the bank row is origin metadata only β€” the\\ncall takes its own `{subject_id}`, re-checked against the target course's\\nsubjects (`400` on a cross-course subject), and instantiating into an exam\\nthat already has attempts is a `409`, the same freeze that guards hand-authored\\nquestions. The instantiated question records the template it came from in\\n`source_bank`. The reverse, `POST /exams/{id}/questions/{qid}/to-bank`, copies\\nan existing exam question **into** the bank (new detached row, images copied to\\nnew files, owner = caller); the source question is left untouched, and the new\\ntemplate records the origin exam in `source_exam`. Both provenance fields are\\nnullable β€” a hand-authored question or template carries `null` β€” and one-way\\nmetadata (the copies stay fully detached). All bank routes are course-agnostic\\nand require teacher+.\\n\\nCopying means a template edit never reaches the copies, so there is one escape\\nhatch for that divergence: `POST /exams/{id}/questions/{qid}/refresh-from-bank`\\nre-copies the template's *current* content over one exam question β€” text,\\npoints, kind, choices (adopting the **template's** choice ids, so the option\\npictures re-land on the right options), `correct`, the illustration and the\\noption pictures. The question keeps its own id, its exam, its `subject` (the\\ntemplate's is unrelated origin metadata) and its provenance links; anything\\nedited on the copy is overwritten, deliberately. A question with no\\n`source_bank` β€” hand-authored, or its template deleted β€” is a `400`, a template\\nthe caller may not see is a `404` (never a 403), and the usual freeze applies:\\nonce any attempt exists, `409`. Every source blob is read before anything is\\nwritten, so a missing blob is a `500` with the question untouched rather than a\\nhalf-applied refresh.", "source": "README.md"}, {"id": "homework", "title": "Homework", "body": "A course hands out **homework**: `POST /courses/{id}/homework` with a title,\\nan optional description, a **required subject** (one of the course's own β€” and\\nthe same delete guard questions have: a subject with homework refuses deletion\\nwith a `409` until the homework is re-tagged via `PATCH /homework/{id}` or\\ndeleted), and a **required `due_at`** that must not lie in the past (same 60s\\ngrace as every schedule field; late *submissions* are fine β€” a late\\n*assignment* is not).\\n\\n**Audience.** By default the whole course, resolved live: whoever is enrolled\\n*when they act* β€” a student enrolled after the assignment sees and submits it\\nlike everyone else. `assigned` (at create or PATCH) instead pins a named\\nsubset of currently enrolled students (at most 200). The unnamed must not even\\nlearn a subset exists: lists omit it, and direct reads and submits answer\\n`404` β€” the same no-leak a hidden exam draft gets. Narrowing the subset later\\nis refused with a `409` that names the blockers while any submission or grade\\nbelongs to a student the new list would strand.\\n\\n**Submitting.** Students only β€” staff and parents never submit β€” enrolled and\\nin the audience, re-checked on every write. A submission is optional text plus\\nup to **10 files of any content type** (each ≀ the school's\\n`max_file_bytes`): text is replaced whole on each `POST` (omit to clear),\\nfiles are added and removed one by one, and a file upload with no prior\\nsubmission auto-creates an empty one, so a photo-only homework is a single\\nrequest. Two stamps tell the lateness story: `submitted_at` pins the **first**\\nhand-in forever, `updated_at` moves on every text edit and file add/remove,\\nand `late` is **computed on read** (`updated_at > due_at`), never stored β€” so\\ntouching work after the deadline flips it late, and a `due_at` edit re-grades\\nlateness for free. Late submissions are always accepted, only flagged. File\\nbytes always come back as a forced download (`Content-Disposition:\\nattachment`): homework accepts any content type, so rendering an uploaded\\nHTML/SVG inline would run it in the viewer's session.\\n\\n**Grading.** A course manager records a status β€” `done`, `incomplete`, or\\n`missing` β€” plus an optional 0–100 `mark` per student\\n(`POST /homework/{id}/results`, one upsert row per homework+student; the\\nexam walls apply: live students only, enrolled, in the audience, never the\\ngrader themselves). A stored grade **freezes** that submission β€” text edits,\\nfile changes, withdrawal all `409` β€” until\\n`DELETE /homework/{id}/results/{user}` removes it and reopens editing.\\nGrading before the due date, or before anything was submitted, is allowed β€”\\nthe latter is how never-handed-in work gets its `missing` verdict, and\\n`GET /homework/{id}/result` is where its student reads it (their submission\\nendpoints have nothing to show). The teacher-set `missing` **status** is a\\ndeliberate verdict; the roster and the report *also* compute a `missing`\\n**flag** for anyone unsubmitted past due β€” the two are independent. Homework\\nmarks stay out of `/marks`: the weighted course average remains exam-only\\n(the exam *kind* named `homework` still lives there), so nothing\\ndouble-counts.\\n\\n**Roster & report.** `GET /homework/{id}/submissions` (course manager) is the\\ngrading table: one row per audience student β€” plus any straggler outside the\\naudience who still owns a submission or grade (an unenrollment, a promotion,\\nor an audience change leaves work behind; it stays visible, flagged\\n`unenrolled`, though a stale student can neither submit nor be graded).\\n`GET /homework/report/{user}` is the fourth observer read beside marks,\\nattendance, and pomodoro: teacher+ (an exactly-teacher caller narrowed to the\\ncourses they manage), or a **parent linked** to the student β€” per-homework\\nrows of submitted/late/missing plus the grade; statuses and marks only,\\n**never the files**.\\n\\nEvery delete collects its garbage: withdrawing a submission, deleting a\\nhomework, and deleting the whole course each cascade the rows (submissions,\\nfiles, grades) and unlink the file blobs from disk. Role changes never sweep\\nhomework rows: a promoted student's work stays readable on the roster behind\\nthe `unenrolled` flag, while the live-role gates refuse fresh edits and\\ngrades.", "source": "README.md"}, {"id": "lesson-sessions-roll-call-the-work-log-pomodoro-attendance-reports", "title": "Lesson sessions, roll call, the work log, pomodoro & attendance reports", "body": "Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session\\nbelongs to a course and carries a `teacher` (defaults to whoever creates it;\\nany explicit `teacher_id` must hold teacher+ β€” a student cannot teach), an\\noptional `topic`, a required `starts_at`, and an optional `ends_at` (when both\\nare set, `ends_at` must not precede `starts_at`; neither may be set in the\\npast). Sessions are created, edited,\\nand deleted under course-management rights, exactly like exams; session lists\\nare ordered by `starts_at` (a timetable, not a creation log).\\n\\n**Roll call** (`/sessions/{id}/attendance`) deliberately differs from event\\nattendance: students never mark themselves. The session's teacher or a course\\nmanager marks **enrolled** students β€” only students attend classes, so a\\nnon-student or unenrolled target is a `400` β€” and the\\n**session teacher's own** presence row can only be written or removed by\\nmanager+ β€” staff presence is management's call, so a teacher can't declare\\nthemselves present. Listing the roll call follows the same rights as taking\\nit; a student reads their own tallies through the attendance report instead.\\nRe-marking overwrites: one row per session+user, by construction. Deleting a\\nsession (or its course) cascades its roll-call rows.\\n\\nThe **work log** (`/work`) is the staff timesheet, for teachers and above.\\n`POST /work/check-in` opens a stint and `POST /work/check-out` closes it, both\\nstamped by the **server clock** β€” a request never carries an instant, so a\\nwrong device clock (or a crafted request) can't forge presence. At most one\\nopen stint per user holds atomically: double check-ins and check-outs without\\nan open stint answer `409`, and a reconnecting double-click can't reset a\\nrunning clock. `GET /work/me` lists your stints newest-first (the open one has\\n`check_out: null`, closed ones a convenience `duration_ms`); manager+ reads\\nanyone's log (`GET /work/{user}`), corrects a **closed** stint's instants\\n(`PATCH /work/entries/{id}`, `409` while open β€” check out or delete instead),\\nand deletes entries.\\n\\nThe **pomodoro log** (`/pomodoro`) is the students' study-time twin of the\\nwork log. The frontend owns the timer β€” the visible countdown, the work/break\\nrhythm, the durations; the backend stores no timing policy and records only\\n**focus stints**, stamped by the server clock exactly like work stints.\\n`POST /pomodoro/start` opens a session and β€” unlike a work check-in β€” always\\nsucceeds for a student: a dangling unfinished session (a laptop closed\\nmid-timer) is **discarded and replaced**, because it recorded no focus and\\nmust not lock the student out of the next one. `POST /pomodoro/finish` closes\\nthe running session (`409` when nothing runs); breaks are never reported.\\nLogs return the usual page envelope plus `total_focus_ms`, the unpaged sum of\\nevery finished session's duration: `GET /pomodoro/me` for your own,\\n`GET /pomodoro/{user}` for teacher+ (study oversight). Only students start\\nsessions β€” pomodoro is the study tool, the work log is the staff timesheet.\\n\\n**Attendance reports** mirror the marks report: `GET /attendance/me` for any\\nlogged-in user, `GET /attendance/{user}` for teacher+ β€” narrowed to the\\ncourses the caller manages (manager+ sees every course; event tallies are\\nschool-wide either way). The report tallies event attendance and lesson roll\\ncall separately, plus a per-course breakdown:\\n\\n```json\\n{\\n \\"user\\": \\"01J…\\",\\n \\"events\\": { \\"present\\": 4, \\"absent\\": 1, \\"late\\": 0, \\"excused\\": 1, \\"total\\": 6, \\"rate\\": 0.8 },\\n \\"sessions\\": { \\"present\\": 9, \\"absent\\": 2, \\"late\\": 1, \\"excused\\": 0, \\"total\\": 12, \\"rate\\": 0.8333 },\\n \\"courses\\": [ { \\"course\\": { \\"id\\": \\"01J…\\", \\"title\\": \\"algebra\\", … }, \\"counts\\": { … } } ]\\n}\\n```\\n\\n`rate = (present + late) / (present + absent + late)`: arriving late still\\ncounts as attending, and an excused absence counts against no one (`rate` is\\n`null` when every row is excused, or there are none). Per-course blocks appear\\nfor every course the user has roll-call rows in β€” attendance is a historical\\nrecord, so unenrolling hides marks from the marks report but never hides an\\nabsence.", "source": "README.md"}, {"id": "quick-tour-curl", "title": "Quick tour (curl)", "body": "```sh\\nBASE=http://127.0.0.1:8080\\nJAR=/tmp/hz.cookies\\n\\ncurl -s $BASE/auth/register -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\ncurl -s -c $JAR $BASE/auth/login -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\n# notes\\ncurl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"first\\",\\"content\\":\\"hello\\"}'\\ncurl -s -b $JAR $BASE/notes\\n\\n# note files (multipart; -F sets filename + content type from the file)\\nNO=$(curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"with file\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nFI=$(curl -s -b $JAR $BASE/notes/$NO/files -F 'file=@plan.pdf' \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/notes/$NO/files # list metadata\\ncurl -s -b $JAR -OJ $BASE/notes/$NO/files/$FI # download, original filename\\n\\n# events + attendance\\n# Creating events needs teacher+; grant it first (see \\"Bootstrapping\\" above β€”\\n# e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403.\\nEV=$(curl -s -b $JAR $BASE/events -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"standup\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json' \\\\\\n -d '{\\"status\\":\\"present\\"}'\\ncurl -s -b $JAR $BASE/events/$EV/attendance\\n\\n# courses + weighted marks (as a teacher)\\n# optional, manager+: weigh midterms triple β€” school policy, per kind\\ncurl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \\\\\\n -d '{\\"exam_kinds\\":[{\\"name\\":\\"midterm\\",\\"weight\\":3},{\\"name\\":\\"quiz\\",\\"weight\\":1}]}'\\n# find the student to enroll (here: a registered user \\"veli\\"): fragment\\n# search over username/name, role-narrowed (teacher+)\\nSID=$(curl -s -b $JAR \\"$BASE/users/search?q=vel&role=student\\" \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nCO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"algebra\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\nEX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"midterm\\",\\"kind\\":\\"midterm\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"mark\\\\\\":90,\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\ncurl -s -b $JAR $BASE/exams/$EX/statistics\\n\\n# lesson sessions + roll call (course manager creates; the session's teacher\\n# or a course manager marks enrolled students)\\nSE=$(curl -s -b $JAR $BASE/courses/$CO/sessions -H 'content-type: application/json' \\\\\\n -d '{\\"topic\\":\\"limits\\",\\"starts_at\\":1900000000000}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/sessions/$SE/attendance -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"status\\\\\\":\\\\\\"present\\\\\\",\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\n\\n# staff work log (instants are server-stamped)\\ncurl -s -b $JAR -X POST $BASE/work/check-in\\ncurl -s -b $JAR -X POST $BASE/work/check-out\\ncurl -s -b $JAR $BASE/work/me\\n\\n# ...and as the student:\\ncurl -s -b $STUDENT_JAR $BASE/marks/me\\ncurl -s -b $STUDENT_JAR $BASE/attendance/me\\n# pomodoro: start when the timer starts, finish when it rings\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/finish\\ncurl -s -b $STUDENT_JAR $BASE/pomodoro/me\\n```", "source": "README.md"}, {"id": "ai-bridge-quic", "title": "AI bridge (QUIC)", "body": "The AI features are separate projects β€” separate repos, separate processes,\\nprobably not Rust. They talk to this backend over a QUIC bridge rather than\\nHTTP.\\n\\nWhy QUIC: stream multiplexing lives in the transport. Each request rides its\\nown **bidirectional stream** on the service's single long-lived connection, so\\nconcurrent requests need no correlation-id bookkeeping and never head-of-line\\nblock each other β€” a 30-second inference on one stream does not delay the\\nanswer on another. Connection setup (and the TLS handshake) happens once, not\\nper request.\\n\\n**The backend listens; the services dial in.** A service can therefore sit\\nbehind NAT, restart without the backend knowing its address, and scale out by\\nopening a second connection β€” each connection is an independent worker.\\n\\nOff by default: with `AI_QUIC_ADDR` unset the bridge never starts and the rest\\nof the API is unaffected.\\n\\n### Handshake\\n\\nThe service connects with ALPN `hab/1`, then opens the **control stream** (the\\nfirst client-initiated bidi stream) and writes one `Hello`:\\n\\n```json\\n{ \\"protocol\\": \\"hab/1\\", \\"service\\": \\"ocr\\", \\"capabilities\\": [\\"ocr.extract\\"],\\n \\"token\\": \\"<AI_SHARED_TOKEN>\\", \\"max_concurrent\\": 8 }\\n```\\n\\nThe backend answers one `Greeting` and leaves the stream open:\\n\\n```json\\n{ \\"type\\": \\"welcome\\", \\"worker_id\\": \\"01J...\\", \\"protocol\\": \\"hab/1\\" }\\n{ \\"type\\": \\"rejected\\", \\"code\\": \\"unauthorized\\", \\"message\\": \\"invalid token\\" }\\n```\\n\\nReject codes: `unsupported_protocol`, `unauthorized`, `no_capabilities`,\\n`malformed`. The token is compared in constant time; the handshake must\\ncomplete within 10s.\\n\\nThe control stream carries no further frames. **Its closure is the goodbye** β€”\\nthere is no heartbeat. A service that dies silently is dropped by the QUIC idle\\ntimeout (30s, with a 10s keepalive) and deregistered then.\\n\\n`max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests\\nbeyond it are refused with \\"busy\\" rather than queued.\\n\\n### Requests\\n\\nFor each request the **backend** opens a bidi stream, writes one `Request`,\\nfinishes its send side, and reads one `Response`:\\n\\n```json\\n{ \\"id\\": \\"01J...\\", \\"capability\\": \\"ocr.extract\\", \\"deadline_ms\\": 30000,\\n \\"payload\\": { \\"image\\": \\"<base64>\\" } }\\n```\\n\\n```json\\n{ \\"status\\": \\"ok\\", \\"id\\": \\"01J...\\", \\"payload\\": { \\"text\\": \\"...\\" } }\\n{ \\"status\\": \\"err\\", \\"id\\": \\"01J...\\", \\"code\\": \\"unsupported_image\\",\\n \\"message\\": \\"only png and jpeg\\" }\\n```\\n\\n`id` is a trace id for logs on both sides β€” correlation is the stream, not the\\nid. It must still be echoed: an answer carrying a different id means the\\nservice lost track of whose work it is, and the payload is refused. `payload`\\nis opaque to the transport; its shape belongs to the capability.\\n\\n`deadline_ms` is when the backend gives up. A service should abandon the work\\nrather than answer late. A handled failure is an `err` frame; a crash is just a\\ndropped stream.\\n\\n### Framing\\n\\n`u32` big-endian byte length, then that many bytes of JSON. One frame per\\nmessage. The length is validated against the 8 MiB cap **before** any buffer is\\nallocated. JSON rather than a binary codec so a service in any language can\\nspeak it in ~20 lines.\\n\\n### Routing\\n\\nRequests route by exact capability string to the **least-loaded** worker\\noffering it (ties broken by worker id). Least-inflight rather than\\nround-robin because AI request costs are wildly uneven β€” round-robin would\\npile a second long inference onto a busy worker while an idle one sits next\\nto it. Selection and the in-flight increment happen under one lock, so\\nconcurrent dispatches cannot overshoot `max_concurrent`.\\n\\nFailure modes the caller sees: `NoWorker` (nothing registered β€” retryable),\\n`Busy` (all at capacity β€” retryable), `Timeout` (may still be running on the\\nfar side, so it promises nothing), `Remote` (the service's considered no β€”\\nnot retryable), `Protocol` / `IdMismatch` (broken peer), `Transport`.\\n\\n### Conformance suite\\n\\n`tests/ai_protocol.rs` is the wire contract, enforced on every `cargo test`. It\\nspeaks `hab/1` with a client that imports none of the crate's protocol types β€”\\nframes built as byte literals, answers parsed as untyped JSON β€” so it fails on\\nexactly the changes a service in another language would notice: a renamed\\nfield, a re-tagged enum, a flipped length-prefix endianness, a newly-required\\n`Hello` field. (`tests/ai_bridge.rs` drives real QUIC clients too, but shares\\nthe Rust structs with the backend, so it cannot see those.)\\n\\nIt is also the reference implementation: its `raw` module is the whole client\\nside of the protocol in about a hundred lines β€” handshake, framing, request\\nloop β€” and is the shortest thing to port when writing a new service.\\n\\nGuarantees it pins beyond the frame shapes: unknown fields in `Hello` and in a\\nresponse are accepted (a newer service may run against an older backend);\\npayloads pass through byte-for-byte whatever their JSON shape; request ids are\\nunique; answers may come back in any order; a service that drops one request\\nstream fails only that request; a service that ignores `deadline_ms` finds its\\nstream torn down rather than delivering a late answer.\\n\\n### TLS, auth & finding the certificate\\n\\nQUIC has no plaintext mode. With `AI_TLS_CERT`/`AI_TLS_KEY` unset, a\\nself-signed certificate is generated at boot and its sha256 fingerprint logged\\nβ€” services pin that instead of installing a CA. The certificate authenticates\\n*the backend*; the shared token in `Hello` authenticates *the service*.\\n\\nSo a service does not have to be handed a file out of band, the certificate is\\npublished over HTTP:\\n\\n```\\nGET /ai/certificate # no auth; 404 when the bridge is disabled\\n{ \\"protocol\\": \\"hab/1\\",\\n \\"certificate_pem\\": \\"-----BEGIN CERTIFICATE-----\\\\n...\\",\\n \\"fingerprint_sha256\\": \\"6745e8...\\" }\\n```\\n\\nUnauthenticated on purpose: a server certificate is handed to every peer during\\nthe TLS handshake anyway, so publishing it discloses nothing. The private key\\nnever leaves the process, and the shared token β€” the thing that actually\\nauthenticates a service β€” is *not* served here.\\n\\n**A service must re-fetch this on every reconnect, not once at startup.** With\\nno PEM pair configured the bridge re-selfsigns at each boot, so a certificate\\npinned once goes stale the moment the backend restarts; a reconnect loop that\\nonly redials would then fail forever. The service startup sequence is: `GET\\n/ai/certificate` β†’ trust that PEM β†’ dial QUIC β†’ `Hello` β†’ serve; on any\\nconnection loss, start again from the fetch.\\n\\nNote what this is not: fetch-then-pin over plain HTTP is trust-on-first-use,\\nonly as trustworthy as that HTTP hop. On an untrusted network set\\n`AI_TLS_CERT`/`AI_TLS_KEY` to a real certificate and distribute it out of band\\nβ€” the endpoint then simply serves that, stable across restarts.", "source": "README.md"}, {"id": "chatbot", "title": "Chatbot", "body": "Every signed-in user β€” `parent` included β€” keeps private threads with an\\nAI service. The backend is a **relay**: it owns auth, the limits, the thread,\\nthe payload format, and the last look at the answer before anyone sees it; the\\nwords are the service's. There are deliberately **no rule, intent or\\ncanned-answer tables** β€” the thread is free-form, and a school that wants\\ndifferent behaviour changes its AI service, not this backend. A thread is\\nprivate to its owner: no teacher, no admin, nobody reads someone else's, and\\nanother user's thread is a `404`, never a `403`.\\n\\n### Sending is two-phase, and that is the point\\n\\n`POST /chatbot/threads/{id}/messages` answers `202 {message_id, status:\\n\\"pending\\"}` instead of the answer, because an inference outlives a normal\\nrequest (and the request-timeout layer that guards every handler). Before the\\nAI is even called, two rows are written: the user's turn, and an **empty\\n`pending` assistant row** β€” `message_id` is that row. That order is the whole\\ndesign: a reload, a dropped connection, a closed laptop can no longer lose an\\nanswer, because the place it will land already exists and the answering task\\noutlives the HTTP request.\\n\\nThe client then reads that row either way it likes:\\n\\n- **poll** `GET /chatbot/threads/{id}/messages/{mid}` β€” `pending` until it\\n settles, then `complete` with `content` or `failed` with `error_code`;\\n- **stream** `GET /chatbot/threads/{id}/messages/{mid}/stream` β€” the same\\n row over Server-Sent Events.\\n\\nBoth read the same row, so they can never disagree, in any state.\\n\\n### The SSE stream\\n\\n```\\nevent: delta\\ndata: {\\"text\\":\\"Newton'un ikinci yasasΔ± \\"}\\n\\nevent: delta\\ndata: {\\"text\\":\\"kuvvet ile ivme arasΔ±ndaki …\\"}\\n\\nevent: done\\ndata: {\\"message\\":{ …the message DTO… }}\\n```\\n\\nOne to eight `delta` events, then exactly one `done` carrying the finished\\nmessage; or, if the turn failed, a single `error` event\\n(`{\\"code\\":\\"timed_out\\",\\"message\\":\\"…\\"}`) and nothing else. Then the stream\\ncloses. A stream opened *after* the answer already landed still emits\\n`delta`s and a `done` β€” the replay is deliberate, so a client that connects\\nlate (or reconnects) never hangs waiting for events that already happened.\\n\\n**The deltas are sliced by the backend from the finished answer.** `hab/1` is\\nunary β€” the service returns the whole reply text, not tokens β€” so today the\\nchunking is cosmetic pacing, not real streaming. The event shape exists now so\\nthat the day a service streams, it becomes a drop-in change behind an\\nunchanged frontend.\\n\\n### The message DTO\\n\\n```json\\n{ \\"id\\": \\"01J8…\\", \\"thread_id\\": \\"01J8…\\", \\"role\\": \\"assistant\\",\\n \\"status\\": \\"complete\\", \\"content\\": \\"…\\", \\"truncated\\": false, \\"error_code\\": null,\\n \\"created_at\\": 1761820800000, \\"completed_at\\": 1761820803120 }\\n```\\n\\n`role` is `user` or `assistant`; `status` is `pending`, `complete`, or\\n`failed` (a user turn is always `complete`). `content` is empty while pending,\\n`error_code` is set only when failed, `completed_at` is `null` until the turn\\nsettles. `truncated` is `true` when `content` is only the first part of what\\nthe assistant answered β€” the rest was over `max_chatbot_message_len` and was cut;\\nit is always `false` for a user turn and for a failed one. Show it: a clipped\\nanswer that looks whole is worse than one the reader knows is clipped. The same\\nDTO is what the SSE `done` event carries, so the streaming and polling reads\\nagree about `truncated` exactly as they do about every other field.\\n\\n### Status codes\\n\\n| code | when |\\n| --- | --- |\\n| `202` | the turn was accepted; the answer is on its way |\\n| `400` | empty message, or longer than the school's `max_chatbot_message_len` |\\n| `404` | no such thread or message β€” or not the caller's |\\n| `409` | already at `max_chatbot_threads`; delete a thread first |\\n| `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |\\n| `503` | no connected service offers `chat.reply` β€” **nothing was written**, retry later |\\n\\nThe `503` ordering matters: availability is checked before the rows exist, so\\nan unavailable service leaves no dead `pending` row behind, and the rate limit\\nis charged before that, so a refused turn leaves no trace at all. The check is\\nthe backend's own worker registry, which owns the QUIC sockets and is therefore\\nthe whole truth about what can be answered.\\n\\n### A turn always settles\\n\\nOnce the two rows exist the answer never stays `pending` forever, through\\nthree independent mechanisms:\\n\\n- the task that owns the bridge round trip stamps `complete` or `failed` β€”\\n the normal path;\\n- a reader **projects** a `pending` row older than 300 seconds as\\n `failed`/`timed_out` (a read-time projection, not a write β€” the row is left\\n for the task that may still own it);\\n- a **boot sweep** flips every leftover `pending` past the 300-second horizon\\n to `failed`/`interrupted`, which is what a process death mid-inference looks\\n like. Younger rows are left alone, since one may still be in flight.\\n\\nA restart therefore loses a turn that was in flight: it settles\\n`failed`/`interrupted` rather than being answered. Accepted β€” the backend is a\\nsingle process with stop-the-world deploys, so there is no peer that could have\\ntaken it over.\\n\\nTwo more verdicts come from inspecting the answer: an **empty** reply is\\nreported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a\\nbug), and an **over-long** one is truncated to `max_chatbot_message_len` β€” a\\nclipped answer still helps, a discarded one does not β€” with `truncated: true`\\non the stored turn, so the clip is never passed off as the whole answer.\\n\\n`error_code` values a client may see: `unavailable` (no worker, or the bridge\\nis off), `busy`, `timed_out`, `transport`, `protocol`, `bad_reply` (the\\nservice's payload did not parse), `empty_reply`, `service_error`,\\n`interrupted`, `not_found`, `internal` β€” **or a code the AI service itself\\nreturned**, verbatim. Treat it as an open set: branch on the ones you handle,\\nfall back to the human-readable text for the rest.\\n\\n### The `chat.reply` capability (for AI-service authors)\\n\\nA chat service declares `chat.reply` in its `Hello` (see \\"AI bridge (QUIC)\\").\\nRequests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:\\n\\n```json\\n{ \\"message\\": \\"and the second law?\\",\\n \\"history\\": [ {\\"role\\":\\"user\\",\\"content\\":\\"what is the first law?\\"},\\n {\\"role\\":\\"assistant\\",\\"content\\":\\"an object at rest …\\"} ] }\\n```\\n\\n`history` is **oldest first** (index 0 is furthest back), optional (absent or\\n`[]` = a fresh thread), and **excludes** the new message β€” that one is\\n`message`. It carries the last `chatbot_history_turns` **settled messages** β€”\\nentries, not exchanges: the default `10` is five question/answer pairs, and\\n`history` is exactly that many entries long whenever the thread holds enough\\nof them. Only settled turns count: a failed answer is skipped and the window\\nreaches further back for a usable one, rather than coming up short. All of it\\nis re-sent on every request, which is why the service may be stateless: it can\\nrestart, scale out, or be replaced mid-thread without losing context.\\n\\nThe answer is a `Response::Ok` whose payload is:\\n\\n```json\\n{ \\"text\\": \\"the complete reply, not chunked, not partial\\" }\\n```\\n\\nFailures reuse the existing `Response::Err {code, message}` β€” one failure\\nshape on the bridge for every capability β€” and that `code` reaches the client\\nas the message's `error_code`.\\n\\n**Unknown extra keys are ignored on both sides, on purpose.** A service may\\nadd fields (a model name, token counts) and a future backend may send more\\ncontext without either end having to be redeployed in lockstep.", "source": "README.md"}, {"id": "collaborative-whiteboard", "title": "Collaborative whiteboard", "body": "A board is a shared canvas whose membership is an **ad-hoc invite list**: the\\ncreator names participant user ids at `POST /boards` and that is the whole\\nmodel β€” no course, no lesson session, no appointment. Any account from\\n`student` upwards may open one. **Every participant draws; the creator\\nalone clears, locks, closes or deletes.**\\n\\n**No parents, anywhere.** The `parent` role is the school's read-only observer,\\nand it has no whiteboard access at all β€” not a view-only tier, none. It is\\nrefused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named*\\nin an invite list either: `resolve_participants` rejects a parent id with a\\n`400`, so a parent is never on a roster in the first place. That one cut is\\nwhat closes the rest β€” never on a roster means the id-scoped routes and the\\nroom's door already answer the outsider's `404` (never a `403`, which would\\nconfirm the board is there), and no socket opens, so no `stroke` frame can be\\nsent. The role bar is re-checked on the read path and at the door as well, so a\\nboard row written before this rule that still lists a parent is inert: that\\nparent sees a `404` for it like any stranger.\\n\\n**Two doors, two statuses.** A caller who is not on a board gets a `404` on\\nevery route, its existence included β€” an outsider must never learn a board is\\nthere. A participant who is not the creator has already been told it exists, so\\nthe four creator-only commands answer them a `403`: hiding it at that point\\nwould be a lie their client cannot act on. Over the socket the same refusal is\\n`error{code:\\"forbidden\\"}` and the socket **stays open** β€” someone clicking a\\nbutton they don't own must not lose the canvas they were drawing on.\\n\\n**A clear deletes nothing.** Strokes are append-only. `POST /boards/{id}/clear`\\nbumps the board's `epoch` and appends a `clear` **marker** carrying the epoch\\nit closed, that epoch's final stroke count, who cleared and when β€” so the live\\ncanvas empties while every mark ever drawn stays stored and replayable. Those\\nmarkers *are* the epoch index, which is why there is no epochs table and why\\nthe open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.\\n`DELETE /boards/{id}` is the one operation here that really destroys marks.\\n\\n**Three caps, and only one of them is terminal** (all three published at `GET\\n/limits` under `board`):\\n\\n- `max_epoch_strokes` bounds the **live** canvas β€” `epoch_stroke_count`, which\\n every clear resets. Hitting it is **recoverable**: the creator clears, the\\n history is kept, drawing resumes.\\n- `max_board_strokes` bounds the board's **lifetime** storage β€”\\n `total_stroke_count`, which never resets, because a clear keeps its history.\\n Hitting it stamps `closed_at` and the board becomes **permanently\\n read-only**: still fully readable and replayable, never deleted, and there is\\n no reopen β€” open a new board. `POST /boards/{id}/close` is the manual form of\\n the same thing, and idempotent.\\n- `max_boards_per_creator` bounds how many boards one creator holds\\n (`board_count` on the user row). Deleting a board frees a seat; closing one\\n does not β€” a closed board is still stored.\\n\\n**Two ways to read the marks, and the difference matters most to a client\\nauthor.** A socket `join` replays the **current epoch only**; history never\\nrides the socket. History is an explicit paged REST read:\\n`GET /boards/{id}/history` (the board's whole life, oldest first, `clear`\\nmarkers included, `?epoch=` for a single one) and `GET /boards/{id}/epochs`\\n(the marker index β€” enough to offer \\"replay session 3\\" without scanning the\\nlog). `GET /boards/{id}/strokes` is the current epoch over REST, the catch-up\\nand fallback path for the same canvas the socket replays β€” with one deliberate\\ndifference: the REST read is *not* filtered by kind, while the socket serves\\n`kind: \\"stroke\\"` rows only. In the steady state that is a distinction without a\\ndifference, since a marker is written with the epoch it *closed* and the open\\nepoch has none; the case where it shows is a clear landing between the board\\nread and the row read, which surfaces that epoch's closing marker in the page.\\nFor a live canvas the socket is the authority.\\n\\n**The board room (WebSocket)** β€” `GET /boards/{id}/ws`, cookie-authed like\\neverything else and, like the exam room, outside the OpenAPI spec (an upgrade\\nis not describable there); REST remains the full fallback. The gate before the\\nupgrade is the same `404` door: not a participant, no room. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| client β†’ | `{\\"type\\":\\"join\\", \\"after\\":\\"<last stroke id>\\", \\"epoch\\":3}` β€” both optional; replay the current epoch |\\n| server β†’ | `{\\"type\\":\\"state\\", board, epoch, locked, closed_at, creator, participants, now}` on connect and every `ws_tick_secs` |\\n| server β†’ | `{\\"type\\":\\"strokes\\", epoch, strokes:[{id, author, payload}]}` β€” one replay chunk, repeated until the epoch is served |\\n| server β†’ | `{\\"type\\":\\"synced\\", epoch, cursor}` β€” the replay is complete; `cursor` is what to resume from |\\n| client β†’ | `{\\"type\\":\\"stroke\\", \\"payload\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` β€” any participant |\\n| server β†’ | `{\\"type\\":\\"saved\\", id, client_seq?}` β€” your stroke landed |\\n| server β†’ | `{\\"type\\":\\"stroke\\", id, author, payload, epoch}` β€” someone *else* drew |\\n| client β†’ | `{\\"type\\":\\"clear\\"}` / `{\\"type\\":\\"lock\\", \\"locked\\":true}` β€” **creator only** |\\n| server β†’ | `{\\"type\\":\\"cleared\\", …}` / `{\\"type\\":\\"locked\\", locked, by}` β€” the canvas was emptied / drawing was paused |\\n| server β†’ | `{\\"type\\":\\"closed\\", …}` / `{\\"type\\":\\"deleted\\"}` β€” the board is finished; both end the room |\\n| server β†’ | `{\\"type\\":\\"participants\\", creator, participants}` β€” the roster changed; a socket no longer on it is dropped |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", code, message, client_seq?}` |\\n\\nA `stroke` may carry a `client_seq` exactly as an exam-room `answer` does: any\\nvalue the client picks, echoed **verbatim** on that message's `saved` or\\n`error` and on nothing else, omitted entirely when the request omitted it. The\\nserver never reads it.\\n\\n`error` codes are a closed set: `epoch_full` (the live canvas is full β€” clear\\nit and keep drawing), `board_closed` (permanently read-only), `locked`,\\n`forbidden` (a creator-only command from a participant), `resync` (below),\\n`invalid` (bad JSON, an unknown frame, an over-long payload), `not_found`,\\n`unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\n**Persist, then publish.** A stroke is fanned out only after its row has\\nlanded, so the channel can never carry a mark the database refused (a locked\\nboard, a full epoch, a closed board). The database is the canvas; the channel\\nis a notification *about* it β€” which is why a client dedupes by stroke `id`,\\nwhy a resync deliberately re-serves marks it already drew, and why a frame is\\nnever the authority: every stroke, clear and lock re-reads the board and\\nre-checks the roster, so a socket that missed a `participants` or `locked`\\nframe is refused all the same. One consequence of the same read-then-write\\nshape: a stroke carries the epoch the server read for it, so a clear landing in\\nthat instant can file one stroke under the epoch it just closed β€” the stroke is\\nkept and stays replayable in `/history`, it simply is not on the new canvas.\\n\\n**Reconnecting.** `join` carries a cursor: `after`, the last stroke id already\\ndrawn, plus the `epoch` it belongs to. Same epoch and only what is newer is\\nreplayed; an older epoch β€” or no cursor at all β€” gets a `cleared` frame first\\nand then the whole current epoch, because a cursor into a closed epoch no\\nlonger means anything. If the room falls behind a slow socket the server sends\\n`error{code:\\"resync\\"}` and immediately replays the current epoch **out of the\\ndatabase**: the client does not re-join, it throws its canvas away and takes\\nwhat follows. The database is always the source of truth, never the channel.\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/boards/${id}/ws`);\\nlet epoch = null, cursor = null, seq = 0;\\nws.onopen = () => ws.send(JSON.stringify({ type: \\"join\\", after: cursor, epoch }));\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"cleared\\") wipeCanvas();\\n if (m.type === \\"strokes\\") m.strokes.forEach(draw); // dedupe by m.id\\n if (m.type === \\"synced\\") ({ epoch, cursor } = m);\\n if (m.type === \\"stroke\\") draw(m);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.id);\\n if (m.type === \\"error\\" && m.code === \\"resync\\") wipeCanvas();\\n};\\nconst send = (payload) =>\\n ws.send(JSON.stringify({ type: \\"stroke\\", payload, client_seq: ++seq }));\\n```", "source": "README.md"}, {"id": "concurrency-model", "title": "Concurrency model", "body": "The backend runs as **one process against one database**, and that buys less\\nthan it sounds like: every request is an async task, dozens are in flight at\\nonce, and each of them awaits the database in the middle of its work. So\\n\\"read, decide, write\\" is never safe on its own β€” SurrealDB does not\\nconflict-check a cross-record `count()` against a concurrent insert\\n(write-skew), and that fires between two tasks in one process exactly as it\\nwould between two machines. The mutex-only design this replaced was already\\nlosing races at one process. Every invariant is therefore guarded where the\\ndatabase itself decides the winner. Three tiers:\\n\\n1. **Single-row conditional writes** β€” compare-and-set (`save_if_unchanged`),\\n `UPDATE … WHERE`, stored counters (`domain::cap`). A single-record write is\\n atomic, so of N concurrent tasks exactly the allowed number get a non-empty\\n result: the database decides the winner, the loser retries\\n (`CAS_UPDATE_RETRIES`) or gets a 409.\\n2. **In-transaction `IF … THROW` gates** β€” the check runs inside the same\\n statement as the write it authorizes, so it is atomic with it. Used where\\n the rule reads the row being written (state machines, delete guards).\\n \\"Is anything still attached?\\" is answered the same way, by a counter on the\\n row being deleted rather than a `SELECT` over the children: a course is\\n deletable while its `enrollment_count` is zero, a term while its\\n `course_count` is (courses claim that reference *before* they write the\\n link, and give it back when the link moves or the course is deleted). A fee\\n plan reads the same way β€” editable *and* deletable while its\\n `assignment_count` is zero, and frozen for good once it is not, since an\\n assignment is never taken back.\\n Where the child also carries a deterministic id β€” one enrollment per\\n (course, user), one registration per (event, user), one fee-plan assignment\\n per (plan, student) β€” the seat and the row\\n are claimed in one transaction (`cap::claim_and_create`), so a duplicate\\n `CREATE` rolls its own seat back instead of costing a stranger their place.\\n3. **Two accepted races**, reviewed and deliberately left open:\\n - *Attempt-seq late save* β€” an exam-room socket writes into the sitting it\\n joined with, a choice made before any lock is taken, so a save racing a\\n retake can stamp an answer onto the just-terminal previous sitting.\\n Damage: one history row; the grade of record (latest `seq`) is never\\n touched.\\n - *Approved-overlap* β€” two approvals landing in the same instant can\\n double-book a teacher. Damage: one overlapping half-hour, visible to both\\n parties, fixable by cancelling either side.\\n\\nIn-process locks remain, and they are a *second* line, never the guarantee:\\n`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional\\n-write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is\\nthe cap β€” the lock only tames the retry loop, and keeps the tests' in-memory\\nengine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in\\nfront of a rule no single-record write can express. Removing one of them costs\\nthroughput or an accepted race; removing the conditional write behind it costs\\nthe invariant.\\n\\nBoot is unconditional: the schema batches, the backfills and the admin seed all\\nrun on every start, because exactly one process ever starts. Deployment is\\nstop-the-world β€” `podman compose down` then `up`, never overlapping β€” and a\\nrelease that adds or renames a stored counter *requires* it. An old binary\\nwrites rows without touching the new counter, the `= NONE` backfill guard\\n(correctly) refuses to re-seed, and the resulting permanent under-count lets a\\nguard approve exactly what it exists to refuse. In-flight work does not survive\\na restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.", "source": "README.md"}, {"id": "layout", "title": "Layout", "body": "```\\nsrc/\\n main.rs bootstrap: config, db, router, serve\\n lib.rs build_router: routes + OpenAPI/Swagger + CORS + /health\\n config.rs env-sourced Config\\n constant.rs validation limits\\n validate.rs field validators (used by every newtype's try_new)\\n error.rs ValidationError + AppError -> HTTP responses\\n database.rs SurrealDB server connect (ws) + SCHEMAFULL migration\\n migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,\\n MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them\\n rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier\\n state.rs AppState { db, files_path, cookie_secure, rate_limit,\\n chatbot_limit, exam_presence, board_hub, db_up, ai }\\n ai/ QUIC bridge to the out-of-process AI services\\n (see \\"AI bridge (QUIC)\\"; the HTTP half is web/ai.rs)\\n protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing\\n server.rs AiBridge: listener, handshake, dispatch over per-request streams\\n registry.rs connected workers, capability routing, least-inflight leases\\n tls.rs listener certificate (PEM or self-signed) + fingerprint\\n error.rs AiError\\n chat.rs the `chat.reply` payload contract (ChatRequestPayload/ChatReplyPayload)\\n domain/ validated newtypes + entities (derive SurrealValue),\\n each owning its persistence\\n user.rs UserId Β· Username Β· Password Β· PasswordHash Β· User (has role)\\n role.rs Role enum (student < teacher < manager < admin), at_least()\\n field_update.rs FieldUpdate: one UPDATE ... SET built from only the fields a\\n PATCH actually carried (an omitted field is never written)\\n monotonic_id.rs next_ulid: ids that sort in write order β€” one process-wide\\n Generator, so same-millisecond rows never scramble\\n key.rs sitting(): the deterministic per-sitting record key shared by\\n attempts, answers, answer images and results (seq 1 stays bare)\\n cap.rs claim()/release(): the count caps the database enforces β€” an\\n atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter\\n column of the parent row, replacing count-then-write mutexes\\n that could not see a concurrent insert;\\n claim_and_create() commits that seat and the child row in\\n one transaction, for children with a deterministic id\\n text_fold.rs case- and diacritic-insensitive folding for search, shared by\\n the Rust needle and the SurrealQL column (Turkish Δ°/Δ±, ΓΌ, â…)\\n session.rs SessionId Β· SessionToken Β· Session (7-day expiry)\\n timestamp.rs Timestamp (unix-millisecond instant)\\n note.rs NoteId Β· NoteTitle Β· NoteContent Β· Note\\n note_file.rs NoteFileId Β· FileName Β· FileContentType Β· NoteFile (metadata row;\\n blob on disk under FILES_PATH, named by the row's ULID)\\n event.rs EventId Β· EventTitle Β· EventDescription Β· Event\\n attendance.rs AttendanceId Β· AttendanceStatus Β· Attendance\\n course.rs CourseId Β· CourseTitle Β· CourseDescription Β· Course\\n course_session.rs CourseSessionId Β· SessionTopic Β· CourseSession (a course's lesson)\\n session_attendance.rs SessionAttendanceId Β· SessionAttendance (roll call; one row per session+user)\\n work_entry.rs WorkEntryId Β· WorkEntry (staff stint; one open per user by construction)\\n enrollment.rs EnrollmentId Β· Enrollment (one row per course+user)\\n exam.rs ExamId Β· ExamTitle Β· ExamDescription Β· ExamKind Β· ExamWeight Β·\\n ExamMode Β· ExamDuration Β· ExamSchedule Β· Exam (belongs to a course)\\n exam_attempt.rs ExamAttemptId Β· AttemptStatus Β· ExamAttempt (numbered sittings per exam+user, metered by max_attempts)\\n exam_question.rs ExamQuestionId Β· QuestionText Β· QuestionKind Β· QuestionPoints Β·\\n ChoiceText Β· QuestionSpec Β· ExamQuestion (choice|text, per exam)\\n exam_answer.rs ExamAnswerId Β· AnswerText Β· ExamAnswer (one row per question+user) Β·\\n auto_score (choice-question suggestion)\\n exam_result.rs ExamResultId Β· Mark Β· ExamResult (one row per exam+user)\\n question_image.rs QuestionImageId Β· QuestionImage (question/choice picture\\n metadata; bytes on disk under FILES_PATH)\\n answer_image.rs AnswerImageId Β· AnswerImage (student answer-drawing\\n metadata; bytes on disk under FILES_PATH)\\n bank_question.rs BankQuestionId Β· BankQuestion (school-wide reusable\\n question template, copied into exams; no exam FK)\\n bank_question_image.rs BankQuestionImageId Β· BankQuestionImage (bank\\n question/choice picture metadata; bytes on disk under FILES_PATH)\\n profile.rs PersonName Β· Email Β· Phone Β· BirthDate (personal-info newtypes)\\n preferences.rs Theme Β· Language Β· PaletteColor (own UI preferences)\\n message.rs MessageId Β· MessageSubject Β· MessageBody Β· MessageLabel Β·\\n Message (per-copy folders: inbox/sent/archive/trash)\\n parent_link.rs ParentLinkId Β· ParentLink (parent↔student tie = the parent's read grant)\\n registration.rs RegistrationId Β· Registration (a seat on a registration event's signup list)\\n subject.rs SubjectId Β· SubjectName Β· SubjectDescription Β· Subject (course curriculum)\\n term.rs TermId Β· TermName Β· Term (school term window)\\n menu.rs MenuId Β· MenuDate Β· MenuSlot Β· Menu (one published menu per\\n calendar day + meal slot; slot snapshotted as text)\\n menu_dish.rs MenuDishId Β· DishName Β· DishDescription Β· DishPrice Β·\\n DishTags Β· MenuDish (a dish on a menu; price in minor units)\\n dietary_profile.rs DietaryProfileId Β· DietaryTags Β· DietaryNote Β·\\n DietaryProfile (what one student may not eat; keyed by the\\n student, tagged from the same `dietary_tags` list a dish is)\\n meal_booking.rs MealBookingId Β· MealBookingStatus Β· MealBooking (one seat\\n per (menu, student); a cancel flips the status, never deletes)\\n meal_attendance.rs MealAttendanceId Β· MealAttendanceStatus Β· MealAttendance\\n (who actually ate; one row per (menu, student), reporting\\n only β€” it never touches the ledger)\\n meal_ledger.rs MealLedgerId Β· MealLedgerKind Β· LedgerAmount Β· LedgerMethod Β·\\n LedgerNote Β· MealLedger (append-only money; the balance is\\n always the fold, never a stored field)\\n fee_plan.rs FeePlanId Β· FeePlanName Β· Installment Β· FeePlan (a school fee\\n plan; installments embedded on the row, past due dates legal)\\n fee_plan_assignment.rs FeePlanAssignmentId Β· FeePlanAssignment (one plan on\\n one student, keyed `<plan>_<student>`; assigning appends\\n every installment charge, a replay appends nothing)\\n payment_ledger.rs PaymentLedgerId Β· PaymentLedgerKind Β· PaymentLedger\\n (append-only school fees: charge/credit/reversal/refund, a\\n credit names its charge and a refund its credit; the balance\\n is always the fold; over-payment cap is advisory)\\n settings.rs ExamKindDef Β· GradeBand Β· Settings (per-school policy)\\n chatbot_thread.rs ChatbotThreadId Β· ChatbotThreadTitle Β· ChatbotThread (one\\n chatbot thread, private to its owner)\\n chatbot_message.rs ChatbotMessageId Β· ChatContent Β· MessageRole Β· MessageStatus Β·\\n ChatbotMessage (one turn; the assistant row is written\\n `pending` before the AI call and settled after)\\n board.rs BoardId Β· BoardTitle Β· Board (a collaborative whiteboard:\\n creator + ad-hoc participant list, `epoch`, the two stroke\\n counters and `closed_at`)\\n board_stroke.rs BoardStrokeId Β· BoardStroke (the\\n append-only stroke log; a `clear` row is the marker that\\n closed an epoch, carrying its final count β€” nothing is\\n ever deleted)\\n appointment_slot.rs AppointmentSlotId Β· SlotSeries Β· SlotNote Β·\\n AppointmentSlot (a teacher's published availability; a\\n recurring publish is expanded into rows sharing a series id)\\n appointment.rs AppointmentId Β· AppointmentStatus Β· AppointmentReason Β·\\n Appointment (a booking on a slot; occupancy is the slot's\\n stored `occupied` cap-1 counter, overlap is derived under\\n APPOINTMENT_LOCK)\\n pomodoro.rs PomodoroSessionId Β· PomodoroSession (student focus log)\\n pool_question.rs PoolQuestionId Β· PoolQuestionTitle Β· PoolQuestionBody Β·\\n PoolQuestion (student-asked question; teacher-approved into\\n the school-wide pool; optional photo as metadata + disk blob)\\n solution.rs SolutionId Β· SolutionBody Β· Solution (discussion thread on an\\n approved pool question; dies with the question)\\n homework.rs HomeworkId Β· HomeworkTitle Β· HomeworkDescription Β· Homework\\n (per-course assignment; required subject; optional `assigned`\\n student subset β€” absent/empty = the whole enrolled course)\\n homework_submission.rs HomeworkSubmissionId Β· SubmissionText Β·\\n HomeworkSubmission (one row per homework+user; immutable\\n submitted_at + moving updated_at β€” `late` is computed)\\n homework_file.rs HomeworkFileId Β· HomeworkFile (submission attachment\\n metadata; any content type; bytes on disk under FILES_PATH)\\n homework_result.rs HomeworkResultId Β· HomeworkStatus Β· HomeworkResult\\n (teacher grade: done/incomplete/missing + optional Mark; one\\n row per homework+user β€” its existence freezes the submission)\\n web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +\\n auth extractors\\n extractor.rs CurrentUser Β· RequireTeacher Β· RequireManager Β· RequireAdmin\\n dto.rs shared UserResponse Β· CourseResponse Β· ExamResponse Β· SessionResponse schemas\\n exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)\\n board_ws.rs the collaborative board room WebSocket (join replay, strokes\\n fanned out to every participant, clear/lock)\\n room.rs the plumbing both rooms share: sending a frame, classifying\\n an incoming message, an AppError as a readable code, and a\\n client_seq echoed untouched\\n page.rs PageParams Β· Page<T> (shared pagination)\\n etag.rs conditional-GET middleware: ETag over a 200 JSON body,\\n If-None-Match β†’ 304 (GET only; SSE and blobs pass through)\\n auth.rs users.rs notes.rs messages.rs events.rs appointments.rs\\n courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs\\n bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs\\n settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs\\n boards.rs\\n limits.rs GET /limits: every constant.rs bound served as JSON\\n```\\n\\nTests: `cargo test` β€” unit (in-source), integration (`tower::oneshot` + in-memory\\ndb), rate-limit (both tiers, proxy-header and peer-address keying, shipped\\nlimits over every route, two limiters sharing one budget over one db), e2e\\n(real TCP + reqwest cookie jar), persistence\\n(tempfile file engine, including close + reopen), ai-bridge (real QUIC on\\nloopback against a fake AI service), ai-protocol (the `hab/1` wire contract,\\ndriven by a client that shares no code with the backend).", "source": "README.md"}];
20+INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "592d24c8e4b3aa8bba80caa0887acc3610096296f9fe26183256708aeeeb5a32"}];
21+DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii;
22+DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25;
23+DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25;
24+REMOVE TABLE IF EXISTS endpoint;
25+INSERT INTO endpoint [{"id": "health", "routes": "| GET | `/health` | no | Liveness check |"}, {"id": "root", "routes": "| GET | `/` | no | Same as `/health` |"}, {"id": "time", "routes": "| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |"}, {"id": "limits", "routes": "| GET | `/limits` | no | Every fixed validation bound, grouped by resource \\u2014 see Validation limits |"}, {"id": "swagger", "routes": "| GET | `/swagger` | no | Interactive API docs (Swagger UI) |"}, {"id": "api-docs", "routes": "| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |"}, {"id": "ai", "routes": "| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |"}, {"id": "auth", "routes": "| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken \\u2014 see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |"}, {"id": "users", "routes": "| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` \\u2014 own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) \\u00b7 paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` \\u2014 find users by username/name fragment (pickers); refs only, no contact info \\u00b7 paged |\\n| GET | `/users` | admin | List all users \\u00b7 paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` \\u2014 set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` \\u2014 tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students \\u00b7 paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |"}, {"id": "notes", "routes": "| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes \\u00b7 paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) \\u2014 \\u2264 the school's `max_file_bytes`, \\u2264 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) \\u00b7 paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |"}, {"id": "messages", "routes": "| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` \\u2014 send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` \\u2014 the caller's folder, newest first; `?folder=inbox&read=false&limit=1` \\u2192 `total` is the unread badge \\u00b7 paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` \\u2014 read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** \\u2014 only from the trash (`409` elsewhere); the row vanishes once both sides deleted |"}, {"id": "events", "routes": "| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` \\u2014 `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` \\u2014 mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) \\u00b7 paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` \\u00b7 paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` \\u2014 seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |"}, {"id": "appointments", "routes": "| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` \\u2014 publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, \\u2264 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) \\u2014 a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar \\u2014 future slots only, demoted teachers' slots left out \\u00b7 paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` \\u2014 book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests \\u00b7 paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` \\u2014 call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included \\u2014 they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` \\u2014 counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal \\u2014 this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |"}, {"id": "courses", "routes": "| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` \\u2014 `kind` is `course` (default), `study` (et\\u00fct), or `club` (kul\\u00fcp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) \\u00b7 paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses \\u00b7 paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ \\u2014 **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` \\u2014 assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` \\u2014 enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u00b7 paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` \\u2014 add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` \\u2014 add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` \\u2014 add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) \\u00b7 paged |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` \\u2014 assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, \\u2264 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) \\u00b7 paged |"}, {"id": "subjects", "routes": "| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |"}, {"id": "sessions", "routes": "| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` \\u2014 roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) \\u00b7 paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |"}, {"id": "exams", "routes": "| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist \\u2014 the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` \\u2014 grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) \\u00b7 paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt \\u2014 students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) \\u00b7 paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question \\u2014 the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam \\u2014 copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** \\u2014 copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question \\u2014 text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` \\u2014 autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers \\u22c3 marks), ascending \\u2014 the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first \\u2014 the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** \\u2014 the answer key the caller checks their own sheet against (same review gate) \\u00b7 paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers \\u22c3 marks), ascending \\u2014 only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster \\u00d7 latest attempts \\u00d7 marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |"}, {"id": "bank-questions", "routes": "| GET | `/bank-questions` | teacher | The school-wide question bank \\u2014 `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) \\u00b7 paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist \\u2014 `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question \\u2014 the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |"}, {"id": "homework", "routes": "| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) \\u00b7 paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade \\u2014 the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades \\u2014 file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` \\u2014 hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part \\u2014 **any** content type, \\u2264 `max_file_bytes`, \\u2264 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) \\u2014 the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student \\u00d7 submission/files/grade + computed `late`/`missing`/`unenrolled` \\u2014 a straggler's stale work stays visible (course manager) \\u00b7 paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` \\u2014 grade `done`/`incomplete`/`missing` (+ optional 0\\u2013100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable \\u2014 that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) \\u2014 readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade \\u2014 un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows \\u2014 submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` \\u2014 full, statuses and marks only, never files \\u00b7 paged |"}, {"id": "questions", "routes": "| POST | `/questions` | student | `{title, body}` \\u2014 ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` \\u2014 the pool questions visible to the caller, each with its `solution_count` \\u00b7 paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question \\u2014 publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` \\u2014 offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first \\u2014 a discussion thread \\u00b7 paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` \\u2014 edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |"}, {"id": "marks", "routes": "| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "work", "routes": "| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) \\u00b7 paged |\\n| GET | `/work/{user}` | manager | A staff member's work log \\u00b7 paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` \\u2014 correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |"}, {"id": "pomodoro", "routes": "| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** \\u2014 a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` \\u00b7 paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape \\u00b7 paged; *or a `parent` linked to `{user}` |"}, {"id": "attendance", "routes": "| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "settings", "routes": "| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |"}, {"id": "terms", "routes": "| POST | `/terms` | manager | `{name, starts_at, ends_at}` \\u2014 past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first \\u00b7 paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term \\u2014 `409` while any course still links to it |"}, {"id": "meals", "routes": "| POST | `/meals/menus` | manager | `{date, slot, capacity?}` \\u2014 publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range \\u00b7 paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` \\u2014 the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` \\u2014 add a dish (\\u2264 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` \\u2014 record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` \\u2014 take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first \\u00b7 paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included \\u00b7 paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` \\u2014 mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu \\u00b7 paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day \\u00b7 paged \\u00b7 own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line |"}, {"id": "payments", "routes": "| POST | `/payments/plans` | manager | `{name, installments}` \\u2014 write a fee plan (1\\u201360 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first \\u00b7 paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it \\u2014 its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (\\u2264 200) \\u2014 place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first \\u00b7 paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` \\u2014 record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` \\u2014 hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` \\u2014 undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines \\u2014 charges, payments, refunds, reversals \\u2014 newest first \\u00b7 paged \\u00b7 own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |"}, {"id": "chatbot", "routes": "| POST | `/chatbot/threads` | student | `{title?}` \\u2014 start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first \\u00b7 paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` \\u2014 rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first \\u2014 user and assistant rows alike \\u00b7 paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (\\u2264 `max_chatbot_message_len`) \\u2014 send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` \\u2014 nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` \\u2014 or one `error` \\u2014 and close; an already-finished answer replays (see \\"Chatbot\\") |"}, {"id": "boards", "routes": "| POST | `/boards` | student | `{title, participant_ids?}` \\u2014 open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first \\u00b7 paged |\\n| GET | `/boards/{id}` | student | One board \\u2014 a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first \\u00b7 paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included \\u00b7 `?epoch=` for one epoch \\u00b7 paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) \\u00b7 paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` \\u2014 re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap \\u2014 nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board \\u2014 permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |"}];
26+SELECT VALUE sha256 FROM meta:readme;
27+REMOVE TABLE IF EXISTS doc;
28+REMOVE TABLE IF EXISTS meta;
29+INSERT INTO doc [{"id": "intro", "title": "intro", "body": "# hezarfen_backend\\n\\nNote, attendance, course + weighted exam mark backend. **Rust (edition 2024) Β· axum Β· SurrealDB 3 (server, WebSocket) Β· tokio.**\\n\\nSession-cookie auth with five hierarchical roles (`parent < student < teacher\\n< manager < admin`). A **`parent`** observes and changes nothing: admins tie\\nstudents to a parent account, and the parent reads those students' mark,\\nattendance, pomodoro, and homework reports β€” that's the whole role. Notes are per-user and carry **file attachments** (PDFs, documents,\\n…): blobs live on disk next to the database, metadata in the database, and the\\nper-file size cap is school policy in settings (`max_file_bytes`, default\\n5 MiB). Any two users can **message** each other, mail-style β€” subject +\\nbody into the recipient's inbox, each side filing its own copy through\\narchive/trash with a read flag the sender sees as a receipt (the only place a\\n`parent` writes). Attendance is event + attendees: create an event with an **audience**\\n(the whole school, one role, a course's enrollment, or a **registration**\\nsignup list β€” omit for school-wide), then teachers mark the expected attendees\\npresent / absent / late / excused (students never self-mark), and a **roster\\nreport** shows who was expected and who missed. Registration lists fill seat\\nby seat: teachers register students (never the other way round), staff\\nregister only themselves, an optional `capacity` caps the seats, and the list\\ncloses the moment the event starts (or, for an event with only an end time β€”\\na pure signup deadline β€” the moment that end passes). Every event stays visible to everyone β€”\\nthe audience is a roster, not a wall. Marks are course-shaped\\n(Google Classroom style): a teacher creates a course β€” kind **`course`** (a\\nregular class), **`study`** (a supervised study session β€” *etΓΌt*), or\\n**`club`** (a student club β€” *kulΓΌp*; same behavior, different label),\\noptionally capped by a `capacity` that refuses new enrolls once the roster is\\nfull β€” lays out its **subjects** (curriculum topics β€”\\nevery exam question must be tagged with one of its course's subjects, so\\nresults can later be read per topic), enrolls students, adds\\nexams inside it, and grades β€” enrolling, sitting exams, roll call, and marks are\\nall student-only, staff never take part. A course is run by whoever created it\\nplus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`):\\nan assigned teacher manages everything inside the course β€” exams, sessions,\\nsubjects, roster, grading β€” but can't delete it or change who else teaches it,\\nand a demotion below `teacher` sweeps their assignments away. Students read a per-course weighted average and\\nan overall average from their mark report β€” each exam weighted by its **kind**\\n(midterms can count double, orals once: weights are set per kind in settings,\\nnot per exam). Exams run **sync** (one\\nfixed window), **async** (start anytime inside the window, with a personal\\ntime budget), or **open** (sit anytime, optionally timed per attempt);\\nstudents *sit* them via attempts β€” retakes metered by a per-exam limit\\n(`0` = unlimited), each sitting keeping its own answers, drawings, and mark\\nso staff can read a student's full attempt history, leaving the exam room\\ngoverned by a teacher-controlled rejoin door. Writing an exam takes a while, so it can be saved as a\\n**draft** β€” invisible to students, unsittable, ungradable β€” and published\\nwhen it's ready. Questions can carry **images**: any question may hold one\\nillustration (a map above the prompt), and each option of a choice question\\nmay be a picture of its own (pick the right city off the map) β€” raster\\nuploads capped by the same `max_file_bytes` policy as note files. Good\\nquestions get reused, so a teacher+ can bank one in a school-wide **question\\nbank** β€” detached templates (with their own images) that any teacher copies\\ninto a fresh exam question across years, editable and deletable only by\\nwhoever saved them. Teachers\\nwatch attendance, per-student remaining time,\\nsittings, walk-outs, no-shows (`absent` once the window closes), submissions,\\nand marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out\\n**homework**: assigned to the whole class or a named subset (the unnamed never\\neven see it), tagged with a course subject, due by a required future `due_at`\\nβ€” students hand in text and/or **files of any type** (same size cap, 10 per\\nsubmission, served back only as forced downloads), editable until the teacher\\ngrades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark\\n(grading freezes the hand-in until the grade is removed); lateness is computed\\nfrom two stamps (first hand-in vs last touch), never stored, and homework\\nmarks stay out of the weighted `/marks` averages. Courses also carry **lesson\\nsessions** with teacher-taken roll call (students never self-mark a lesson),\\nstaff clock in/out on a server-stamped **work log**, students track study time\\nwith a server-stamped **pomodoro log** (the timer runs in the frontend; the\\nbackend records the focus stints, and teachers can read any student's log),\\nand every user has an\\n**attendance report** (event + per-course lesson tallies with rates).\\nA school-wide **question pool** runs on moderation: a student asks a question\\n(optionally attaching one photo of the problem β€” raster only, same\\n`max_file_bytes` cap), a teacher+ **approves** it into the pool (or deletes\\nit β€” rejection is deletion, there is no rejected state), and every approved\\nquestion is readable by the whole school with anyone free to offer\\n**solutions** under it (parents stay out) β€” text plus an optional photo of\\nthe worked steps, both editable by the solution's author anytime; pending\\nquestions show only to their asker and to teacher+, and approval freezes the\\ncontent so nothing unmoderated ever reaches the pool.\\nTeachers keep an **appointment calendar**: a teacher+ publishes availability\\nslots (one-off, or repeating weekly up to an `until` date as a series that\\ndeletes as one), and students and parents book a slot with a reason β€” the\\nbooking lands `pending` until the teacher approves it, rejects it, or\\ncounter-proposes another time (which sends it back to `pending` for the\\nrequester to accept or decline); the **requester** may cancel until the meeting\\nstarts β€” a teacher ends a booking by rejecting it, or by counter-proposing and\\nthen rejecting an approved one β€” one live booking holds a slot, a teacher's own\\npublished windows may not overlap each other, and no approved meeting may\\noverlap another for the teacher or the requester (see \\"Appointments\\").\\nSchool-varying policy is data, not code: exam kinds (each with its weight in\\ncourse averages), attendance statuses, grade-display bands, the note-file\\nsize limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms**\\nare plain rows courses can link to (see \\"Per-school policy\\"). Each account\\nalso carries its own **UI preferences** β€” theme (`light`/`dark`), language\\n(`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` β€”\\nany hex, deliberately not a fixed palette) β€” self-managed, admin-editable for\\nanyone, `null` until chosen so the client can fall back to the device\\npreference (or, for the accent, its own default).\\nThe **AI features live in separate projects**, so the backend also opens a\\nQUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in,\\nregister the capabilities they serve, and each request rides its own QUIC\\nstream on that one connection β€” no correlation ids, no head-of-line blocking.\\nThe bridge's certificate is published at `GET /ai/certificate` so a service can\\npin it before dialling (see \\"AI bridge (QUIC)\\").\\nThe first thing riding that bridge is the **chatbot**: every signed-in user\\n(`parent` included) keeps private threads with an AI service, free-form β€”\\nno rule tables, no canned answers, the backend only owns auth, limits,\\npersistence and the payload format. Sending is asynchronous because an\\ninference outlives a request: the turn plus an empty `pending` answer are\\nwritten *first*, the call goes out after, so a reload never loses an answer;\\nthe client then polls the message or reads it off an SSE stream (see\\n\\"Chatbot\\").\\nAny signed-in account (a `parent` included) can also open a **collaborative\\nwhiteboard**: a titled board whose membership is an **ad-hoc invite list** β€”\\nthe creator names participant user ids, and no course, session or appointment\\nis involved. Every participant draws over a WebSocket, the creator alone\\nclears, locks, closes or deletes, and someone who is not on a board gets a\\n`404` for it on every route, existence included. Strokes are **append-only and\\na clear deletes nothing** β€” it bumps the board's epoch, so the live canvas\\nempties while every mark ever drawn stays stored and replayable through the\\nhistory reads (see \\"Collaborative whiteboard\\").\\nThe school's **food program** is published here too: a manager puts up one\\n**menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot`\\ndrawn from the school's `meal_slots`, unique per pair), lists its **dishes**\\nwith dietary tags from the school's own list, and prices them in **minor\\nunits** (kuruş) as integers β€” this API never speaks decimals or floats about\\nmoney. A student's own **dietary profile** is tagged from that same list\\n(manager-written β€” an allergen list is a school record, not a self-service\\npreference), so every dish a menu read returns names the tags it `conflicts`\\nwith for whoever is reading. Every authenticated user reads what is being\\nserved; students (or their parents) book a seat, and every seat writes a line into an\\n**append-only** meal ledger whose balance is derived and never stored (see\\n\\"Food program: menus, dishes, bookings & the ledger\\").\\nSchool **fees** are tracked the same way, in a ledger of their own: a manager\\nwrites a **fee plan** (a name and 1–60 installments, each an amount in minor\\nunits and a due date that may sit in the past) and **assigns** it to students,\\nwhich appends every installment as a `charge` at once β€” there is no scheduler,\\nand \\"overdue\\" is derived at read time. Payments are recorded against one named\\ncharge, refunds against one named payment, and nothing is ever edited or\\ndeleted: a mistake is corrected by appending the opposing line. **There is no\\nonline payment integration and none is planned** β€” no gateway, no card data,\\n`method` is free text. Teachers see no money at all (see \\"Payments\\").\\n\\nEvery field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)\\nconstructed only after its restrictions pass β€” invalid input can't be\\nrepresented. Those restrictions are published rather than left to be guessed:\\n**`GET /limits`** (no auth) serves every fixed bound and closed value set the\\nAPI enforces, read straight from the constants the newtypes use, so a frontend\\nvalidates against the server's own rules instead of a hand-kept copy (see\\n\\"Validation limits\\"). Those same types derive `surrealdb::types::SurrealValue`, so one\\ntyped value flows from HTTP request into the `SCHEMAFULL` database. Record ids\\nare ULIDs (time-sortable).", "source": "README.md"}, {"id": "run", "title": "Run", "body": "```sh\\nsurreal start --user root --pass root surrealkv:./data/hezarfen.db # the DB server\\ncp .env.example .env # optional\\ncargo run\\n```\\n\\nBoots on `http://127.0.0.1:8080`, talking to the SurrealDB server at\\n`DB_URL` (default `ws://127.0.0.1:8000`, root credentials via\\n`DB_USER`/`DB_PASS`) and storing uploaded note files in\\n`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs\\n(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at\\n`/api-docs/openapi.json`.", "source": "README.md"}, {"id": "run-in-a-container-podman", "title": "Run in a container (podman)", "body": "```sh\\npodman compose up -d --build # build + start, http://127.0.0.1:8080\\npodman compose logs -f backend\\npodman compose down # stop (data survives in the volume)\\n```\\n\\nThe `Containerfile` is a two-stage build (Rust builder with cargo cache\\nmounts, `debian:trixie-slim` runtime, non-root user). Two services: the\\n`surrealdb` server (official image, surrealkv storage) and the backend, which\\nwaits for the server's healthcheck and connects over `ws://surrealdb:8000`.\\nEach has its own named volume β€” `surreal-data` holds the database,\\n`hezarfen-data` the uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the\\ncontainer so the published port works. Production knobs (`COOKIE_SECURE`,\\n`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in\\n`compose.yaml` β€” uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset\\nmeans dev mirror mode without credentials; a cookie-using browser frontend\\nmust be allowlisted explicitly. Works with `docker compose` too.\\n\\nThe backend survives the database going away, at boot and at runtime.\\n\\nAt boot it retries the connection (1s doubling to 5s) until the server\\nanswers, rather than exiting. Exiting looks tidier but is worse: the container\\nruntime restarts the process, it fails again in milliseconds, and a few\\nseconds of startup skew burns the whole restart budget and leaves the backend\\ndown for good.\\n\\nAt runtime a keepalive query every 5s doubles as a liveness probe. This\\nmatters more than it sounds: a query issued while the socket is down does\\n*not* fail β€” the SDK's reconnect loop stops draining its request queue, so the\\nquery parks until the database returns and only *then* runs. Left alone, a\\nrequest waits out the entire outage and any write it carries lands long after\\nthe caller gave up.\\n\\nSo while the probe says the socket is down, requests are refused at the edge\\nwith `503` and `Retry-After: 1`, before they can reach the database. Nothing\\nis queued, which is what makes that retry safe. Requests that slip through in\\nthe window between the socket dying and the probe noticing are capped at 30s\\nand answer `503` *without* `Retry-After`, with a message saying the write may\\nor may not have applied β€” they were already queued, so retrying them could\\napply the same write twice. WebSocket and SSE routes are unaffected: both\\nreturn their response immediately and stream afterwards.\\n\\nWithout compose:\\n\\n```sh\\npodman build -t hezarfen-backend .\\npodman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backend\\n```", "source": "README.md"}, {"id": "auth-model", "title": "Auth model", "body": "Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, stored\\nserver-side). Send it back on later requests. Every endpoint below whose `Auth`\\ncolumn names a role requires a valid session; the ones marked `no` (`/health`,\\nthe docs pages, `register` / `login` / `logout`) don't (`logout` is idempotent β€”\\nit clears the session if one is present). Set `COOKIE_SECURE=true` when serving\\nbehind TLS to add the cookie's `Secure` attribute.\\n\\n**Register never reveals whether a username is taken.** `POST /auth/register`\\nanswers `201` either way with the *same* body β€” `{username, role}`, the echoed\\nname and the `student` role every fresh account gets. Both outcomes return one\\nvalue built before the insert is even attempted, so they are byte-identical by\\nconstruction. This is deliberate: the route is unauthenticated, so a `409` (or a\\nfaster reply) would let anyone enumerate the school's users. The password is\\nhashed *before* the availability check so both outcomes cost the same ~33ms.\\n\\nThe reply carries **no `id`**: on the taken path there is no row to name, and a\\nfabricated one would leave the client holding an id that matches nothing. Log\\nin and read `GET /auth/me` to learn who you are. The accepted cost: a caller who\\ncollides with an existing account gets no distinct error and simply cannot log\\nin with that password β€” they pick another name. Do not \\"fix\\" this back to a\\n`409`, and do not add an `id` back.", "source": "README.md"}, {"id": "time-policy", "title": "Time policy", "body": "Timezones and clock differences cannot corrupt data, by construction:\\n\\n- **Every instant is a UTC unix-millisecond `i64`** (`domain::timestamp::Timestamp`),\\n stored as an `int`, sent as a plain number. Nothing stores or parses a\\n timezone, so the server's `TZ`, the container's clock config, and the\\n client's locale are all irrelevant β€” clients convert millis to local time\\n for display only.\\n- **One clock choke point.** `Timestamp::now()` is the only wall-clock read.\\n `clippy.toml` bans every other source (`chrono::Local`/`Utc::now`,\\n `SystemTime::now`, `time::OffsetDateTime::now_*`, absolute cookie\\n `Expires`) and `[lints.clippy]` raises that to a hard `cargo clippy` error,\\n so local-time bugs can't be reintroduced.\\n- **Expiry is server-authoritative.** Sessions expire by comparing the stored\\n millis against the server clock; the cookie carries a relative `Max-Age`\\n (never an absolute `Expires`), so a wrong client clock changes nothing.\\n- **Pacing uses the monotonic clock.** The rate limiter runs on `Instant`,\\n immune to NTP steps and wall-clock jumps.\\n- **Calendar dates get a timezone grace.** A birth date is a calendar date on\\n the writer's wall, not an instant: validation accepts up to UTC-tomorrow,\\n since a client ahead of UTC (up to UTC+14) legitimately writes a date the\\n server's UTC calendar hasn't reached yet.\\n- **Times-of-day are UTC too, and staff enter them that way.** A meal slot's\\n `serving_minute` (minutes past midnight, `0`–`1439`) is the one clock-face\\n value a school types in, and it is read as UTC on the menu's `date` β€” there\\n is deliberately **no school-timezone setting** (a rejected feature), so a\\n UTC+3 school enters `540` (09:00 UTC) for a meal served at noon locally.\\n- **Nothing schedules in the past.** A request-supplied schedule instant β€” an\\n exam window, a lesson's `starts_at`/`ends_at`, an event time β€” must not lie\\n before the server's now, on create and on every `PATCH` that sets it: a\\n deadline that starts in the past is dead on arrival, so it's a `400`. A\\n 60-second grace absorbs request latency and client-clock skew (\\"starts now\\"\\n survives its own round trip). Values a `PATCH` merely keeps are exempt β€” a\\n running exam's `starts_at` is legitimately past, and a rename or deadline\\n extension must not trip over it. (Work-log corrections are records of past\\n work, not schedules, and stay free.)\\n- **Frontends can sync to the server clock.** `GET /time` (no auth) returns\\n `{\\"now\\": <UTC unix-millis>}`. Fetch once, keep\\n `offset = now - Date.now()`, and use `Date.now() + offset` for countdowns\\n and past/future checks instead of trusting the device clock.\\n\\nKeep the single server's clock NTP-synced; that's the only clock that matters.", "source": "README.md"}, {"id": "validation-limits", "title": "Validation limits", "body": "Every fixed bound the API enforces is published at `GET /limits` (no auth), so\\na client never has to hard-code a copy that drifts the day a constant moves.\\nThe handler reads `src/constant.rs` directly β€” a changed constant changes the\\nresponse in the same commit.\\n\\n```json\\n{\\n \\"user\\": { \\"min_username_len\\": 3, \\"max_username_len\\": 32,\\n \\"username_separators\\": [\\".\\", \\"_\\", \\"-\\"],\\n \\"reserved_usernames\\": [\\"admin\\", \\"…\\"],\\n \\"min_password_len\\": 6, \\"max_password_len\\": 128,\\n \\"max_name_len\\": 100, \\"max_email_len\\": 254,\\n \\"min_phone_digits\\": 7, \\"max_phone_digits\\": 15,\\n \\"roles\\": [\\"parent\\", \\"student\\", \\"teacher\\", \\"manager\\", \\"admin\\"],\\n \\"themes\\": [\\"light\\", \\"dark\\"], \\"languages\\": [\\"tr\\", \\"en\\"],\\n \\"palette_color_pattern\\": \\"^#[0-9a-fA-F]{6}$\\", \\"palette_color_len\\": 7,\\n \\"session_duration_days\\": 7 },\\n \\"note\\": { \\"max_title_len\\": 200, \\"max_content_len\\": 10000, \\"max_files\\": 10 },\\n \\"file\\": { \\"max_name_len\\": 255, \\"max_content_type_len\\": 100,\\n \\"min_max_file_bytes\\": 1024, \\"max_max_file_bytes\\": 26214400,\\n \\"default_max_file_bytes\\": 5242880,\\n \\"image_content_types\\": [\\"image/png\\", \\"image/jpeg\\", \\"image/webp\\", \\"image/gif\\"] },\\n \\"message\\": { \\"max_subject_len\\": 200, \\"max_body_len\\": 10000, \\"max_label_len\\": 50 },\\n \\"event\\": { \\"max_title_len\\": 200, \\"max_description_len\\": 2000 },\\n \\"course\\": { \\"kinds\\": [\\"course\\", \\"study\\", \\"club\\"], \\"max_title_len\\": 200, \\"…\\": 0 },\\n \\"exam\\": { \\"modes\\": [\\"sync\\", \\"async\\", \\"open\\"],\\n \\"question_kinds\\": [\\"choice\\", \\"text\\"],\\n \\"min_duration_ms\\": 60000, \\"max_duration_ms\\": 86400000,\\n \\"max_attempts\\": 100, \\"unlimited_attempts\\": 0,\\n \\"min_mark\\": 0, \\"max_mark\\": 100, \\"…\\": 0 },\\n \\"homework\\": { \\"statuses\\": [\\"done\\", \\"incomplete\\", \\"missing\\"],\\n \\"max_files_per_submission\\": 10, \\"max_assigned\\": 200, \\"…\\": 0 },\\n \\"question_pool\\": { \\"max_title_len\\": 200, \\"max_body_len\\": 10000, \\"max_solution_body_len\\": 10000 },\\n \\"appointment\\": { \\"max_note_len\\": 500, \\"max_reason_len\\": 1000, \\"max_slot_occurrences\\": 52 },\\n \\"chatbot\\": { \\"max_message_len\\": 8000, \\"max_thread_title_len\\": 200,\\n \\"min_max_message_len\\": 100, \\"…\\": 0 },\\n \\"board\\": { \\"max_title_len\\": 200, \\"max_participants\\": 50,\\n \\"max_stroke_payload_len\\": 4096,\\n \\"max_epoch_strokes\\": 5000, \\"max_board_strokes\\": 50000,\\n \\"max_boards_per_creator\\": 200,\\n \\"stroke_kinds\\": [\\"stroke\\", \\"clear\\"],\\n \\"ws_tick_secs\\": 15, \\"ws_max_board_id_len\\": 64 },\\n \\"settings\\": { \\"max_list_len\\": 20, \\"max_item_len\\": 50,\\n \\"min_exam_kind_weight\\": 1, \\"max_exam_kind_weight\\": 100,\\n \\"max_grade_bands\\": 20, \\"max_grade_label_len\\": 20,\\n \\"required_attendance_statuses\\": [\\"present\\", \\"absent\\", \\"late\\", \\"excused\\"] },\\n \\"request\\": { \\"max_page_limit\\": 500, \\"schedule_past_grace_ms\\": 60000,\\n \\"request_timeout_secs\\": 30 },\\n \\"rate\\": { \\"window_secs\\": 60, \\"auth_per_minute\\": 10,\\n \\"api_per_minute\\": 300, \\"chatbot_per_minute\\": 20 }\\n}\\n```\\n\\nThe `rate` group is the one part that is **not** compile-time: those tiers are\\nenvironment-tunable, so the endpoint serves *this* server's live values (read\\nfrom its running limiters), not the shipped defaults. `0` means the tier is\\noff. A client should read its budget here rather than discovering it by\\ncollecting a `429`.\\n\\n### Two surfaces, one source\\n\\nThe bounds are published twice, on purpose, because clients consume them two\\ndifferent ways:\\n\\n| Surface | Shape | Use it when |\\n|---------|-------|-------------|\\n| `GET /limits` | One JSON document, grouped by resource, closed value sets included | Runtime fetch. No codegen step, survives a deploy skew, and carries things OpenAPI holds awkwardly (`reserved_usernames`, `image_content_types`) |\\n| `/api-docs/openapi.json` | Per-field `maxLength` / `minLength` / `minimum` / `maximum` / `maxItems` on the request schemas | Build-time codegen β€” `openapi-typescript`, `orval`, and friends turn these into types *and* validators automatically |\\n\\nBoth are generated from the same `src/constant.rs`, and **neither is allowed to\\ndrift from it**, which is enforced rather than asked for:\\n\\n- `tests/limits_completeness.rs` parses every `pub const` out of `constant.rs`\\n and fails unless each one is either referenced by `src/web/limits.rs` or\\n listed as a deliberate exclusion *with a reason*. A new constant breaks the\\n suite until someone decides, consciously, whether clients need it.\\n- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 161 published\\n bounds back out of the emitted JSON, and asserts each equals its constant.\\n This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal\\n only** β€” a `const` there does not compile β€” so the annotations are\\n unavoidably a second copy of each number. The test is what makes that copy\\n safe. It also pins the `limit` query parameter's `maximum` to\\n `MAX_PAGE_LIMIT`, a duplication `constant.rs` previously only *asked* a human\\n to maintain.\\n- A third check in `limits_completeness.rs` refuses to let a validation bound\\n be declared **outside** `constant.rs` at all. Without it a limit can hide in\\n a domain module and reach neither surface β€” which is exactly where\\n `MAX_CHATBOT_THREAD_TITLE_LEN` was found sitting, private and unpublished.\\n\\nNotes:\\n\\n- **No auth.** The registration and login forms need the username and password\\n bounds before a session exists, and none of these are secrets β€” they are the\\n same rules a `400` already spells out in prose.\\n- **Answers during a database outage.** `/limits` touches no row, so it is\\n exempt from the guard that answers `503` while the database reconnects β€” a\\n frontend booting against a degraded backend is exactly when it needs the\\n contract. Every route that does read the database still refuses.\\n- **Fetch once.** The values are compile-time constants, so the response only\\n changes with a deploy. Cache it for the session; the `ETag`/`304` path makes\\n a revalidation cheap if you'd rather re-check.\\n- **`/limits` is not `/settings`.** School-adjustable policy β€” the exam kinds\\n and their weights, the attendance statuses, the grade bands, the live\\n `max_file_bytes` and chatbot knobs β€” is on `GET /settings` and changes when a\\n manager edits it. What `/limits` carries for those knobs is the fixed range a\\n manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the\\n attendance statuses no school may remove.\\n- **Open sets travel as a pattern.** `palette_color` accepts any hex accent\\n color, so `/limits` publishes `palette_color_pattern` (a regular expression)\\n and `palette_color_len` instead of a value list β€” validate the shape, not\\n membership in a palette. The pattern describes what the server *accepts*, so\\n it matches either case; the stored (and returned) value is lowercased, which\\n is the one place a response may differ in case from the request.\\n- **Closed value sets ride along.** `roles`, `themes`, `languages`, course\\n `kinds`, exam `modes`, `question_kinds`, homework `statuses`, board\\n `stroke_kinds`, and the\\n uploadable `image_content_types` are the exact accepted spellings β€” build\\n pickers from these rather than from a literal list.", "source": "README.md"}, {"id": "rate-limiting", "title": "Rate limiting", "body": "Requests are limited per client IP over a fixed 60-second window, in two tiers:\\n`/auth/login` + `/auth/register` get a strict budget\\n(`RATE_LIMIT_AUTH_PER_MINUTE`, default 10) against credential brute-force,\\nand every route β€” Swagger included β€” shares a generous catch-all\\n(`RATE_LIMIT_API_PER_MINUTE`, default 300). Exceeding either answers `429` with\\na `Retry-After` header (seconds). Set a limit to `0` to disable that tier β€”\\nuseful for load tests.\\n\\nSending a chatbot message adds a third tier, and it is keyed by **user id**,\\nnot by IP (`RATE_LIMIT_CHATBOT_PER_MINUTE`, default 20), because an inference\\ncosts the school real money and a shared-IP classroom must not spend one\\nstudent's budget on another's. `0` disables it like the other two. It is\\ncharged before anything is written, so a `429` leaves no trace (see\\n\\"Chatbot\\").\\n\\nAll three tiers admit from memory β€” no request ever waits on the database to be\\nlet in β€” but the window **outlives the process**. A background task folds each\\ntier's new admits into one shared `rate_limit` row per tier + client + minute\\nevery 2 seconds, then caps the in-memory bucket by the total that comes back,\\nso a restart mid-minute does not hand every client a fresh budget. One caveat:\\na just-started process can spend up to the tier's budget in the 2 seconds\\nbefore its first fold tightens it. If the database is down the tiers simply\\nfall back to their own local budgets β€” nobody is refused for it.\\n\\nBehind a reverse proxy every connection carries the proxy's address, so also\\nset `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry\\n(the one the proxy itself appends). Leave it off when clients reach the server\\ndirectly β€” the header is client-forged in that case.", "source": "README.md"}, {"id": "cors", "title": "CORS", "body": "Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin`\\n(browsers refuse it on credentialed requests), so origins listed in the\\ncomma-separated `CORS_ALLOWED_ORIGINS` allowlist are echoed back with\\n`Access-Control-Allow-Credentials: true`. When the allowlist is unset the\\nserver reflects the request's `Origin` β€” dev-friendly β€” but **without**\\ncredentials: mirroring with credentials would let any website ride a\\nvisitor's session cookie. A browser frontend that needs the session cookie\\ncross-origin must therefore be allowlisted explicitly.", "source": "README.md"}, {"id": "roles-access-control", "title": "Roles & access control", "body": "Every user has one of five roles, ranked lowest to highest:\\n\\n```\\nparent < student < teacher < manager < admin\\n```\\n\\nThe check is **hierarchical** β€” a higher role satisfies any lower requirement\\n(an admin can do anything a teacher can). New accounts always register as\\n`student`; a role read is re-checked on every request, so a role change takes\\neffect on the user's very next call (no re-login).\\n\\n`parent` is the read-only observer at the bottom of the ladder: an admin ties\\nany number of students to a parent account (`POST /users/{id}/students`), and\\nthe tie is the parent's whole power β€” they list their students\\n(`GET /users/me/students`) and read each one's mark, attendance, pomodoro,\\nand homework reports in full. Student-only checks are exact (`role == student`), so a\\nparent can never enroll, sit an exam, be graded, or land on a roll call; and\\nsitting below every staff bar, they can't touch anything else either β€” except\\nmessages, which any role sends and receives (that's how a parent reaches a\\nteacher). A role\\nchange off either end of a tie (the parent stops being a `parent`, the\\nstudent stops being a `student`) drops the tie, exactly like promotion drops\\ncourse enrollments.\\n\\n| Action | Minimum role | Notes |\\n|------------------------------------------|--------------|-----------------------------------------------|\\n| Register / login / view own account | (any) | Registration always creates a `student` |\\n| View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves |\\n| Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included β€” the role's one write); each party only ever touches their own copy |\\n| Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark β€” a teacher+ may mark anyone expected, themselves included |\\n| Create events | teacher | The audience (school / role / course / registration) is set at creation and editable later |\\n| Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** β€” never for another staff member. Unregistering mirrors the same rule |\\n| List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report |\\n| Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |\\n| View a course's sessions | student | Only inside **visible** courses: enrolled, creator, assigned teacher, or `manager`+ |\\n| List a session's roll call | teacher | The **session's teacher**, or anyone with course-management rights |\\n| Create / edit / delete a course session | teacher | Course-management rights (course creator, an assigned teacher, or `manager`+) |\\n| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights; only students sit on a roster |\\n| Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call β€” the teacher can't self-mark |\\n| Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied |\\n| View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries |\\n| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session |\\n| View **any** user's pomodoro log | teacher | Study oversight β€” same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' |\\n| Ask into the school question pool | student | **Students only** (exact); born `pending` β€” visible to the asker + teacher+ only; the asker may attach/replace/remove one photo while pending |\\n| Read the pool; offer / edit / withdraw own solutions | student | Every `approved` question is school-wide (parents stay out); a solution's author edits its body and photo anytime (solutions never freeze) and deletes it, teacher+ delete any |\\n| Approve a pending pool question; delete any question or solution | teacher | Approval publishes school-wide and **freezes** the content; rejection = deletion β€” moderation never edits, so teacher+ cannot rewrite a solution |\\n| Read the school **question bank**; save / instantiate bank questions | teacher | Every bank row is school-wide (reads + copy into an exam); saving one makes the caller its owner |\\n| Edit / delete a bank question (and its images) | teacher | **Owner only** (admin bypass); bank rows carry no exam link, so they never freeze |\\n| Read **own** attendance report | student | |\\n| Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created + assigned; `manager`+: all); exam **drafts** show only to the course's managers |\\n| Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** β€” staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |\\n| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |\\n| Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |\\n| Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights β€” one teacher can't read another's answer key |\\n| Watch an exam's live monitor (poll the snapshot) | teacher | Course-management rights |\\n| Create courses | teacher | The creator manages the course, and owns it for good |\\n| Assign / unassign a course's teachers | manager | Staffing is the office's call β€” a course's own creator cannot hand rights to peers; the assignee must be `teacher`+ |\\n| Delete a course | teacher | Only the **creator**, or a `manager`+ β€” an assigned teacher runs the course but doesn't own it |\\n| Manage inside a course: edit it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | The **course creator**, a teacher **assigned** to it, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions or homework won't delete (`409`) |\\n| View a course's roster, an exam's result list / statistics | teacher | Course-management rights |\\n| Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself |\\n| Assign / edit / delete homework; grade it; read its roster | teacher | Course-management rights; an `assigned` subset (≀ 200 enrolled students) can't be narrowed over existing work (`409`); a grade (`done`/`incomplete`/`missing` + optional mark) freezes the submission until removed |\\n| Submit **own** homework (text + files); read own submission and grade | student | **Students only** β€” staff never submit; enrolled + in the audience; editable until graded; ≀ 10 files of any type, each ≀ `max_file_bytes`, always downloaded as attachments |\\n| Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full β€” statuses/marks/flags, never files |\\n| Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields |\\n| Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen β€” the client then follows the device preference |\\n| List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports β€” a parent changes nothing, anywhere |\\n| Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |\\n| Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call |\\n| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role |\\n\\n### Bootstrapping the first admin\\n\\nThere is no self-service path to `admin` β€” registration always creates a\\n`student`. The first admin comes from the startup seed: set both\\n\\n```sh\\nADMIN_USERNAME=admin\\nADMIN_PASSWORD=admin123 # local-dev default used by compose.yaml; change it\\n```\\n\\nand on boot the account is created with the `admin` role **if the username\\ndoesn't exist yet**. The seed is idempotent and deliberately conservative: it\\nnever promotes or rewrites an existing account (if the name is taken by a\\nnon-admin it logs a warning and leaves it alone β€” promoting someone else's\\naccount would be an escalation). Setting only one of the two variables aborts\\nstartup. `compose.yaml` ships with the credentials above for local dev.\\n\\nThat admin can then promote everyone else through `PATCH /users/{id}/role`.\\n\\nManual fallback (also the recovery path if the seeded name was squatted or the\\nsole admin locked themselves out): run\\n\\n```surql\\nUPDATE user SET role = 'admin' WHERE username = 'ada';\\n```\\n\\nagainst the SurrealDB server β€” e.g.\\n`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db hezarfen`\\n(in the container setup, `podman exec -it hezarfen-surrealdb /surreal sql ...`).", "source": "README.md"}, {"id": "endpoints", "title": "Endpoints", "body": "`Auth` is the minimum role; `no` means no session required, `student` means any\\nlogged-in user.\\n\\nA course is a regular class (kind `course`, the default), an *etΓΌt* (kind\\n`study` β€” a supervised study session), or a *kulΓΌp* (kind `club` β€” a student\\nclub). The three kinds behave identically everywhere β€” enrollment, exams,\\nsessions, marks β€” the kind is a label the UI renders differently, settable at\\ncreation and editable later. A course may also carry a `capacity`: once the\\nroster reaches it, new enrolls are refused with `409` (members already on the\\nroster are unaffected, even if the cap is later lowered below them; `null`\\nlifts the cap).\\n\\n**Who runs a course.** Its **creator** owns it for good β€” only they (or a\\nmanager+) may delete it. On top of that, a manager can **assign** any\\n`teacher`+ to the course with `POST /courses/{id}/teachers` (`{user_id}`,\\nidempotent) and drop them again with `DELETE /courses/{id}/teachers/{user}`.\\nAn assigned teacher gets full **course-management rights** β€” edit the course,\\nenroll and unenroll students, add exams, sessions and subjects, grade, take\\nroll call β€” but *not* the two owner powers: they cannot delete the course, and\\nthey cannot change who else teaches it. Staffing is deliberately the office's\\ncall, so a course's own creator cannot hand rights to their peers; only\\nmanager+ may touch the list. Every course response carries its `teachers`\\narray alongside `creator`, and a user demoted below `teacher` is swept off\\nevery course they were assigned to (the mirror of promotion dropping\\nenrollments).\\n\\nCourse data is walled per course. A course, its exams, its sessions, and its\\nsubjects are\\n**visible** only to its enrolled users, its creator, its assigned teachers,\\nand manager+ β€” a student\\nsees just the classes they were added to, and the `/courses` / `/exams`\\ncatalogs are filtered accordingly. Teacher-level reads *inside* a course\\n(roster, results, statistics, the question list, answer sheets, the live\\nmonitor) additionally need **course-management rights** (creator, an assigned\\nteacher, or manager+):\\none teacher cannot look into another teacher's course, and the per-user\\nmarks/attendance reports narrow to the courses the caller manages.\\n\\n**Paging.** Every list endpoint below (the rows tagged **Β· paged**) accepts\\n`?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope\\nrather than a bare array. `total` is the full row count *before* the window, so\\na frontend can show \\"100 of 256\\" and page with `offset`. Paging is **opt-in**:\\nomit `limit` and you get every remaining row (the echoed `limit` is then\\n`null`), so a caller that sends no parameters still receives the whole list β€”\\nnothing silently truncates. `limit` must be `1`–`500`, `offset` defaults to `0`\\nand must be β‰₯ 0 (bad values are `400`), and an `offset` at or past the end\\nreturns an empty `items` (not an error). Deliberately **not** paged β€” these keep\\ntheir existing shapes: the student exam-room reads\\n`/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and\\n`/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`.\\n\\n**Schedule window (`GET /events`, `GET /exams`).** Both lists additionally\\naccept `?starts_after=` and `?ends_after=`, UTC unix-millis, both optional and\\nindependent (AND-ed when both are sent). `ends_after=T` keeps rows whose window\\nhas not finished β€” `ends_at > T`, falling back to `starts_at > T` when `ends_at`\\nis `null`; `starts_after=T` keeps rows with `starts_at > T`. A row with no\\nschedule at all (an event without times, an exam with no `mode` or in `open`\\nmode) is excluded by either parameter. Supplying either one flips the order to\\n**ascending by schedule** (`starts_at`, falling back to `ends_at`; ties by id),\\nso `?ends_after=<now>&limit=20` gives the twenty *soonest* rows instead of the\\ntwenty newest-created β€” with neither parameter the list is byte-for-byte the\\nnewest-first list it always was. `total` is the count after visibility *and*\\nwindow filtering, before paging; negative values are a `400` naming the field.\\n\\n| Method | Path | Auth | Description |\\n|--------|----------------------------------|---------|---------------------------------|\\n| GET | `/health` | no | Liveness check |\\n| GET | `/` | no | Same as `/health` |\\n| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |\\n| GET | `/limits` | no | Every fixed validation bound, grouped by resource β€” see Validation limits |\\n| GET | `/swagger` | no | Interactive API docs (Swagger UI) |\\n| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |\\n| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |\\n| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken β€” see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |\\n| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` β€” own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) Β· paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` β€” find users by username/name fragment (pickers); refs only, no contact info Β· paged |\\n| GET | `/users` | admin | List all users Β· paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` β€” set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` β€” tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students Β· paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |\\n| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes Β· paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) β€” ≀ the school's `max_file_bytes`, ≀ 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) Β· paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |\\n| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` β€” send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` β€” the caller's folder, newest first; `?folder=inbox&read=false&limit=1` β†’ `total` is the unread badge Β· paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` β€” read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** β€” only from the trash (`409` elsewhere); the row vanishes once both sides deleted |\\n| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` β€” `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` β€” mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) Β· paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` Β· paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` β€” seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |\\n| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` β€” publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, ≀ 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) β€” a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar β€” future slots only, demoted teachers' slots left out Β· paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` β€” book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests Β· paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` β€” call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included β€” they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` β€” counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal β€” this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |\\n| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` β€” `kind` is `course` (default), `study` (etΓΌt), or `club` (kulΓΌp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) Β· paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses Β· paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ β€” **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` β€” assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` β€” enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) Β· paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β€” add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β€” add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |\\n| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` β€” roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) Β· paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` β€” add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) Β· paged |\\n| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist β€” the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` β€” grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) Β· paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt β€” students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) Β· paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question β€” the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam β€” copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** β€” copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question β€” text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` β€” autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers ⋃ marks), ascending β€” the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first β€” the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** β€” the answer key the caller checks their own sheet against (same review gate) Β· paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers ⋃ marks), ascending β€” only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster Γ— latest attempts Γ— marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |\\n| GET | `/bank-questions` | teacher | The school-wide question bank β€” `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) Β· paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist β€” `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question β€” the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` β€” assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≀ 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) Β· paged |\\n| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) Β· paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade β€” the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades β€” file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` β€” hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part β€” **any** content type, ≀ `max_file_bytes`, ≀ 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) β€” the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student Γ— submission/files/grade + computed `late`/`missing`/`unenrolled` β€” a straggler's stale work stays visible (course manager) Β· paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` β€” grade `done`/`incomplete`/`missing` (+ optional 0–100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable β€” that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) β€” readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade β€” un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows β€” submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` β€” full, statuses and marks only, never files Β· paged |\\n| POST | `/questions` | student | `{title, body}` β€” ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` β€” the pool questions visible to the caller, each with its `solution_count` Β· paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question β€” publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` β€” offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first β€” a discussion thread Β· paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` β€” edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |\\n| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) Β· paged |\\n| GET | `/work/{user}` | manager | A staff member's work log Β· paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` β€” correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |\\n| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** β€” a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` Β· paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape Β· paged; *or a `parent` linked to `{user}` |\\n| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |\\n| POST | `/terms` | manager | `{name, starts_at, ends_at}` β€” past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first Β· paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course still links to it |\\n| POST | `/meals/menus` | manager | `{date, slot, capacity?}` β€” publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first Β· `?from=&to=` inclusive `YYYY-MM-DD` range Β· paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` β€” the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` β€” add a dish (≀ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` β€” record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` β€” take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first Β· paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included Β· paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent β€” cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` β€” mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu Β· paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history Β· `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day Β· paged Β· own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` β€” record money received; **admin only**, appends a `credit` line |\\n| POST | `/payments/plans` | manager | `{name, installments}` β€” write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it β€” its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (≀ 200) β€” place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first Β· paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` β€” record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` β€” hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` β€” undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines β€” charges, payments, refunds, reversals β€” newest first Β· paged Β· own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |\\n| POST | `/chatbot/threads` | student | `{title?}` β€” start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first Β· paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` β€” rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first β€” user and assistant rows alike Β· paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≀ `max_chatbot_message_len`) β€” send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` β€” nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β€” or one `error` β€” and close; an already-finished answer replays (see \\"Chatbot\\") |\\n| POST | `/boards` | student | `{title, participant_ids?}` β€” open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first Β· paged |\\n| GET | `/boards/{id}` | student | One board β€” a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |\\n\\n`status` must be one of the school's attendance statuses (`GET /settings`);\\nthe core four `present | absent | late | excused` always exist, plus whatever\\nthe school added.\\n`kind` must be one of the school's exam kinds (`GET /settings`; defaults:\\n`homework | quiz | midterm | final | project | oral`). The kind carries the\\nexam's weight in the course average β€” an integer `1`–`100` set per **kind** in\\nsettings (defaults all `1`), resolved when a report is read; an exam whose\\nkind was later removed from settings counts with weight `1`.\\nA course may carry a `term_id` (`null` = unassigned); on `PATCH\\n/courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`\\nclears it.\\n`role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are\\nULIDs. `parent` accounts are made by an admin (register as `student`, then\\n`PATCH /users/{id}/role`) and observe only the students an admin tied to them\\nβ€” see \\"Roles & access control\\".\\nAn exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row,\\nnever in a `note`. Students never grade anyone β€” grading is teacher+ with\\ncourse-management rights, and the target must be enrolled in the exam's course;\\na student reads just their own mark via `GET /exams/{id}/result`.\\nA course average is `Ξ£(markΓ—weight) / Ξ£(weight)` over the student's **graded**\\nexams in that course (`null` while nothing is graded β€” ungraded exams are\\nskipped, not zeroed). The overall average is the plain mean of the non-null\\ncourse averages. Unenrolling keeps result rows: the marks drop out of the\\nreport until re-enrollment, but stay visible on the exam itself. A course\\nwith anyone still on its roster refuses deletion (`409`) β€” empty the roster\\nfirst; once empty, deleting it cascades its exams, their results, its\\nsessions and roll call, and its subjects.\\nA **subject** is one topic of a course's curriculum (`name` ≀ 200 chars,\\noptional `description` ≀ 2000): every exam question carries a mandatory\\n`subject_id` naming one of *its own course's* subjects (an unknown or\\nforeign-course subject is a `400`), so exam content is always attributable to\\na topic. A subject's course link is fixed at creation, and a subject still\\nreferenced by questions refuses deletion with a `409` β€” re-tag (PATCH the\\nquestions' `subject_id`) or delete those questions first. Questions written\\nbefore subjects existed are **destroyed on boot** (answers first) β€” the clean\\nbreak instead of inventing a placeholder topic.\\nEvent `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both\\nare given, `ends_at` must not precede `starts_at`, and neither may be set in\\nthe past (else `400`). On `PATCH`, an omitted time keeps its value and an\\nexplicit `null` clears it.\\nAn event's `audience` is a tagged object β€” `{\\"kind\\": \\"school\\"}` (the default),\\n`{\\"kind\\": \\"role\\", \\"role\\": \\"student\\"}` (that exact role, no \\"and above\\"),\\n`{\\"kind\\": \\"course\\", \\"course\\": \\"<id>\\"}` (the course's current enrollment), or\\n`{\\"kind\\": \\"registration\\", \\"capacity\\": 30}` (a signup list; `capacity` optional,\\n`null` = unlimited) β€” and is the event's **expected-attendee roster**, resolved\\nlive at read time: role changes, (un)enrollments, and (un)registrations move\\npeople in and out by themselves. It never hides the event β€” everyone sees every\\nevent. Only audience members can be marked; `GET /events/{id}/roster` joins the\\nlive roster with the recorded marks (`status: null` = expected but never\\nmarked). Attendance rows for people a later audience edit (or unenrollment /\\nrole change) dropped stay stored and listed under `/events/{id}/attendance`,\\nbut leave the roster report.\\nA registration list fills through `POST /events/{id}/register`: teachers place\\nstudents (a student never registers, not even themselves) and take seats only\\nfor themselves β€” registering another staff member is refused. Re-registering\\nsomeone is a no-op, a full list is a `409`, and the list freezes the moment\\nthe event starts β€” or, when only `ends_at` is set (a pure signup deadline),\\nthe moment it passes (register and unregister both). Signup rows survive an\\naudience switch inertly and resurface if the event returns to the registration\\nkind; deleting the event deletes them. Pre-existing hand-picked (`users`)\\naudiences convert on boot: each listed user becomes a signup row credited to\\nthe event's creator, and the audience becomes an uncapped registration list.\\nReading a child collection of a missing parent (`/events/{id}/attendance`,\\n`/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`,\\n`/courses/{id}/sessions`, `/courses/{id}/subjects`, `/courses/{id}/homework`,\\n`/homework/{id}/submissions`, `/sessions/{id}/attendance`) is a `404`, not an\\nempty list.\\nPersonal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same\\noptional set on every account, whatever the role, and is `null` until filled\\nin. On `PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) each field\\nis independent: omitted (or `null`) keeps the current value, an empty string\\n`\\"\\"` clears it, anything else is validated β€” email must look like\\n`name@example.com`, phone is 7–15 digits with an optional `+` and cosmetic\\nseparators, `birth_date` is a real `YYYY-MM-DD` calendar date not in the\\nfuture. Names allow unicode; usernames are strict: lowercase letters and\\ndigits plus non-consecutive interior `.`, `_`, `-` separators, starting and\\nending with a letter or digit (3–32 chars). Staff-looking names (`admin`,\\n`administrator`, `root`, `support`, `system`, `moderator`, `staff`) are\\nrejected at `/auth/register` only β€” the `ADMIN_USERNAME` bootstrap may still\\nseed them.\\nUI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`,\\n`palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the\\nsame account row and come back on every user response (`/auth/me` included).\\n`PATCH /users/me/preferences` (or the admin `PATCH /users/{id}/preferences`)\\nuses the same field semantics as the profile patch: omitted keeps, `\\"\\"` clears\\nback to `null` (\\"never chose\\" β€” the client then follows the device\\npreference, or its own default accent), anything else must be valid or the\\nwhole patch is a `400`. `palette_color` is the one **open** set: any valid hex\\npasses (mixed case in, stored and returned lowercase), so a new frontend\\npalette needs no backend change β€” `/limits` publishes its pattern rather than a\\nlist of colors.", "source": "README.md"}, {"id": "appointments", "title": "Appointments", "body": "Office hours and parent-teacher conferences, booked instead of arranged by\\nmessage. A teacher+ **publishes availability**; a student or a parent\\n**books** one of those windows with a reason; the teacher **decides**. Two\\nrows carry it: an `appointment_slot` (the offer) and an `appointment` (the\\nbooking sitting on it) β€” a slot is never \\"half booked\\", and a refused request\\nstays readable instead of vanishing.\\n\\nA slot is a window on one teacher's calendar: `starts_at`/`ends_at` (unix\\nmilliseconds, `starts_at` strictly before `ends_at`, neither in the past β€” the\\nusual 60-second grace) plus an optional `note` (≀ 500 chars) shown to\\nrequesters (\\"office hours\\", \\"veli gΓΆrüşmesi\\"). Windows are **half-open**, so\\n10:00–10:30 and 10:30–11:00 are two slots, not a collision. A window that *does*\\noverlap one the same teacher has already published is refused with a `409` β€” the\\nguard is **per-teacher** (two teachers may hold office hours at the same hour)\\nand boundary-touching windows are legal by that same half-open rule, which is\\nhow an hour gets carved into back-to-back slots. `POST\\n/appointments/slots` publishes on the caller's *own* calendar (managers and\\nadmins included β€” the calendar always belongs to whoever posted) and **always\\nanswers an array**: one element for a one-off, one per occurrence for a\\nrecurring publish.\\n\\n`repeat_weekly: true` with an `until` expands the same window every seven days\\nup to and including `until`, server-side, into **concrete rows** sharing a\\n`series` id β€” no recurrence rule is stored, so one week can be cancelled\\nwithout touching the rest. At most 52 occurrences (a year); asking for more is\\na `400`, as is `repeat_weekly` without `until` β€” and so is a window sitting so\\nfar ahead that shifting it by a week would run off the end of representable\\ntime (the shift is checked, never wrapped: a wrapped end would land *before*\\nits start, and an inverted window can never overlap anything, which would\\nquietly disable the double-booking guard). A recurring publish is\\n**all-or-nothing**: every occurrence is checked β€” against the slots already\\nstored *and* against the earlier occurrences of the same batch, which a window\\nlonger than a week overlaps itself β€” before a single row is written, so a\\nmid-series collision answers `409` and leaves no stray weeks behind. Delete one\\noccurrence with\\n`DELETE /appointments/slots/{id}`, the whole publish with `DELETE\\n/appointments/slots/series/{series}`.\\n\\n```json\\nPOST /appointments/slots\\n{ \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"repeat_weekly\\": true, \\"until\\": 1901209600000 }\\n\\n201 [ { \\"id\\": \\"01J8…A\\", \\"teacher\\": {\\"id\\": \\"01J8…T\\", \\"username\\": \\"ayse\\",\\n \\"display_name\\": \\"Ayşe YΔ±lmaz\\"},\\n \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"series\\": \\"01J8…S\\", \\"created_at\\": 1899… },\\n { \\"id\\": \\"01J8…B\\", …, \\"starts_at\\": 1900604800000, \\"series\\": \\"01J8…S\\" } ]\\n```\\n\\n`GET /appointments/slots` is two lists behind one path: a teacher+ reads\\n**their own** calendar, past occurrences included; everyone else reads the\\n**bookable** calendar β€” future slots only, earliest first. A teacher demoted\\nafter publishing leaves **inert** slots: their live role is re-read, so those\\nslots drop out of the bookable list and booking one is refused with a `409`.\\nThe list does not say whether a slot is already taken β€” booking a taken one\\nanswers `409`.\\n\\n**Booking.** `POST /appointments` (`{slot, reason}` β€” the reason is required,\\n≀ 1000 chars) is for **students and parents only**; staff arrange between\\nthemselves off this API. A parent books for *themselves* β€” this is the\\nparent-teacher conference, not a booking on behalf of a child. The request\\nlands `pending`, always: publishing availability is not consent to a\\nparticular person and a particular topic, so approve/reject still applies.\\n\\nA booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two\\nare **live** and hold the slot; rejecting or cancelling frees it for someone\\nelse immediately (the slot carries an `occupied` counter, taken by a booking\\nand handed back in the same transaction as the reject or cancel that settles\\nit, so the seat is decided by the database rather than by a count two\\nconcurrent bookings can both read as free). The decisions:\\n\\n- `PATCH /{id}/approve` β€” the slot's teacher (or manager+) confirms. Refused\\n (`409`) when the effective window has already started.\\n- `PATCH /{id}/reject` β€” turns it down; the slot frees up.\\n- `PATCH /{id}/cancel` β€” **the requester only**, from either live state.\\n Anyone else is a `403`, the slot's teacher and a manager/admin included (the\\n guard compares ids, not roles). A teacher ends a booking by **rejecting** it\\n while it is `pending`, and an approved one by counter-proposing another time\\n (`/reschedule`, which sends it back to `pending`) and then rejecting it β€” or\\n simply by rescheduling to a time that works. Refused (`409`) once the\\n meeting's window has started: a\\n meeting that already began is history, not a plan. The guard sits in the\\n domain's `cancel` itself, on a fresh read compared-and-set into the row, so\\n every way of cancelling β€” the decline below included β€” inherits it.\\n- `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) β€” the teacher\\n **counter-proposes**. The times land on the *same* row as\\n `proposed_starts_at`/`proposed_ends_at`, the status goes back to `pending`\\n and `decided_by` clears, because leaving it `approved` would silently move a\\n confirmed appointment. The slot stays held meanwhile. A window that has\\n already opened is refused (`409`): the 60-second grace on the times is for\\n clock skew, not for proposing into a meeting already underway β€” one nobody\\n could then cancel.\\n- `PATCH /{id}/reschedule/accept` β€” the **requester** only: this *is* approval\\n at the new time, so the overlap guard runs again β€” and so does the\\n already-started guard (`409`). Agreeing to a window that has begun does not\\n help: the meeting could never be cancelled. The booking stays `pending`, so\\n the teacher just proposes a time that can still happen.\\n- `PATCH /{id}/reschedule/decline` β€” the requester only, and it **cancels the\\n booking**: the proposal replaced the time that was asked for, so there is\\n nothing to fall back to. The row stays readable as `cancelled` with the\\n refused proposal still on it β€” book another slot instead. Declining *is* a\\n cancel, so it answers to the cancel deadline too (`409` once the effective\\n window has started).\\n\\n**Who settled it, and why.** Every settled booking carries its own audit trail\\non the row: `decided_by` (who approved or rejected β€” cleared again by a\\ncounter-proposal), `cancelled_by` (who called it off, stamped by `cancel` and by\\na declined counter-proposal), plus the optional free text that came with the\\ndecision β€” `reject_reason` on `PATCH /{id}/reject` and `cancel_reason` on\\n`PATCH /{id}/cancel` and `/reschedule/decline`. Both reasons are optional: the\\nwhole body may be omitted, a blank one records nothing (`null`), and a present\\none is validated like the booking's own reason (≀ 1000 chars, `400` past that)\\nbefore it reaches the row. They are **not public**: bookings are only ever\\nrendered to the person who requested them and to the slot's teacher (a\\nmanager/admin acting on one by id sees the response to their own call), so\\n\\"couldn't make it, sorry\\" goes no further than the two people it concerns. Rows\\nwritten before these fields existed simply read back `null`.\\n\\nA booking's effective window is the accepted counter-proposal when there is\\none and the slot's own window otherwise; that is what `starts_at`/`ends_at` on\\nan `AppointmentResponse` report, and what the cancel deadline is judged on.\\n\\n**No double-booking.** Two `approved` meetings may never overlap for the same\\nteacher *or* the same requester (`409`). The guard runs at approval β€” the\\nmoment anyone is actually committed β€” and again on accepting a counter-proposal,\\nbecause the time moved. Approval also refuses (`409`) an **effective window\\nthat has already started** (the proposal's when one stands, the slot's\\notherwise), for the same reason booking one is refused. Requesting is checked more loosely: a booking is\\nrefused up front only when the slot's window has already started (booking it\\nwould create a meeting `cancel` refuses to undo β€” the 60-second publish grace\\nis for clock skew, not for booking into the past), when the slot is already\\ntaken, or when the *requester* is already committed at that hour; a clash on the teacher's side is theirs to\\nresolve when they decide, since refusing a request against a window they\\nthemselves published would only confuse. Touching windows never conflict.\\n\\nDeletion follows the same rule as the rest of the codebase: a slot carrying a\\nlive (pending or approved) booking refuses to go (`409`) β€” reject or cancel\\nthat booking first β€” and a series delete is all-or-nothing, `409` if *any*\\noccurrence still carries one, so the person waiting is dealt with rather than\\nleft stranded on a stray week. Settled (rejected/cancelled) bookings cascade\\naway with their slot.\\n\\n`GET /appointments` is likewise two lists: a teacher+ sees the bookings aimed\\nat their own slots (their request inbox), everyone else the ones they\\nrequested, newest first, paged. Managers and admins read their own inbox here\\ntoo β€” they may still decide any booking by id.", "source": "README.md"}, {"id": "messaging", "title": "Messaging", "body": "One-to-one, mail-style (subject + body + an optional free-text `label` the UI\\nrenders as a badge β€” \\"EtΓΌt\\", \\"SΔ±nav\\"; no threads): any user writes to any\\nuser β€” student to teacher, parent to teacher, teacher to student; only\\nmessaging yourself is refused. A single stored message serves both parties,\\nbut each **owns their copy independently**: the recipient's moves through\\n`inbox` β†’ `archive`/`trash` and carries the `read` flag (the sender sees it\\nas a read receipt); the sender's moves through `sent` β†’ `archive`/`trash`. Filing or\\ndeleting your copy never changes the other side's view.\\n\\nEvery copy remembers where it was filed from, so it can go back there. Moving\\ninto `archive`/`trash` stamps the folder you left onto the copy's\\n`previous_folder`, and restoring is a `PATCH` of `folder` back to that value:\\nan inbox message you archive and then trash returns to `archive`, and from\\nthere to `inbox`. Two folders are never stamped β€” the trash itself (pulling a\\ncopy out of the trash must not leave it pointing back at the discard pile) and\\nthe folder you are already in β€” and moving back to `inbox`/`sent` clears the\\nstamp. `previous_folder` is therefore `null` for any copy sitting in its home\\nfolder, and for copies filed before the field existed; both mean \\"restore to\\n`inbox`\\" (`sent` for the sender's copy).\\n\\nListing is per folder β€” `GET /messages?folder=` with `inbox` (default),\\n`sent`, `archive`, or `trash` (trash shows both received and sent copies you\\ntrashed) β€” newest first, paged, with sender/recipient rendered as person refs\\nplus their role. `?read=false` narrows to unread (`true` to read), and since\\n`total` counts the filtered view, `?folder=inbox&read=false&limit=1` is the\\none-row unread-badge query. `PATCH /messages/{id}` flips `read` (recipient only) or\\nmoves your copy (`folder`), restoring included. `DELETE` is\\npermanent, allowed only while your copy sits in the trash (`409` otherwise),\\nand physically removes the row once both sides have deleted theirs. Replying\\nis just sending a new message back β€” the frontend prefixes the subject if it\\nwants an `Re:`.", "source": "README.md"}, {"id": "question-pool", "title": "Question pool", "body": "Students get stuck; the pool is where the school unsticks them β€” with a\\nmoderation gate so nothing unreviewed goes school-wide. `POST /questions`\\n(students only, exact role) creates the question `pending`: only the asker\\nand teacher+ can see it (anyone else gets a `404`, not a `403` β€” a pending\\nquestion's existence is nobody else's business), and `GET\\n/questions?status=pending` is a teacher's approval queue. The asker may\\nattach **one photo** of the problem (`POST /questions/{id}/image`,\\n`multipart/form-data` with a `file` part β€” raster types only, no SVG, ≀ the\\nschool's `max_file_bytes`), replace it, or remove it β€” while pending only.\\n\\n`POST /questions/{id}/approve` (teacher+) publishes it: the question becomes\\nreadable by every signed-in user above `parent`, and its content β€” title,\\nbody, photo β€” **freezes**, because an edit after approval would bypass the\\nmoderation that just happened. There is no rejected state and no edit\\nendpoint: to fix a typo the asker deletes and re-asks; to reject, a teacher+\\ndeletes. Approving twice is a `409`; the response records `approved_by`.\\n\\nAnyone in the school (student through admin β€” not parents) may then offer a\\n**solution**: `POST /questions/{id}/solutions` with a text body, listed\\noldest-first like a discussion thread (`GET`, paged). Solutions are the\\nunmoderated half of the pool, so nothing about them ever freezes: the author\\nβ€” and only the author, teacher+ included out β€” may edit the body (`PATCH\\n/questions/{id}/solutions/{sid}`) and attach one **photo** of the worked\\nsteps (`POST /questions/{id}/solutions/{sid}/image`, same raster-only rules\\nand `max_file_bytes` cap as the question's photo), replace it, or remove it,\\nat any time; moderation stays delete-only β€” a teacher+ removes a bad\\nsolution, never rewrites someone else's words. A solution is deleted by its\\nauthor or by teacher+, its photo blob going with it; deleting a question β€”\\nasker withdrawing, or teacher+ moderating β€” takes its solutions and every\\nphoto blob (its own and its solutions') with it. Each question row reports\\nits `solution_count`, and questions and solutions embed their people as\\nperson refs (`{id, username, display_name}`), so the UI never shows a raw\\nULID.", "source": "README.md"}, {"id": "per-school-policy-settings-terms", "title": "Per-school policy (settings & terms)", "body": "Every school runs differently; the parts that vary are data, not code. One\\neditable `settings` singleton (`GET /settings` for any signed-in user,\\n`PATCH /settings` for manager+) carries seven knobs:\\n\\n- **`exam_kinds`** β€” the accepted `kind` values for new exams, each an\\n object `{name, weight}`. The weight (`1`–`100`) is how many times an exam\\n of that kind counts into its course average β€” weighting is school policy,\\n set once per kind, never per exam. Defaults to `homework, quiz, midterm,\\n final, project, oral`, all weighing `1` (a plain average); replace the\\n list with whatever the school grades and weighs (`{\\"name\\": \\"final\\",\\n \\"weight\\": 3}`, …). Reports resolve weights live: editing a weight\\n re-weights every exam of that kind at once. For the same reason a kind\\n whose exams already carry marks cannot be removed from the list (`409`):\\n those marks would silently re-weight. An unmarked kind leaves freely, and\\n an exam keeping a since-removed kind counts with weight `1` β€” but it can no\\n longer be graded (`409`) until the school offers that kind again, which is\\n what keeps \\"a marked kind cannot be removed\\" true from both ends. The same\\n rule pointed at one exam: an exam that already carries marks keeps its\\n `kind` (`PATCH /exams/{id}` answers `409`), because re-pointing it would\\n re-weight those marks just as silently.\\n- **`attendance_statuses`** β€” what attendance marking accepts. The core four\\n (`present`, `absent`, `late`, `excused`) are mandatory because the\\n attendance rate is defined over them (`(present+late) /\\n (present+absent+late)`); school extras (say `online`) are **rate-neutral**\\n and tally under `custom` in the attendance reports.\\n- **`grade_bands`** β€” how numeric marks display: a list of `{min, label}`\\n bands (`85 β†’ \\"AA\\"`, `50 β†’ \\"CC\\"`, …). One band must start at `0` so every\\n mark maps; an empty list (the default) means numeric-only. Storage and\\n averaging stay `0`–`100` forever β€” bands only add `grade`,\\n `average_grade`, and `overall_grade` labels to the mark report, so a school\\n can switch display scales without touching a single stored mark.\\n- **`max_file_bytes`** β€” the per-file size cap for uploads (note files and\\n exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;\\n a server hard cap β€” uploads buffer in memory), default `5242880` (5 MiB).\\n Checked at upload time only: lowering it never touches already-stored files.\\n- **`chatbot_history_turns`** β€” how many prior **messages** of a thread the\\n chatbot is given as context, `1`–`50` (default `10`). The unit is messages,\\n not exchanges: a question and its answer are two, so the default remembers\\n five question/answer pairs. Every one of them is re-sent on every reply, so\\n the number is both what the bot remembers and what each answer costs.\\n- **`max_chatbot_threads`** β€” how many chatbot threads one user may\\n keep, `1`–`500` (default `50`); at the cap the user deletes an old one\\n first. Storage protection, not a usage quota β€” that is the per-minute\\n message limit.\\n- **`max_chatbot_message_len`** β€” character limit on one chat message,\\n `100`–`8000` (default `4000`); the ceiling is a server hard cap, because\\n the message and its history must fit one bridge frame.\\n\\nA `PATCH` replaces only the fields it carries, each wholesale, and validation\\nis all-or-nothing. Concurrent edits are safe: each save applies only if the\\npolicy still matches the snapshot it merged from (retrying over the fresh row\\notherwise), so two managers patching different fields both land instead of\\nthe later write silently reverting the earlier one. Editing a list never\\nrewrites history: an exam keeps its retired kind, a roll-call row keeps its\\nretired status β€” only **new writes** are held to the current lists (which is\\nwhy grading an exam whose kind has left the list is refused).\\n\\nThe kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see \\"Food program: menus, dishes, bookings & the ledger\\").\\n\\nAcademic structure is data too. **Terms** (`/terms`) model whatever calendar\\nthe school runs β€” semester, trimester, quarter systems are just rows with a\\nname and a date range. Courses may link to one via `term_id` (nullable), and\\ndeleting a term is refused with a `409` while any course still links to it β€”\\nunlink those courses (`PATCH /courses/{id}` with `\\"term_id\\": null`) or delete\\nthem first, so the calendar never disappears under them. Term dates may lie in the past,\\ndeliberately: a school adopting the app mid-year backfills its calendar β€”\\nunlike exam/lesson/event times, which reject backdating.\\n\\nWhat stays fixed is deliberate too: the four roles, the `0`–`100` mark scale,\\nvalidation bounds, and the UTC time policy are invariants, not preferences\\n(rename role labels in the frontend if a school says \\"principal\\" instead of\\n\\"manager\\"). Deployment knobs (ports, rate limits, admin seed, CORS) remain\\nenvironment variables β€” the model is **one school per deployment**, which\\nkeeps every school's data physically isolated.", "source": "README.md"}, {"id": "food-program-menus-dishes-bookings-attendance-the-ledger", "title": "Food program: menus, dishes, bookings, attendance & the ledger", "body": "The school publishes **one menu per calendar day and meal slot** (`POST\\n/meals/menus`). Two shapes there are deliberate:\\n\\n- **`date` is text**, `YYYY-MM-DD`, not a timestamp. \\"One menu per day and\\n slot\\" is an equality test on the school's own day, and a midnight-in-millis\\n day is only unique for one timezone. Fixed-width and zero-padded, so the\\n text sorts chronologically β€” which is what the inclusive `?from=&to=` range\\n filter and the newest-day-first ordering are built on.\\n- **`slot` is a snapshot**, not a link into settings. It must be one of the\\n school's `meal_slots` (`GET /settings`) *when the menu is written*, and it\\n is stored as text β€” so retiring a slot later never rewrites a menu already\\n published under it. The slot's `serving_minute` is *not* snapshotted: the\\n booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any\\n menu was published for cannot be removed from the list (`409`), same\\n contract exam kinds have with graded exams.\\n\\nThe day+slot pair is unique: a second publish for the same meal answers `409`\\nβ€” edit the first one instead. Only `capacity` is patchable (`null` = uncapped)\\nβ€” `date` and `slot` are immutable, because a menu on another day is another\\nmenu.\\n\\n**Dishes** hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, then\\n`PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional\\ndescription (blank or `null` clears it), dietary `tags` drawn from the\\nschool's `dietary_tags` list β€” an unknown tag is a `400`, never a stored\\nstring β€” and a `price_minor`.\\n\\n### Dietary profiles and conflicts\\n\\nA student carries a **dietary profile**: a list of tags plus a free-text note\\nfor the kitchen, one row per student (the record key *is* the student's id).\\nThe tags come from the *same* `dietary_tags` list a dish is tagged from β€”\\nthere is deliberately no second vocabulary, because one shared list is exactly\\nwhat makes \\"is this dish a problem for this student\\" answerable as a set\\nintersection, without the backend knowing any nutrition.\\n\\nWriting it is **manager+** (`PATCH /meals/profiles/{user}`, first write\\ncreates the row). A student does *not* edit their own allergen list: it is a\\nsafety record the school keeps on their behalf, and a mistyped β€” or quietly\\nremoved β€” allergy would otherwise reach the kitchen with the school's\\nauthority behind it. Reading is `GET /meals/profiles/me`, or\\n`GET /meals/profiles/{user}` under the usual per-student gate (own id always,\\notherwise teacher+ or a parent link). A student who was never recorded reads\\nback as an *empty* profile rather than a `404` β€” \\"nothing known\\" is an answer.\\n\\nEvery dish a menu read returns therefore carries a **`conflicts`** list: the\\nintersection of that dish's `tags` with the **calling user's** profile tags.\\nIt is empty when the two do not overlap, and empty for every reader without a\\nprofile β€” a manager reading a menu sees `conflicts: []`, which is correct and\\nnot a bug (the field answers \\"may *I* eat this\\", and there is no \\"conflicts\\nfor student X\\" parameter). The caller's profile is loaded **once per request**,\\nnot per dish, so the menu list stays at its fixed query count no matter how\\nmany menus or dishes the page holds.\\n\\n**Money is minor units** (kuruş) as an integer, at every layer: `4550` is\\n45,50 β‚Ί. This API never speaks decimals or floats about money, so no rounding\\nis ever introduced by transport or by a client's JSON number parser.\\n\\nReads are open to every authenticated user β€” a student has to see what is\\nbeing served β€” and every write is manager+. Deleting a menu takes its dishes\\nwith it: a dish has no meaning apart from the menu it was published on.\\n\\n**Bookings** are seats on a published menu (`POST\\n/meals/menus/{id}/bookings`). One row per (menu, student), keyed by a\\ndeterministic composite id, so booking twice is the same seat and never a\\nsecond one. A **student books only for themselves**; a **parent books for a\\nstudent they hold a link to** β€” the one write a `parent_link` authorises, since\\npaying for lunch is a parent's job. Nobody else books through this route: a\\nteacher or manager ordering a child's lunch is a `403`.\\n\\n- **Cancelling is a status flip, not a delete** (`DELETE\\n /meals/bookings/{bid}` answers `200` with the flipped row): the row survives\\n as `cancelled` with a `cancelled_at` stamp, so a freed seat stays auditable\\n against the money it moved. Only `booked` rows count against `capacity`,\\n which is what genuinely frees the seat β€” and re-booking is the same row\\n flipped back. The call is **idempotent**: cancelling an already-cancelled\\n seat answers `200` with the row as it stands *and replays the refund*, so a\\n cancel cut short between the flip and the reversal (the tab closed, a proxy\\n timed out) is recovered by sending it again. Refusing it as a `409` β€” as it\\n once did β€” made that state permanent: no route could append the missing\\n reversal, and the student stayed billed for a seat they no longer held.\\n- **The capacity check is serialized in-process.** Counting rows and then\\n writing one is write-skew: SurrealDB does not conflict-check a cross-record\\n count against a concurrent insert, so 24 students racing for 3 seats would\\n otherwise all pass the count. The whole check-then-write runs under the same\\n lock a menu publish takes, and the cap is re-read inside it.\\n- **One cutoff closes both ends.** Within the school's\\n `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new\\n booking nor a cancellation lands (`409`) β€” the kitchen's headcount has to\\n settle at some point. `null` (the default) means no cutoff at all. The\\n cutoff is measured back from the menu's `date` **plus the slot's\\n `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served\\n at `720` closes at 10:00 UTC that morning, not at 22:00 the night before.\\n **That minute is UTC**: `date` carries no timezone and the backend stores no\\n school timezone β€” deliberately, it is a rejected feature β€” so a UTC+3 school\\n enters `540` (09:00 UTC) for a meal served at noon locally. A slot with no\\n `serving_minute` falls back to **midnight UTC starting the meal's day**, the\\n behaviour every booking had before the field existed; the booking is never\\n refused for want of a serving time.\\n- **The serving time is read live, not snapshotted onto the menu.** The cutoff\\n minutes are already read live, so freezing the other half of the same\\n deadline would make one policy edit apply and its twin not; a kitchen that\\n moves lunch an hour later wants today's menus to move with it. The menu\\n still snapshots the slot *name* (that is what keeps a retired slot's history\\n readable), so a menu whose slot has since left the list simply has no\\n serving time and falls back to midnight UTC.\\n- A menu somebody still holds a seat on **cannot be unpublished** (`409`) β€”\\n cancel the bookings first, so nothing is left pointing at a deleted meal.\\n\\n`GET /meals/bookings/me` is the caller's own list: the seats held *for* them\\nplus, for a parent, the seats held for every student they **currently** hold a\\nlink to β€” so a parent's list is their children's meals. The links are re-read\\non every call rather than trusted from the booking's `booked_by` stamp: an\\nunlinked parent stops seeing the child's seats at once, including the ones\\nthey booked and paid for themselves, exactly like every other parent read. `GET /meals/menus/{id}/bookings` is the kitchen's list for\\none menu (manager+), cancelled rows included so the changes are visible.\\n\\n### Meal attendance\\n\\nWhoever stands at the canteen door records who actually ate:\\n`POST /meals/menus/{id}/attendance` with `{student_id, status}`, teacher+ (a\\nstudent never marks, not even themselves). The status is the fixed pair\\n`served` / `missed` β€” deliberately **not** the school's editable\\n`attendance_statuses`, since a canteen line has no \\"late\\" or \\"excused\\", and one\\nlist meaning two things would let a school change one by editing the other.\\nOne row per (menu, student) keyed by a composite id, so a correction re-marks\\nthe same row instead of stacking a second one.\\n\\n**Attendance has zero billing effect.** Booking is the sole charge trigger, so\\na student who booked and did not eat still pays β€” the kitchen bought the food.\\nThere is no no-show penalty, no refund-on-missed, and no auto-reversal:\\nnothing under `meal_attendance` writes to the ledger. A walk-in with no live\\nbooking *can* be marked `served` (the record is operationally true) and is\\nlikewise not charged for it β€” charging there would be a ledger write. The\\ntarget only has to *exist*: a canteen also feeds staff, so any user may be\\nmarked, not only a student. A mark is a record of what happened, not a check\\nof who was entitled, and since it moves no money it costs nobody anything.\\n\\n`GET /meals/menus/{id}/attendance` is the per-menu list (teacher+), and\\n`GET /meals/attendance/{user}` is one student's history, narrowable with\\n`?from=&to=` β€” inclusive `YYYY-MM-DD` bounds compared against the *menu's*\\nday, a lexical compare that is chronological for that format. Same gate as the\\nbalance and the ledger: the caller's own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`meal_ledger`): one line per `charge`,\\n`credit`, or `reversal`, every field `READONLY`, and **no code path anywhere\\nthat updates or deletes one**. A ledger line that can be edited or dropped\\nsilently rewrites a student's financial history with no trace of the rewrite β€”\\nthis is the one genuinely irreversible part of the food program, so a mistake\\nis corrected by appending the opposing line, which leaves both the mistake and\\nthe correction visible.\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer.\\nA *negative* balance means the student owes the school; a positive one is\\nmoney on account. Amounts are stored positive; the sign lives in the `kind`.\\n\\n- **Booking is what charges, at a price snapshot.** The menu's dishes are\\n summed the moment the seat is taken and that number is frozen onto the\\n charge. Editing a dish's price afterwards moves no existing charge β€” what a\\n student owes is what the menu cost the day they booked. The price is\\n snapshotted *before* the seat is given, so a menu that cannot be charged\\n refuses the booking rather than leaving a booked-but-unbilled row (`400`,\\n when the dishes sum past 10 000 000). A free menu writes no line at all β€”\\n but the booking row records that it *was* free, so \\"free when taken\\" is\\n never confused with \\"not billed yet\\": pricing the menu afterwards leaves\\n every seat already taken on it free.\\n- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its\\n money move together under one in-process lock, and the ledger id is derived\\n from the seat plus how many times it has been taken β€” so eight simultaneous\\n `POST`s of one seat write one charge, a retried cancel refunds once, and a\\n write that failed halfway heals when the request is repeated. Booking the\\n same seat twice bills once because the *identity* is the same, never\\n because a scan happened to see the first charge in time.\\n- **Cancelling appends a `reversal`** for the charge's exact amount, with\\n `source` pointing at the charge it undoes. The charge row itself stays. A\\n cancel past the cutoff is already a `409`, so a reversal only ever follows a\\n legal cancel β€” and repeating a cancel replays the reversal, which is what\\n makes the refund recoverable rather than a one-shot the network can lose.\\n Re-booking afterwards is a **fresh** charge at the then-current price.\\n- **The price snapshot is taken under the booking lock**, and dish\\n create/edit/delete take that same lock. Taken outside it, a dish added\\n between the sum and the seat would be frozen onto the row as \\"the menu was\\n free then\\" β€” and nothing heals it, since a seat already held is returned\\n as-is, never re-priced.\\n- **A no-show still pays.** Meal attendance has zero billing effect β€” nothing\\n in the ledger reads or writes it. The seat was reserved and the food was\\n cooked; there is no no-show penalty and no no-show refund.\\n- **`POST /meals/credits` is admin-only**, not manager: writing down cash\\n received is the highest-trust action in the app. It appends a `credit` for a\\n student with a positive `amount_minor` (≀ 10 000 000), an optional `method`\\n (\\"cash\\", \\"havale\\", …) and `note`, and records the admin as `recorded_by`.\\n There is no payment gateway and no card data, ever. An over-credit is\\n corrected with a compensating line, never a fix-up.\\n\\n`GET /meals/balance/me` is the caller's own balance. `GET\\n/meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line\\nfirst) read a student's: your own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student. A charge's `source` is the\\nbooking id it came from, a reversal's is the charge line it reverses, and a\\ncredit has none.", "source": "README.md"}, {"id": "payments-fee-plans-assignment-the-fee-ledger", "title": "Payments: fee plans, assignment & the fee ledger", "body": "School fees live in their own tables (`fee_plan`, `fee_plan_assignment`,\\n`payment_ledger`) and their own balance. **Meal money is separate** β€” two\\nledgers, two balances, and no route folds one into the other: what a family\\nowes the canteen and what it owes the school are different debts, and mixing\\nthem would make either statement unreadable.\\n\\nEvery write here is **manager+**. Reads are narrower than the other\\nper-student reports: the student themselves, a parent holding a live link to\\nthem, or manager+ β€” **a teacher gets a `403` on every `/payments` route**,\\nbecause what a family owes the school is not classroom information.\\n\\n### Fee plans and what turns them into money\\n\\nA **fee plan** (`POST /payments/plans`) is a name and 1 to 60 **installments**,\\neach `{amount_minor, due_at}` β€” minor units (kuruş) as an integer, and unix\\nmilliseconds. `due_at` **may be in the past**: a school adopting the app\\nmid-year assigns plans whose first installments were already due, so there is\\nno future-date rule here.\\n\\nWriting a plan bills nobody. **Assigning it does** (`POST\\n/payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call):\\nthat appends *every* installment as a `charge` line right away, each carrying\\nits own due date. There is no scheduler, no nightly sweep, and nothing that\\nwakes up when a date passes β€” the whole schedule is written once, and lateness\\nis read off it.\\n\\nAssignment is **replay-safe by identity**: the assignment row is keyed\\n(plan, student) and every charge it raises is keyed (plan, student,\\ninstallment), so re-assigning bills nothing a second time (that student comes\\nback `already_assigned`), and an assignment cut short after three of twelve\\ncharges landed completes itself when the call is simply repeated. Only\\nstudents carry a fee record, so any other target comes back `rejected` β€” one\\nbad id never loses the rest of the batch.\\n\\nA plan that has been assigned to anyone can no longer be edited or deleted\\n(`409`). Its charges are frozen copies of the installments as they stood, so\\nan edit would only make the plan and the money tell different stories β€” write\\na new plan instead.\\n\\nThat freeze is a **counter on the plan row** (`assignment_count`), incremented\\nin the *same transaction* as the assignment row it counts, and the edit and the\\ndelete are single-record conditional writes against it β€” the same shape as a\\nterm's `course_count`. It used to be a `SELECT` taken before the write, which a\\nconcurrent assign could land behind, leaving a plan edited *and* assigned, or\\ndeleted with a live assignment naming it. Now the two contend on one record: an\\nassign either freezes the plan first (and the edit or delete is a `409`) or\\narrives after it (and bills the edited plan β€” the installments a first\\nassignment charges are re-read from the *stored* plan at the instant it\\nfreezes, never from the copy the request first looked at). A plan deleted out\\nfrom under a running batch is `rejected` for that student on, in the same\\nper-student report as every other outcome β€” the students it already billed are\\nnever dropped from the answer. A `PATCH`\\ncarrying no field at all writes nothing, so it is not refused.\\n\\nBecause an assignment is never removed, the counter is only ever claimed and\\nnever released: once assigned, a plan stays frozen for good. Plans written\\nbefore the counter existed are seeded from their assignment rows at boot,\\nbefore the server accepts a request β€” an absent counter reads as zero, and a\\nzero would have re-opened every already-assigned plan on an existing volume.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`payment_ledger`), exactly like the\\nmeal one: every field `READONLY`, and **no code path anywhere that updates or\\ndeletes a line**. A ledger line that can be edited or dropped silently\\nrewrites a family's financial history with no trace of the rewrite, so a\\nmistake is corrected by appending the **opposing line**, which leaves both the\\nmistake and the correction visible.\\n\\nFour kinds, and the sign lives in the `kind` β€” amounts are always stored\\npositive:\\n\\n| Kind | Sign | What it records | `source` points at |\\n| ---------- | ---- | ------------------------------------------------ | ------------------ |\\n| `charge` | βˆ’1 | An installment billed by a plan assignment | the assignment |\\n| `credit` | +1 | Money received, against one named charge | the charge paid |\\n| `reversal` | +1 | A `charge` or `refund` entered in error, undone | the undone line |\\n| `refund` | βˆ’1 | Money handed back, against one named payment | the credit returned |\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge) - SUM(refund)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer. A\\n*negative* balance means the family owes the school; a positive one is money on\\naccount.\\n\\n- **A payment names the charge it settles.** `POST /payments/credits` takes\\n `{charge_id, amount_minor, method?, note?}`: allocation is *recorded*, never\\n inferred from a balance, so a statement can say which installment is still\\n open rather than only how much is outstanding. **Partial payments are the\\n norm** β€” several credits accumulate against one charge.\\n- **A refund names the payment it returns.** `POST /payments/refunds` takes\\n `{credit_id, …}`, partials allowed, capped by what that credit was worth.\\n This is also the **only** way a mistaken credit is corrected: a credit is\\n never reversed, so money leaving the school is always spelled the one way.\\n- **A retry is not a second payment β€” when the client says so.** Both routes\\n take an optional `request_key` (`[A-Za-z0-9-]`, 1 to 64 characters β€” `_` is\\n the separator inside a ledger id, so a key may not carry one). With\\n one, the line is keyed `<charge>_k_<key>` (a refund: `<credit>_kr_<key>`), so\\n a client retrying after a network timeout gets **the line the first attempt\\n wrote**, not a second charge on the family β€” idempotence by identity, the\\n same rule that keeps a replayed assignment from billing twice, never a \\"has\\n this been recorded yet?\\" scan two concurrent requests can both walk past. The\\n replay is answered **before** the over-payment cap is consulted, so a payment\\n that filled its charge to the penny still replays as itself instead of coming\\n back \\"already paid in full\\". Sending that key again with a **different**\\n `amount_minor` or a different target is a `409`, never the stored line: that\\n is a client bug, and a `201` would bury it. Omit the key and nothing changes\\n from before β€” two identical posts are two payments, which is exactly what a\\n desk taking the same amount twice means.\\n- **A reversal only undoes a `charge` or a `refund`**, for its exact amount and\\n nothing else (`400` on any other kind). It is keyed `<line>_r`, so a line has\\n at most one reversal however often the call is retried, and the reversed line\\n itself stays on the record beside it.\\n- **A refund frees the charge's room.** The cap on a payment is folded over the\\n target's whole source subtree, so refunding a payment gives that charge its\\n room back and the charge **can be paid again** β€” and reversing that refund\\n takes the room back with it. Money that came back out is not money the school\\n still holds.\\n- **The over-payment cap is not the database's.** The `409` past a charge's or\\n a credit's worth is a cross-record fold, which SurrealDB cannot enforce on\\n its own; it holds because the backend is one process and the fold, and the\\n append it authorizes, are taken under one lock. Should an over-payment ever\\n be recorded anyway it is not a crisis: this is human data entry at an office\\n desk, the outcome is an over-paid charge that is plainly visible in the\\n statement, and it is undone by appending a refund. Both lines are true\\n records of money that really arrived β€” refusing them would be the worse lie.\\n- **There is no payment gateway and no card data, ever**, and none is planned:\\n nothing here talks to a bank, a PSP, or a card network. `method` is free text\\n (\\"cash\\", \\"havale\\", …) describing how money that already arrived was handed\\n over, and `note` is whatever the office needs to remember (a receipt number,\\n say).\\n\\n### Statements, balances and `overdue`\\n\\n`GET /payments/ledger/{user}` is the raw lines, newest first, paged.\\n`GET /payments/statement/me` and `/payments/statement/{user}` are the\\n**per-charge rollup** (its rows paged by the usual opt-in `?limit=&offset=`,\\nin an `entries: {items, total, limit, offset}` envelope): one row per charge with its plan, the installment's\\namount and due date, what it collected, what went back out, what is still\\noutstanding, whether the charge itself was reversed (such a charge owes\\nnothing), and whether it is **`overdue`** β€” still owed, and its `due_at` has\\npassed.\\n\\nAll of that is folded from the raw lines **on every request and stored\\nnowhere**, `overdue` included. Paging windows the *returned rows* only, after\\nthat fold: `balance_minor` β€” and every row's own arithmetic β€” is identical on\\nevery page, because it is read from all of the student's lines either way. There is no overdue flag, no sweep that sets\\none, and no stored rollup: a stored rollup is a second version of the truth,\\nand the ledger is the first. `GET /payments/balance/me` and\\n`/payments/balance/{user}` are the same fold reduced to one number.", "source": "README.md"}, {"id": "exam-modes-attempts-retakes-rejoin-live-monitoring", "title": "Exam modes, attempts, retakes, rejoin & live monitoring", "body": "Preparing an exam is slow work, so an exam can be created as a **draft**\\n(`draft: true`): only the course's managers see it (to students it's a `404`\\nthat might as well not exist β€” lists, direct reads, and attempts all hide\\nit), nobody can sit it, and grading it is a `409`. The teacher builds the\\nquestions in peace and publishes with `PATCH /exams/{id}` `{\\"draft\\": false}`.\\nAn exam can go back into hiding the same way β€” but only while it has **no\\nattempts and no results**; after that, re-drafting is a `409` (students never\\nlose sight of an exam they've sat or been graded on). Existing exams (and\\nthose created without the flag) are published from the start.\\n\\nSeparately from drafts, a published exam without a `mode` (all schedule\\nfields `null`) is **offline-graded** β€” a paper exam whose marks are entered\\nby hand; students see it and their marks, but attempts on it are a `409`\\n(\\"nothing to sit\\"). Making an exam sittable means giving it a `mode`, as one\\nconsistent unit (validated together on create and after every `PATCH` merge):\\n\\n- `mode: \\"sync\\"` + `starts_at` + `ends_at` β€” everyone sits inside one window;\\n every attempt's deadline is `ends_at`.\\n- `mode: \\"async\\"` + `starts_at` + `ends_at` + `duration_ms` β€” each student\\n starts anywhere inside the window and gets\\n `min(started_at + duration_ms, ends_at)` as their personal deadline.\\n- `mode: \\"open\\"` β€” no window at all: students sit anytime. `duration_ms` is\\n *optional* β€” set it for a per-attempt countdown (`started_at +\\n duration_ms`), omit it for unlimited time (the attempt only ends by\\n submission).\\n- `duration_ms` is 1 minute to 24 hours wherever it appears, and for `async`\\n cannot exceed the `starts_at`..`ends_at` window (equal to it is fine).\\n `ends_at` must be strictly after `starts_at`, and neither may be *set* in\\n the past β€” on create or `PATCH` (kept values are exempt, so a running exam\\n stays editable). All instants are the usual UTC unix-milliseconds, judged\\n only by the server clock (`GET /time` for sync).\\n\\nTwo per-exam policy knobs ride along, both **live-editable** at any point:\\n\\n- `max_attempts` (default `1`, `0` = unlimited) β€” how many sittings each\\n student gets. Raising it mid-exam grants retakes on the spot; lowering it\\n never kills a running attempt, it only blocks future starts.\\n- `allow_rejoin` (default `true`) β€” whether a student who *left the exam room*\\n may come back in and keep answering (see the exam-room section).\\n- `allow_review` (default `false`) β€” opt-in door to the student self-review\\n reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A\\n student may review only when this is on **and** the teacher has marked them\\n (an `ExamResult` row exists); own-scoped, so no student reads another's sheet.\\n\\nA student **sits** an exam through attempts (sitting 1, 2, … β€” each row id is\\nthe composite `exam_user[_seq]` key, so a sitting exists at most once by\\nconstruction):\\n\\n- `POST /exams/{id}/attempt` starts, resumes, or retakes (students only β€”\\n staff never sit; enrolled; window open where one exists β€” `open` exams start\\n anytime). While the latest\\n sitting runs, re-posting returns it unchanged (`200`, not `201`):\\n reconnecting never resets the clock. Once it is submitted or expired,\\n re-posting mints the next sitting (`201`) **from a blank answer sheet** β€”\\n the previous sitting's answers are wiped β€” until `max_attempts` is spent\\n (`409` after that). Starting is the live-attendance signal.\\n- `GET /exams/{id}/attempt` is the student's exam screen: the latest sitting's\\n `status` (`in_progress` | `submitted` | `expired`), `attempt` (its number),\\n `attempts_used`/`max_attempts`, `deadline`/`remaining_ms` (`null` for an\\n untimed open exam), `left_at`, own `mark` once graded, and the server `now`.\\n- `POST /exams/{id}/attempt/finish` submits. After the deadline the attempt is\\n `expired` β€” a valid terminal state (the student used their full time), and\\n finishing answers `409`. Grading stays per exam+user (one mark), whatever\\n the sitting count β€” the sheet a grader sees is always the latest sitting's.\\n\\nDeadlines are **recomputed from the exam's current schedule on every read**,\\nnever stored: a teacher who `PATCH`es `ends_at` (or a `duration_ms`)\\nwhile the exam runs moves every running deadline instantly. What's frozen once\\nanyone has started is only `mode` (including back to unscheduled) β€” swapping\\nthe deadline rules mid-sitting would be a different exam (`409`).\\n\\nThe course's manager (its creator, or manager+) watches it all live:\\n`GET /exams/{id}/live` returns one snapshot β€”\\nthe enrolled roster joined with attempts and marks (`not_started` | `absent` |\\n`in_progress` | `submitted` | `expired`, per-student `attempt` /\\n`attempts_used` / `left_at` / `deadline` / `remaining_ms` / `mark`, always the\\nlatest sitting) plus summary counts, all judged at a single `now`. Once the\\nwindow closes, `not_started` hardens into `absent` β€” the no-shows, flagged\\nright in the roster (open exams have no window, so never an `absent`). The\\nflag is informational: an absent student still has no mark until the teacher\\nrecords one through `POST /exams/{id}/results`. Poll `GET /exams/{id}/live` to\\nkeep a monitor current β€” attendance, ticking clocks, submissions, and marks all\\nride in each snapshot.\\n\\nDeleting an exam (or its course) cascades attempts, questions, answers, and\\nquestion + answer images (blobs included) along with results; unenrolling mid-exam\\nhides the student from the monitor roster but keeps the attempt and mark\\nrows, mirroring the marks report.\\n\\n> **Upgrading a pre-course database**: `exam` rows created before courses\\n> existed lack the now-required `course` field and will fail to deserialize.\\n> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data,\\n> backfill manually with the SurrealDB CLI (server stopped), e.g.\\n> `UPDATE exam SET course = course:<id> WHERE course = NONE;`\\n> after creating a course to attach them to.\\n>\\n> **Upgrading to the attempts/rejoin build needs nothing manual**: the boot\\n> migration backfills `max_attempts = 1`, `allow_rejoin = true`, and attempt\\n> `seq = 1` on existing rows, and swaps the single-attempt unique index for\\n> the per-sitting one. Pre-upgrade attempts keep their record ids and count\\n> as sitting #1.\\n>\\n> **Upgrading to the kind-weight build is a clean break**: weights moved off\\n> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with\\n> no data migration. A database from an older build has string kinds and a\\n> per-exam `weight` column the code no longer understands β€” delete\\n> `./data/hezarfen.db` and reboot.", "source": "README.md"}, {"id": "taking-an-exam-questions-answers-the-exam-room", "title": "Taking an exam: questions, answers & the exam room", "body": "Teachers author a question list per exam; students answer inside their\\nattempt, autosaved as they go; choice questions are machine-checked as a\\n**suggestion** β€” the final mark stays a human call through the existing\\n`POST /exams/{id}/results`.\\n\\n**Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`,\\ncourse-management rights): each has a mandatory `subject_id` (one of the\\ncourse's subjects, `GET /courses/{id}/subjects` β€” the topic the question\\nbelongs to), `text` (≀ 2000 chars), `points` `1`–`100`\\n(its share of the auto-score), and a `kind`:\\n\\n- `kind: \\"choice\\"` β€” carries `choices` (2–10 options, each ≀ 500 chars) and\\n `correct`, the zero-based index of the right option. Auto-scorable.\\n- `kind: \\"text\\"` β€” free text, judged by the grader; carries neither.\\n\\nThe kind bundle is validated as a unit (create and after every `PATCH` merge):\\nswitching a question to `text` needs explicit `\\"choices\\": null, \\"correct\\":\\nnull`, switching to `choice` must bring both along. Presentation order is\\ncreation order. The whole list **freezes once anyone has started an attempt**\\n(`409` on create/edit/delete) β€” editing questions under a sitting student\\nwould fork what \\"the exam\\" means. Deleting a question cascades its answers\\nand images.\\n\\n**Question images**: any question may carry one **illustration** (`POST\\n/exams/{id}/questions/{qid}/image` β€” the map the prompt asks about, on\\n`choice` and `text` questions alike), and each option of a `choice` question\\nmay carry a **picture** of its own (`POST .../choices/{choice_id}/image` β€” so\\nthe options themselves can be images: four map crops, pick the right one).\\nUploads are `multipart/form-data` with a single `file` part, capped by the\\nschool's `max_file_bytes`; the declared content type must be `image/png`,\\n`image/jpeg`, `image/webp`, or `image/gif` (rasters only β€” SVG can script,\\nand these bytes render inline for the whole class). One image per slot:\\nre-uploading replaces, `DELETE` on the same paths removes, and replacing a\\nquestion's `choices` list drops all its option pictures (the illustration\\nstays β€” re-upload against the new list). Image writes follow question\\nauthoring exactly: course-management rights, frozen once attempts exist.\\nBoth question views (`GET /exams/{id}/questions` and the sitting view)\\nembed the metadata as `image: {content_type, size} | null` and\\n`choice_images: [...|null]` aligned with `choices`; the bytes come from the\\n`GET` endpoints above β€” course managers anytime, students through the same\\nenrollment + started-attempt wall as the sitting view (no early peek at the\\npictures either), served with `Cache-Control: private, no-store`.\\n\\n**Answering** (student, attempt `in_progress`, deadline judged by the server\\nclock on every save):\\n\\n- `GET /exams/{id}/attempt/questions` β€” the sitting view. Requires\\n enrollment (`403` β€” the questions are course content, so leaving the course\\n closes them) and an attempt (`404` before `POST /exams/{id}/attempt`; also\\n the anti-peek gate), never contains `correct`, and embeds the caller's own\\n saved answer per question (`{selected, text, updated_at}` or `null`). Still\\n readable after submitting/expiry, for review.\\n- `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` β€” an\\n upsert: one row per question+user, re-answering overwrites. The payload must\\n match the question's kind (`selected` indexing a choice, or `text`\\n ≀ 10 000 chars β€” empty clears the draft); mismatches are `400`s. Requires\\n the student role and enrollment (`403`): a promotion out of `student` or an\\n unenrollment mid-exam closes the sheet (the exam room's door checks,\\n re-applied to every save β€” finishing stays open). Once the\\n attempt is submitted or past its deadline every save is a `409` β€” likewise\\n while the student has left the exam room with `allow_rejoin` off; answers\\n saved in time survive untouched for grading. Each sitting keeps its own\\n answers, drawings, and mark, keyed by the attempt's `seq` β€” a retake starts\\n from a blank sheet without erasing the prior one, so the full per-attempt\\n history stays readable (see the grading view).\\n\\n**Answer images**: the student side mirrors the teacher's question images. A\\nstudent may attach one **drawing** to any question in their attempt β€” a\\nsketched answer or worked steps β€” via `POST\\n/exams/{id}/attempt/answers/{qid}/image` (`multipart/form-data`, one `file`\\npart, the same raster allowlist and `max_file_bytes` cap as question images).\\nOne image per question: re-uploading replaces, `DELETE` on the same path\\nremoves. Writes ride the exact `POST /exams/{id}/attempt/answers` gate β€” the\\nstudent role, enrollment, an `in_progress` attempt, and the rejoin door β€” so a\\ndrawing is just another autosaved answer; a drawing-only answer (nothing\\ntyped) still surfaces, and clearing it grooms the empty row away. The bytes\\ncome from `GET` on the same path (the caller's own, behind the sitting-view\\nwall) and, for the grader, `GET /exams/{id}/attempts/{user}/answers/{qid}/image`\\n(course-management rights); both serve inline with `Cache-Control: private,\\nno-store`. The metadata rides the answer as `answer_image: {content_type,\\nsize} | null` on both the sitting view and the grading sheet. To the backend\\nit is a normal raster PNG; the frontend piggybacks its editable stroke data in\\na PNG `tEXt` chunk, opaque here β€” stored on disk under `Config::files_path`\\nby a ULID, metadata in the `answer_image` table, structurally identical to\\nquestion images.\\n\\n**Grading view** (course-management rights): `GET /exams/{id}/attempts/{user}/answers` returns\\nthe student's **latest** sitting's sheet β€” every saved answer with `is_correct`\\n(`true`/`false` for choice, `null` for text: that's the grader's call) plus\\n`auto_score: {earned, possible}` summing the choice questions' points. It is a\\nsuggestion to read while grading, never written anywhere.\\n\\n**Per-attempt history** (course-management rights): prior sittings stay\\nreadable. `GET /exams/{id}/students/{user}/attempts` lists the sitting numbers\\na student has (every `seq` carrying answers or a mark, ascending);\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers` is the grading sheet\\nfor one of them (drawing bytes at\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image`); and\\n`GET /exams/{id}/students/{user}/marks` is the full per-sitting mark history,\\noldest first. Grading (`POST /exams/{id}/results`) always lands on the current\\nsitting, and the latest seq is the grade-of-record β€” the roster, report, and\\nstatistics reads all show it. Every result payload carries its `seq`, so a mark\\nlinks straight to that sitting's answer sheet β€” without it a marked retake's\\nanswers would be unreachable from the mark.\\n\\n**The exam room (WebSocket)** β€” `GET /exams/{id}/attempt/ws`, cookie-authed\\nlike everything else; REST above remains the full fallback. Gates run before\\nthe upgrade: unknown or draft exam `404`, unscheduled (no mode) `409`, not a\\nstudent `403`, not enrolled `403`, no attempt yet `404` (start it first),\\nsubmitted/expired `409`, left while rejoin is closed `409`. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| server β†’ | `{\\"type\\":\\"state\\", status, attempt, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save |\\n| client β†’ | `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"selected\\":1}` or `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"text\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` |\\n| server β†’ | `{\\"type\\":\\"saved\\", question_id, updated_at, client_seq?}` β€” the autosave ack |\\n| client β†’ | `{\\"type\\":\\"finish\\"}` β€” submit the attempt |\\n| server β†’ | `{\\"type\\":\\"finished\\", finished_at}`, then Close |\\n| server β†’ | `{\\"type\\":\\"expired\\"}`, then Close β€” a tick noticed the deadline |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", message, question_id?, client_seq?}` β€” bad JSON, wrong kind, deadline, … |\\n\\nAn `answer` may carry a `client_seq`: any number the client picks, echoed verbatim on\\nthat message's `saved` or `error` and on nothing else. The server never reads\\nit β€” no uniqueness, no ordering, no dedupe, all the client's business β€” and\\nomits the key entirely when the request omitted it, so leaving it out keeps\\ntoday's frames byte for byte. It exists because `question_id` is not an\\nidentity: save a question, time out, save it again, and two sends are\\noutstanding for the same id β€” the first reply would settle the second and the\\nUI would claim \\"Saved\\" for an answer the server never took. `question_id` on\\nan `error` is the separate, orthogonal question: whether the failure belongs\\nto that one question (payload or question) or to the room, in which case every\\nsave in flight is equally refused. An error can carry `client_seq` without\\n`question_id`.\\n\\nEvery tick and every save re-read the exam, so a mid-exam `ends_at` extension\\nmoves the room's countdown on the next tick, and no stale socket can write\\npast its real deadline β€” the socket shares the exact REST write path. Each\\nroom acts only on the sitting it was opened for: once that sitting is over,\\nits `answer`/`finish` are `error` frames, so a lingering socket can never\\nscribble on (or instantly submit) a retake started elsewhere.\\n\\nThe room is also the presence signal behind the **rejoin door**: connecting\\nclears the attempt's `left_at`, and the *last* socket of the sitting to close\\nwhile it is still running stamps it (visible on the live monitor β€” \\"left the\\nroom three minutes ago\\" at a glance). Closing one of two tabs is not leaving,\\nand a lingering socket from an already-finished sitting never marks a later\\nretake as left β€” each room is bound to the sitting it was opened for. With the exam's `allow_rejoin` off, a stamped\\n`left_at` refuses re-entry *and* any further saves, over the socket or REST,\\nuntil the teacher flips the door back open (`PATCH /exams/{id}\\n{\\"allow_rejoin\\": true}` β€” live, like the times). Finishing stays allowed: a\\nlocked-out student can always submit what they saved. The timer never pauses\\neither way. Students who only ever use REST never trip the door β€” the room is\\nwhat marks leaving.\\nExample client:\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/exams/${id}/attempt/ws`);\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"state\\") renderCountdown(m.remaining_ms, m.answered, m.question_count);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.question_id);\\n};\\nlet clientSeq = 0;\\nconst save = (question_id, selected) =>\\n ws.send(JSON.stringify({ type: \\"answer\\", question_id, selected, client_seq: ++clientSeq }));\\n```\\n\\nThe live monitor rides along: each roster row now carries `answered` and\\n`last_activity` (latest save instant), and the snapshot a top-level\\n`question_count`, so \\"stuck at 3/10 for five minutes\\" is visible at a glance.\\nThe student's own `GET /exams/{id}/attempt` echoes the same\\n`answered`/`question_count` pair.", "source": "README.md"}, {"id": "question-bank", "title": "Question bank", "body": "Writing good questions is slow, and the same one gets asked year after year, so\\nthe school keeps a reusable **question bank**. A bank question is an\\n`ExamQuestion` cut loose from any exam: it has the same shape (`subject_id`,\\n`text`, `kind`, `points`, and β€” for a `choice` β€” `choices` + `correct`), the\\nsame image slots (one illustration, plus a picture per option), and the same\\nnewtype validation, but it carries **no exam link**. Because nothing sits it,\\na bank row **never freezes** β€” its owner can edit or delete it forever.\\n\\n`POST /bank-questions` (teacher+) saves one, stamping the caller as its\\n**owner**. `subject_id` is origin metadata, but it must **exist** β€” an unknown\\nsubject is a `400` (create and PATCH alike). The reverse guard does **not**\\nhold here, unlike exam questions and homework: a template never blocks a\\nsubject delete, which simply clears `subject` off every template that carried\\nit (only a template's owner may re-tag it, so a `409` would be one a manager\\ncould never clear β€” and a private template raising it would leak its\\nexistence). Reads are school-wide: `GET /bank-questions` lists the\\nwhole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` β€” or\\n`?owner=me` β€” by owner) and `GET /bank-questions/{bid}` fetches one with\\n`correct` included β€” any teacher+ can browse and reuse what any colleague\\nbanked. Each response carries its **image metadata** β€” an `image` meta for the\\nillustration and a `choice_images` array aligned with `choices` (per-slot\\n`{content_type, size}`, `null` where a slot has no picture) β€” the same shape an\\nexam question's response uses; the bytes still come from the image endpoints.\\nMutation is **owner-only** (an `admin` bypasses): `PATCH /bank-questions/{bid}`\\nrevalidates the kind bundle as a unit, `DELETE /bank-questions/{bid}` drops the\\nrow and its image blobs. The illustration and option pictures work exactly like\\nan exam question's β€” `POST|GET|DELETE /bank-questions/{bid}/image` and\\n`…/choices/{choice_id}/image`, `multipart/form-data` with one `file` part, raster\\nonly (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` β€” reads school-wide,\\nwrites owner-only.\\n\\nThe bank feeds exams by **copying**, never linking. `POST\\n/exams/{id}/questions/from-bank/{bid}` instantiates a bank question into the\\nexam: it mints a **fresh** exam-scoped question (new id, its own answer rows,\\nits image blobs copied to new files), so later edits on either side never\\ntouch the other. The subject on the bank row is origin metadata only β€” the\\ncall takes its own `{subject_id}`, re-checked against the target course's\\nsubjects (`400` on a cross-course subject), and instantiating into an exam\\nthat already has attempts is a `409`, the same freeze that guards hand-authored\\nquestions. The instantiated question records the template it came from in\\n`source_bank`. The reverse, `POST /exams/{id}/questions/{qid}/to-bank`, copies\\nan existing exam question **into** the bank (new detached row, images copied to\\nnew files, owner = caller); the source question is left untouched, and the new\\ntemplate records the origin exam in `source_exam`. Both provenance fields are\\nnullable β€” a hand-authored question or template carries `null` β€” and one-way\\nmetadata (the copies stay fully detached). All bank routes are course-agnostic\\nand require teacher+.\\n\\nCopying means a template edit never reaches the copies, so there is one escape\\nhatch for that divergence: `POST /exams/{id}/questions/{qid}/refresh-from-bank`\\nre-copies the template's *current* content over one exam question β€” text,\\npoints, kind, choices (adopting the **template's** choice ids, so the option\\npictures re-land on the right options), `correct`, the illustration and the\\noption pictures. The question keeps its own id, its exam, its `subject` (the\\ntemplate's is unrelated origin metadata) and its provenance links; anything\\nedited on the copy is overwritten, deliberately. A question with no\\n`source_bank` β€” hand-authored, or its template deleted β€” is a `400`, a template\\nthe caller may not see is a `404` (never a 403), and the usual freeze applies:\\nonce any attempt exists, `409`. Every source blob is read before anything is\\nwritten, so a missing blob is a `500` with the question untouched rather than a\\nhalf-applied refresh.", "source": "README.md"}, {"id": "homework", "title": "Homework", "body": "A course hands out **homework**: `POST /courses/{id}/homework` with a title,\\nan optional description, a **required subject** (one of the course's own β€” and\\nthe same delete guard questions have: a subject with homework refuses deletion\\nwith a `409` until the homework is re-tagged via `PATCH /homework/{id}` or\\ndeleted), and a **required `due_at`** that must not lie in the past (same 60s\\ngrace as every schedule field; late *submissions* are fine β€” a late\\n*assignment* is not).\\n\\n**Audience.** By default the whole course, resolved live: whoever is enrolled\\n*when they act* β€” a student enrolled after the assignment sees and submits it\\nlike everyone else. `assigned` (at create or PATCH) instead pins a named\\nsubset of currently enrolled students (at most 200). The unnamed must not even\\nlearn a subset exists: lists omit it, and direct reads and submits answer\\n`404` β€” the same no-leak a hidden exam draft gets. Narrowing the subset later\\nis refused with a `409` that names the blockers while any submission or grade\\nbelongs to a student the new list would strand.\\n\\n**Submitting.** Students only β€” staff and parents never submit β€” enrolled and\\nin the audience, re-checked on every write. A submission is optional text plus\\nup to **10 files of any content type** (each ≀ the school's\\n`max_file_bytes`): text is replaced whole on each `POST` (omit to clear),\\nfiles are added and removed one by one, and a file upload with no prior\\nsubmission auto-creates an empty one, so a photo-only homework is a single\\nrequest. Two stamps tell the lateness story: `submitted_at` pins the **first**\\nhand-in forever, `updated_at` moves on every text edit and file add/remove,\\nand `late` is **computed on read** (`updated_at > due_at`), never stored β€” so\\ntouching work after the deadline flips it late, and a `due_at` edit re-grades\\nlateness for free. Late submissions are always accepted, only flagged. File\\nbytes always come back as a forced download (`Content-Disposition:\\nattachment`): homework accepts any content type, so rendering an uploaded\\nHTML/SVG inline would run it in the viewer's session.\\n\\n**Grading.** A course manager records a status β€” `done`, `incomplete`, or\\n`missing` β€” plus an optional 0–100 `mark` per student\\n(`POST /homework/{id}/results`, one upsert row per homework+student; the\\nexam walls apply: live students only, enrolled, in the audience, never the\\ngrader themselves). A stored grade **freezes** that submission β€” text edits,\\nfile changes, withdrawal all `409` β€” until\\n`DELETE /homework/{id}/results/{user}` removes it and reopens editing.\\nGrading before the due date, or before anything was submitted, is allowed β€”\\nthe latter is how never-handed-in work gets its `missing` verdict, and\\n`GET /homework/{id}/result` is where its student reads it (their submission\\nendpoints have nothing to show). The teacher-set `missing` **status** is a\\ndeliberate verdict; the roster and the report *also* compute a `missing`\\n**flag** for anyone unsubmitted past due β€” the two are independent. Homework\\nmarks stay out of `/marks`: the weighted course average remains exam-only\\n(the exam *kind* named `homework` still lives there), so nothing\\ndouble-counts.\\n\\n**Roster & report.** `GET /homework/{id}/submissions` (course manager) is the\\ngrading table: one row per audience student β€” plus any straggler outside the\\naudience who still owns a submission or grade (an unenrollment, a promotion,\\nor an audience change leaves work behind; it stays visible, flagged\\n`unenrolled`, though a stale student can neither submit nor be graded).\\n`GET /homework/report/{user}` is the fourth observer read beside marks,\\nattendance, and pomodoro: teacher+ (an exactly-teacher caller narrowed to the\\ncourses they manage), or a **parent linked** to the student β€” per-homework\\nrows of submitted/late/missing plus the grade; statuses and marks only,\\n**never the files**.\\n\\nEvery delete collects its garbage: withdrawing a submission, deleting a\\nhomework, and deleting the whole course each cascade the rows (submissions,\\nfiles, grades) and unlink the file blobs from disk. Role changes never sweep\\nhomework rows: a promoted student's work stays readable on the roster behind\\nthe `unenrolled` flag, while the live-role gates refuse fresh edits and\\ngrades.", "source": "README.md"}, {"id": "lesson-sessions-roll-call-the-work-log-pomodoro-attendance-reports", "title": "Lesson sessions, roll call, the work log, pomodoro & attendance reports", "body": "Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session\\nbelongs to a course and carries a `teacher` (defaults to whoever creates it;\\nany explicit `teacher_id` must hold teacher+ β€” a student cannot teach), an\\noptional `topic`, a required `starts_at`, and an optional `ends_at` (when both\\nare set, `ends_at` must not precede `starts_at`; neither may be set in the\\npast). Sessions are created, edited,\\nand deleted under course-management rights, exactly like exams; session lists\\nare ordered by `starts_at` (a timetable, not a creation log).\\n\\n**Roll call** (`/sessions/{id}/attendance`) deliberately differs from event\\nattendance: students never mark themselves. The session's teacher or a course\\nmanager marks **enrolled** students β€” only students attend classes, so a\\nnon-student or unenrolled target is a `400` β€” and the\\n**session teacher's own** presence row can only be written or removed by\\nmanager+ β€” staff presence is management's call, so a teacher can't declare\\nthemselves present. Listing the roll call follows the same rights as taking\\nit; a student reads their own tallies through the attendance report instead.\\nRe-marking overwrites: one row per session+user, by construction. Deleting a\\nsession (or its course) cascades its roll-call rows.\\n\\nThe **work log** (`/work`) is the staff timesheet, for teachers and above.\\n`POST /work/check-in` opens a stint and `POST /work/check-out` closes it, both\\nstamped by the **server clock** β€” a request never carries an instant, so a\\nwrong device clock (or a crafted request) can't forge presence. At most one\\nopen stint per user holds atomically: double check-ins and check-outs without\\nan open stint answer `409`, and a reconnecting double-click can't reset a\\nrunning clock. `GET /work/me` lists your stints newest-first (the open one has\\n`check_out: null`, closed ones a convenience `duration_ms`); manager+ reads\\nanyone's log (`GET /work/{user}`), corrects a **closed** stint's instants\\n(`PATCH /work/entries/{id}`, `409` while open β€” check out or delete instead),\\nand deletes entries.\\n\\nThe **pomodoro log** (`/pomodoro`) is the students' study-time twin of the\\nwork log. The frontend owns the timer β€” the visible countdown, the work/break\\nrhythm, the durations; the backend stores no timing policy and records only\\n**focus stints**, stamped by the server clock exactly like work stints.\\n`POST /pomodoro/start` opens a session and β€” unlike a work check-in β€” always\\nsucceeds for a student: a dangling unfinished session (a laptop closed\\nmid-timer) is **discarded and replaced**, because it recorded no focus and\\nmust not lock the student out of the next one. `POST /pomodoro/finish` closes\\nthe running session (`409` when nothing runs); breaks are never reported.\\nLogs return the usual page envelope plus `total_focus_ms`, the unpaged sum of\\nevery finished session's duration: `GET /pomodoro/me` for your own,\\n`GET /pomodoro/{user}` for teacher+ (study oversight). Only students start\\nsessions β€” pomodoro is the study tool, the work log is the staff timesheet.\\n\\n**Attendance reports** mirror the marks report: `GET /attendance/me` for any\\nlogged-in user, `GET /attendance/{user}` for teacher+ β€” narrowed to the\\ncourses the caller manages (manager+ sees every course; event tallies are\\nschool-wide either way). The report tallies event attendance and lesson roll\\ncall separately, plus a per-course breakdown:\\n\\n```json\\n{\\n \\"user\\": \\"01J…\\",\\n \\"events\\": { \\"present\\": 4, \\"absent\\": 1, \\"late\\": 0, \\"excused\\": 1, \\"total\\": 6, \\"rate\\": 0.8 },\\n \\"sessions\\": { \\"present\\": 9, \\"absent\\": 2, \\"late\\": 1, \\"excused\\": 0, \\"total\\": 12, \\"rate\\": 0.8333 },\\n \\"courses\\": [ { \\"course\\": { \\"id\\": \\"01J…\\", \\"title\\": \\"algebra\\", … }, \\"counts\\": { … } } ]\\n}\\n```\\n\\n`rate = (present + late) / (present + absent + late)`: arriving late still\\ncounts as attending, and an excused absence counts against no one (`rate` is\\n`null` when every row is excused, or there are none). Per-course blocks appear\\nfor every course the user has roll-call rows in β€” attendance is a historical\\nrecord, so unenrolling hides marks from the marks report but never hides an\\nabsence.", "source": "README.md"}, {"id": "quick-tour-curl", "title": "Quick tour (curl)", "body": "```sh\\nBASE=http://127.0.0.1:8080\\nJAR=/tmp/hz.cookies\\n\\ncurl -s $BASE/auth/register -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\ncurl -s -c $JAR $BASE/auth/login -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\n# notes\\ncurl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"first\\",\\"content\\":\\"hello\\"}'\\ncurl -s -b $JAR $BASE/notes\\n\\n# note files (multipart; -F sets filename + content type from the file)\\nNO=$(curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"with file\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nFI=$(curl -s -b $JAR $BASE/notes/$NO/files -F 'file=@plan.pdf' \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/notes/$NO/files # list metadata\\ncurl -s -b $JAR -OJ $BASE/notes/$NO/files/$FI # download, original filename\\n\\n# events + attendance\\n# Creating events needs teacher+; grant it first (see \\"Bootstrapping\\" above β€”\\n# e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403.\\nEV=$(curl -s -b $JAR $BASE/events -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"standup\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json' \\\\\\n -d '{\\"status\\":\\"present\\"}'\\ncurl -s -b $JAR $BASE/events/$EV/attendance\\n\\n# courses + weighted marks (as a teacher)\\n# optional, manager+: weigh midterms triple β€” school policy, per kind\\ncurl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \\\\\\n -d '{\\"exam_kinds\\":[{\\"name\\":\\"midterm\\",\\"weight\\":3},{\\"name\\":\\"quiz\\",\\"weight\\":1}]}'\\n# find the student to enroll (here: a registered user \\"veli\\"): fragment\\n# search over username/name, role-narrowed (teacher+)\\nSID=$(curl -s -b $JAR \\"$BASE/users/search?q=vel&role=student\\" \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nCO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"algebra\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\nEX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"midterm\\",\\"kind\\":\\"midterm\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"mark\\\\\\":90,\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\ncurl -s -b $JAR $BASE/exams/$EX/statistics\\n\\n# lesson sessions + roll call (course manager creates; the session's teacher\\n# or a course manager marks enrolled students)\\nSE=$(curl -s -b $JAR $BASE/courses/$CO/sessions -H 'content-type: application/json' \\\\\\n -d '{\\"topic\\":\\"limits\\",\\"starts_at\\":1900000000000}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/sessions/$SE/attendance -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"status\\\\\\":\\\\\\"present\\\\\\",\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\n\\n# staff work log (instants are server-stamped)\\ncurl -s -b $JAR -X POST $BASE/work/check-in\\ncurl -s -b $JAR -X POST $BASE/work/check-out\\ncurl -s -b $JAR $BASE/work/me\\n\\n# ...and as the student:\\ncurl -s -b $STUDENT_JAR $BASE/marks/me\\ncurl -s -b $STUDENT_JAR $BASE/attendance/me\\n# pomodoro: start when the timer starts, finish when it rings\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/finish\\ncurl -s -b $STUDENT_JAR $BASE/pomodoro/me\\n```", "source": "README.md"}, {"id": "ai-bridge-quic", "title": "AI bridge (QUIC)", "body": "The AI features are separate projects β€” separate repos, separate processes,\\nprobably not Rust. They talk to this backend over a QUIC bridge rather than\\nHTTP.\\n\\nWhy QUIC: stream multiplexing lives in the transport. Each request rides its\\nown **bidirectional stream** on the service's single long-lived connection, so\\nconcurrent requests need no correlation-id bookkeeping and never head-of-line\\nblock each other β€” a 30-second inference on one stream does not delay the\\nanswer on another. Connection setup (and the TLS handshake) happens once, not\\nper request.\\n\\n**The backend listens; the services dial in.** A service can therefore sit\\nbehind NAT, restart without the backend knowing its address, and scale out by\\nopening a second connection β€” each connection is an independent worker.\\n\\nOff by default: with `AI_QUIC_ADDR` unset the bridge never starts and the rest\\nof the API is unaffected.\\n\\n### Handshake\\n\\nThe service connects with ALPN `hab/1`, then opens the **control stream** (the\\nfirst client-initiated bidi stream) and writes one `Hello`:\\n\\n```json\\n{ \\"protocol\\": \\"hab/1\\", \\"service\\": \\"ocr\\", \\"capabilities\\": [\\"ocr.extract\\"],\\n \\"token\\": \\"<AI_SHARED_TOKEN>\\", \\"max_concurrent\\": 8 }\\n```\\n\\nThe backend answers one `Greeting` and leaves the stream open:\\n\\n```json\\n{ \\"type\\": \\"welcome\\", \\"worker_id\\": \\"01J...\\", \\"protocol\\": \\"hab/1\\" }\\n{ \\"type\\": \\"rejected\\", \\"code\\": \\"unauthorized\\", \\"message\\": \\"invalid token\\" }\\n```\\n\\nReject codes: `unsupported_protocol`, `unauthorized`, `no_capabilities`,\\n`malformed`. The token is compared in constant time; the handshake must\\ncomplete within 10s.\\n\\nThe control stream carries no further frames. **Its closure is the goodbye** β€”\\nthere is no heartbeat. A service that dies silently is dropped by the QUIC idle\\ntimeout (30s, with a 10s keepalive) and deregistered then.\\n\\n`max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests\\nbeyond it are refused with \\"busy\\" rather than queued.\\n\\n### Requests\\n\\nFor each request the **backend** opens a bidi stream, writes one `Request`,\\nfinishes its send side, and reads one `Response`:\\n\\n```json\\n{ \\"id\\": \\"01J...\\", \\"capability\\": \\"ocr.extract\\", \\"deadline_ms\\": 30000,\\n \\"payload\\": { \\"image\\": \\"<base64>\\" } }\\n```\\n\\n```json\\n{ \\"status\\": \\"ok\\", \\"id\\": \\"01J...\\", \\"payload\\": { \\"text\\": \\"...\\" } }\\n{ \\"status\\": \\"err\\", \\"id\\": \\"01J...\\", \\"code\\": \\"unsupported_image\\",\\n \\"message\\": \\"only png and jpeg\\" }\\n```\\n\\n`id` is a trace id for logs on both sides β€” correlation is the stream, not the\\nid. It must still be echoed: an answer carrying a different id means the\\nservice lost track of whose work it is, and the payload is refused. `payload`\\nis opaque to the transport; its shape belongs to the capability.\\n\\n`deadline_ms` is when the backend gives up. A service should abandon the work\\nrather than answer late. A handled failure is an `err` frame; a crash is just a\\ndropped stream.\\n\\n### Framing\\n\\n`u32` big-endian byte length, then that many bytes of JSON. One frame per\\nmessage. The length is validated against the 8 MiB cap **before** any buffer is\\nallocated. JSON rather than a binary codec so a service in any language can\\nspeak it in ~20 lines.\\n\\n### Routing\\n\\nRequests route by exact capability string to the **least-loaded** worker\\noffering it (ties broken by worker id). Least-inflight rather than\\nround-robin because AI request costs are wildly uneven β€” round-robin would\\npile a second long inference onto a busy worker while an idle one sits next\\nto it. Selection and the in-flight increment happen under one lock, so\\nconcurrent dispatches cannot overshoot `max_concurrent`.\\n\\nFailure modes the caller sees: `NoWorker` (nothing registered β€” retryable),\\n`Busy` (all at capacity β€” retryable), `Timeout` (may still be running on the\\nfar side, so it promises nothing), `Remote` (the service's considered no β€”\\nnot retryable), `Protocol` / `IdMismatch` (broken peer), `Transport`.\\n\\n### Conformance suite\\n\\n`tests/ai_protocol.rs` is the wire contract, enforced on every `cargo test`. It\\nspeaks `hab/1` with a client that imports none of the crate's protocol types β€”\\nframes built as byte literals, answers parsed as untyped JSON β€” so it fails on\\nexactly the changes a service in another language would notice: a renamed\\nfield, a re-tagged enum, a flipped length-prefix endianness, a newly-required\\n`Hello` field. (`tests/ai_bridge.rs` drives real QUIC clients too, but shares\\nthe Rust structs with the backend, so it cannot see those.)\\n\\nIt is also the reference implementation: its `raw` module is the whole client\\nside of the protocol in about a hundred lines β€” handshake, framing, request\\nloop β€” and is the shortest thing to port when writing a new service.\\n\\nGuarantees it pins beyond the frame shapes: unknown fields in `Hello` and in a\\nresponse are accepted (a newer service may run against an older backend);\\npayloads pass through byte-for-byte whatever their JSON shape; request ids are\\nunique; answers may come back in any order; a service that drops one request\\nstream fails only that request; a service that ignores `deadline_ms` finds its\\nstream torn down rather than delivering a late answer.\\n\\n### TLS, auth & finding the certificate\\n\\nQUIC has no plaintext mode. With `AI_TLS_CERT`/`AI_TLS_KEY` unset, a\\nself-signed certificate is generated at boot and its sha256 fingerprint logged\\nβ€” services pin that instead of installing a CA. The certificate authenticates\\n*the backend*; the shared token in `Hello` authenticates *the service*.\\n\\nSo a service does not have to be handed a file out of band, the certificate is\\npublished over HTTP:\\n\\n```\\nGET /ai/certificate # no auth; 404 when the bridge is disabled\\n{ \\"protocol\\": \\"hab/1\\",\\n \\"certificate_pem\\": \\"-----BEGIN CERTIFICATE-----\\\\n...\\",\\n \\"fingerprint_sha256\\": \\"6745e8...\\" }\\n```\\n\\nUnauthenticated on purpose: a server certificate is handed to every peer during\\nthe TLS handshake anyway, so publishing it discloses nothing. The private key\\nnever leaves the process, and the shared token β€” the thing that actually\\nauthenticates a service β€” is *not* served here.\\n\\n**A service must re-fetch this on every reconnect, not once at startup.** With\\nno PEM pair configured the bridge re-selfsigns at each boot, so a certificate\\npinned once goes stale the moment the backend restarts; a reconnect loop that\\nonly redials would then fail forever. The service startup sequence is: `GET\\n/ai/certificate` β†’ trust that PEM β†’ dial QUIC β†’ `Hello` β†’ serve; on any\\nconnection loss, start again from the fetch.\\n\\nNote what this is not: fetch-then-pin over plain HTTP is trust-on-first-use,\\nonly as trustworthy as that HTTP hop. On an untrusted network set\\n`AI_TLS_CERT`/`AI_TLS_KEY` to a real certificate and distribute it out of band\\nβ€” the endpoint then simply serves that, stable across restarts.", "source": "README.md"}, {"id": "chatbot", "title": "Chatbot", "body": "Every signed-in user β€” `parent` included β€” keeps private threads with an\\nAI service. The backend is a **relay**: it owns auth, the limits, the thread,\\nthe payload format, and the last look at the answer before anyone sees it; the\\nwords are the service's. There are deliberately **no rule, intent or\\ncanned-answer tables** β€” the thread is free-form, and a school that wants\\ndifferent behaviour changes its AI service, not this backend. A thread is\\nprivate to its owner: no teacher, no admin, nobody reads someone else's, and\\nanother user's thread is a `404`, never a `403`.\\n\\n### Sending is two-phase, and that is the point\\n\\n`POST /chatbot/threads/{id}/messages` answers `202 {message_id, status:\\n\\"pending\\"}` instead of the answer, because an inference outlives a normal\\nrequest (and the request-timeout layer that guards every handler). Before the\\nAI is even called, two rows are written: the user's turn, and an **empty\\n`pending` assistant row** β€” `message_id` is that row. That order is the whole\\ndesign: a reload, a dropped connection, a closed laptop can no longer lose an\\nanswer, because the place it will land already exists and the answering task\\noutlives the HTTP request.\\n\\nThe client then reads that row either way it likes:\\n\\n- **poll** `GET /chatbot/threads/{id}/messages/{mid}` β€” `pending` until it\\n settles, then `complete` with `content` or `failed` with `error_code`;\\n- **stream** `GET /chatbot/threads/{id}/messages/{mid}/stream` β€” the same\\n row over Server-Sent Events.\\n\\nBoth read the same row, so they can never disagree, in any state.\\n\\n### The SSE stream\\n\\n```\\nevent: delta\\ndata: {\\"text\\":\\"Newton'un ikinci yasasΔ± \\"}\\n\\nevent: delta\\ndata: {\\"text\\":\\"kuvvet ile ivme arasΔ±ndaki …\\"}\\n\\nevent: done\\ndata: {\\"message\\":{ …the message DTO… }}\\n```\\n\\nOne to eight `delta` events, then exactly one `done` carrying the finished\\nmessage; or, if the turn failed, a single `error` event\\n(`{\\"code\\":\\"timed_out\\",\\"message\\":\\"…\\"}`) and nothing else. Then the stream\\ncloses. A stream opened *after* the answer already landed still emits\\n`delta`s and a `done` β€” the replay is deliberate, so a client that connects\\nlate (or reconnects) never hangs waiting for events that already happened.\\n\\n**The deltas are sliced by the backend from the finished answer.** `hab/1` is\\nunary β€” the service returns the whole reply text, not tokens β€” so today the\\nchunking is cosmetic pacing, not real streaming. The event shape exists now so\\nthat the day a service streams, it becomes a drop-in change behind an\\nunchanged frontend.\\n\\n### The message DTO\\n\\n```json\\n{ \\"id\\": \\"01J8…\\", \\"thread_id\\": \\"01J8…\\", \\"role\\": \\"assistant\\",\\n \\"status\\": \\"complete\\", \\"content\\": \\"…\\", \\"truncated\\": false, \\"error_code\\": null,\\n \\"created_at\\": 1761820800000, \\"completed_at\\": 1761820803120 }\\n```\\n\\n`role` is `user` or `assistant`; `status` is `pending`, `complete`, or\\n`failed` (a user turn is always `complete`). `content` is empty while pending,\\n`error_code` is set only when failed, `completed_at` is `null` until the turn\\nsettles. `truncated` is `true` when `content` is only the first part of what\\nthe assistant answered β€” the rest was over `max_chatbot_message_len` and was cut;\\nit is always `false` for a user turn and for a failed one. Show it: a clipped\\nanswer that looks whole is worse than one the reader knows is clipped. The same\\nDTO is what the SSE `done` event carries, so the streaming and polling reads\\nagree about `truncated` exactly as they do about every other field.\\n\\n### Status codes\\n\\n| code | when |\\n| --- | --- |\\n| `202` | the turn was accepted; the answer is on its way |\\n| `400` | empty message, or longer than the school's `max_chatbot_message_len` |\\n| `404` | no such thread or message β€” or not the caller's |\\n| `409` | already at `max_chatbot_threads`; delete a thread first |\\n| `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |\\n| `503` | no connected service offers `chat.reply` β€” **nothing was written**, retry later |\\n\\nThe `503` ordering matters: availability is checked before the rows exist, so\\nan unavailable service leaves no dead `pending` row behind, and the rate limit\\nis charged before that, so a refused turn leaves no trace at all. The check is\\nthe backend's own worker registry, which owns the QUIC sockets and is therefore\\nthe whole truth about what can be answered.\\n\\n### A turn always settles\\n\\nOnce the two rows exist the answer never stays `pending` forever, through\\nthree independent mechanisms:\\n\\n- the task that owns the bridge round trip stamps `complete` or `failed` β€”\\n the normal path;\\n- a reader **projects** a `pending` row older than 300 seconds as\\n `failed`/`timed_out` (a read-time projection, not a write β€” the row is left\\n for the task that may still own it);\\n- a **boot sweep** flips every leftover `pending` past the 300-second horizon\\n to `failed`/`interrupted`, which is what a process death mid-inference looks\\n like. Younger rows are left alone, since one may still be in flight.\\n\\nA restart therefore loses a turn that was in flight: it settles\\n`failed`/`interrupted` rather than being answered. Accepted β€” the backend is a\\nsingle process with stop-the-world deploys, so there is no peer that could have\\ntaken it over.\\n\\nTwo more verdicts come from inspecting the answer: an **empty** reply is\\nreported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a\\nbug), and an **over-long** one is truncated to `max_chatbot_message_len` β€” a\\nclipped answer still helps, a discarded one does not β€” with `truncated: true`\\non the stored turn, so the clip is never passed off as the whole answer.\\n\\n`error_code` values a client may see: `unavailable` (no worker, or the bridge\\nis off), `busy`, `timed_out`, `transport`, `protocol`, `bad_reply` (the\\nservice's payload did not parse), `empty_reply`, `service_error`,\\n`interrupted`, `not_found`, `internal` β€” **or a code the AI service itself\\nreturned**, verbatim. Treat it as an open set: branch on the ones you handle,\\nfall back to the human-readable text for the rest.\\n\\n### The `chat.reply` capability (for AI-service authors)\\n\\nA chat service declares `chat.reply` in its `Hello` (see \\"AI bridge (QUIC)\\").\\nRequests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:\\n\\n```json\\n{ \\"message\\": \\"and the second law?\\",\\n \\"history\\": [ {\\"role\\":\\"user\\",\\"content\\":\\"what is the first law?\\"},\\n {\\"role\\":\\"assistant\\",\\"content\\":\\"an object at rest …\\"} ] }\\n```\\n\\n`history` is **oldest first** (index 0 is furthest back), optional (absent or\\n`[]` = a fresh thread), and **excludes** the new message β€” that one is\\n`message`. It carries the last `chatbot_history_turns` **settled messages** β€”\\nentries, not exchanges: the default `10` is five question/answer pairs, and\\n`history` is exactly that many entries long whenever the thread holds enough\\nof them. Only settled turns count: a failed answer is skipped and the window\\nreaches further back for a usable one, rather than coming up short. All of it\\nis re-sent on every request, which is why the service may be stateless: it can\\nrestart, scale out, or be replaced mid-thread without losing context.\\n\\nThe answer is a `Response::Ok` whose payload is:\\n\\n```json\\n{ \\"text\\": \\"the complete reply, not chunked, not partial\\" }\\n```\\n\\nFailures reuse the existing `Response::Err {code, message}` β€” one failure\\nshape on the bridge for every capability β€” and that `code` reaches the client\\nas the message's `error_code`.\\n\\n**Unknown extra keys are ignored on both sides, on purpose.** A service may\\nadd fields (a model name, token counts) and a future backend may send more\\ncontext without either end having to be redeployed in lockstep.", "source": "README.md"}, {"id": "collaborative-whiteboard", "title": "Collaborative whiteboard", "body": "A board is a shared canvas whose membership is an **ad-hoc invite list**: the\\ncreator names participant user ids at `POST /boards` and that is the whole\\nmodel β€” no course, no lesson session, no appointment. Any account from\\n`student` upwards may open one. **Every participant draws; the creator\\nalone clears, locks, closes or deletes.**\\n\\n**No parents, anywhere.** The `parent` role is the school's read-only observer,\\nand it has no whiteboard access at all β€” not a view-only tier, none. It is\\nrefused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named*\\nin an invite list either: `resolve_participants` rejects a parent id with a\\n`400`, so a parent is never on a roster in the first place. That one cut is\\nwhat closes the rest β€” never on a roster means the id-scoped routes and the\\nroom's door already answer the outsider's `404` (never a `403`, which would\\nconfirm the board is there), and no socket opens, so no `stroke` frame can be\\nsent. The role bar is re-checked on the read path and at the door as well, so a\\nboard row written before this rule that still lists a parent is inert: that\\nparent sees a `404` for it like any stranger.\\n\\n**Two doors, two statuses.** A caller who is not on a board gets a `404` on\\nevery route, its existence included β€” an outsider must never learn a board is\\nthere. A participant who is not the creator has already been told it exists, so\\nthe four creator-only commands answer them a `403`: hiding it at that point\\nwould be a lie their client cannot act on. Over the socket the same refusal is\\n`error{code:\\"forbidden\\"}` and the socket **stays open** β€” someone clicking a\\nbutton they don't own must not lose the canvas they were drawing on.\\n\\n**A clear deletes nothing.** Strokes are append-only. `POST /boards/{id}/clear`\\nbumps the board's `epoch` and appends a `clear` **marker** carrying the epoch\\nit closed, that epoch's final stroke count, who cleared and when β€” so the live\\ncanvas empties while every mark ever drawn stays stored and replayable. Those\\nmarkers *are* the epoch index, which is why there is no epochs table and why\\nthe open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.\\n`DELETE /boards/{id}` is the one operation here that really destroys marks.\\n\\n**Three caps, and only one of them is terminal** (all three published at `GET\\n/limits` under `board`):\\n\\n- `max_epoch_strokes` bounds the **live** canvas β€” `epoch_stroke_count`, which\\n every clear resets. Hitting it is **recoverable**: the creator clears, the\\n history is kept, drawing resumes.\\n- `max_board_strokes` bounds the board's **lifetime** storage β€”\\n `total_stroke_count`, which never resets, because a clear keeps its history.\\n Hitting it stamps `closed_at` and the board becomes **permanently\\n read-only**: still fully readable and replayable, never deleted, and there is\\n no reopen β€” open a new board. `POST /boards/{id}/close` is the manual form of\\n the same thing, and idempotent.\\n- `max_boards_per_creator` bounds how many boards one creator holds\\n (`board_count` on the user row). Deleting a board frees a seat; closing one\\n does not β€” a closed board is still stored.\\n\\n**Two ways to read the marks, and the difference matters most to a client\\nauthor.** A socket `join` replays the **current epoch only**; history never\\nrides the socket. History is an explicit paged REST read:\\n`GET /boards/{id}/history` (the board's whole life, oldest first, `clear`\\nmarkers included, `?epoch=` for a single one) and `GET /boards/{id}/epochs`\\n(the marker index β€” enough to offer \\"replay session 3\\" without scanning the\\nlog). `GET /boards/{id}/strokes` is the current epoch over REST, the catch-up\\nand fallback path for the same canvas the socket replays β€” with one deliberate\\ndifference: the REST read is *not* filtered by kind, while the socket serves\\n`kind: \\"stroke\\"` rows only. In the steady state that is a distinction without a\\ndifference, since a marker is written with the epoch it *closed* and the open\\nepoch has none; the case where it shows is a clear landing between the board\\nread and the row read, which surfaces that epoch's closing marker in the page.\\nFor a live canvas the socket is the authority.\\n\\n**The board room (WebSocket)** β€” `GET /boards/{id}/ws`, cookie-authed like\\neverything else and, like the exam room, outside the OpenAPI spec (an upgrade\\nis not describable there); REST remains the full fallback. The gate before the\\nupgrade is the same `404` door: not a participant, no room. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| client β†’ | `{\\"type\\":\\"join\\", \\"after\\":\\"<last stroke id>\\", \\"epoch\\":3}` β€” both optional; replay the current epoch |\\n| server β†’ | `{\\"type\\":\\"state\\", board, epoch, locked, closed_at, creator, participants, now}` on connect and every `ws_tick_secs` |\\n| server β†’ | `{\\"type\\":\\"strokes\\", epoch, strokes:[{id, author, payload}]}` β€” one replay chunk, repeated until the epoch is served |\\n| server β†’ | `{\\"type\\":\\"synced\\", epoch, cursor}` β€” the replay is complete; `cursor` is what to resume from |\\n| client β†’ | `{\\"type\\":\\"stroke\\", \\"payload\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` β€” any participant |\\n| server β†’ | `{\\"type\\":\\"saved\\", id, client_seq?}` β€” your stroke landed |\\n| server β†’ | `{\\"type\\":\\"stroke\\", id, author, payload, epoch}` β€” someone *else* drew |\\n| client β†’ | `{\\"type\\":\\"clear\\"}` / `{\\"type\\":\\"lock\\", \\"locked\\":true}` β€” **creator only** |\\n| server β†’ | `{\\"type\\":\\"cleared\\", …}` / `{\\"type\\":\\"locked\\", locked, by}` β€” the canvas was emptied / drawing was paused |\\n| server β†’ | `{\\"type\\":\\"closed\\", …}` / `{\\"type\\":\\"deleted\\"}` β€” the board is finished; both end the room |\\n| server β†’ | `{\\"type\\":\\"participants\\", creator, participants}` β€” the roster changed; a socket no longer on it is dropped |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", code, message, client_seq?}` |\\n\\nA `stroke` may carry a `client_seq` exactly as an exam-room `answer` does: any\\nvalue the client picks, echoed **verbatim** on that message's `saved` or\\n`error` and on nothing else, omitted entirely when the request omitted it. The\\nserver never reads it.\\n\\n`error` codes are a closed set: `epoch_full` (the live canvas is full β€” clear\\nit and keep drawing), `board_closed` (permanently read-only), `locked`,\\n`forbidden` (a creator-only command from a participant), `resync` (below),\\n`invalid` (bad JSON, an unknown frame, an over-long payload), `not_found`,\\n`unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\n**Persist, then publish.** A stroke is fanned out only after its row has\\nlanded, so the channel can never carry a mark the database refused (a locked\\nboard, a full epoch, a closed board). The database is the canvas; the channel\\nis a notification *about* it β€” which is why a client dedupes by stroke `id`,\\nwhy a resync deliberately re-serves marks it already drew, and why a frame is\\nnever the authority: every stroke, clear and lock re-reads the board and\\nre-checks the roster, so a socket that missed a `participants` or `locked`\\nframe is refused all the same. One consequence of the same read-then-write\\nshape: a stroke carries the epoch the server read for it, so a clear landing in\\nthat instant can file one stroke under the epoch it just closed β€” the stroke is\\nkept and stays replayable in `/history`, it simply is not on the new canvas.\\n\\n**Reconnecting.** `join` carries a cursor: `after`, the last stroke id already\\ndrawn, plus the `epoch` it belongs to. Same epoch and only what is newer is\\nreplayed; an older epoch β€” or no cursor at all β€” gets a `cleared` frame first\\nand then the whole current epoch, because a cursor into a closed epoch no\\nlonger means anything. If the room falls behind a slow socket the server sends\\n`error{code:\\"resync\\"}` and immediately replays the current epoch **out of the\\ndatabase**: the client does not re-join, it throws its canvas away and takes\\nwhat follows. The database is always the source of truth, never the channel.\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/boards/${id}/ws`);\\nlet epoch = null, cursor = null, seq = 0;\\nws.onopen = () => ws.send(JSON.stringify({ type: \\"join\\", after: cursor, epoch }));\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"cleared\\") wipeCanvas();\\n if (m.type === \\"strokes\\") m.strokes.forEach(draw); // dedupe by m.id\\n if (m.type === \\"synced\\") ({ epoch, cursor } = m);\\n if (m.type === \\"stroke\\") draw(m);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.id);\\n if (m.type === \\"error\\" && m.code === \\"resync\\") wipeCanvas();\\n};\\nconst send = (payload) =>\\n ws.send(JSON.stringify({ type: \\"stroke\\", payload, client_seq: ++seq }));\\n```", "source": "README.md"}, {"id": "concurrency-model", "title": "Concurrency model", "body": "The backend runs as **one process against one database**, and that buys less\\nthan it sounds like: every request is an async task, dozens are in flight at\\nonce, and each of them awaits the database in the middle of its work. So\\n\\"read, decide, write\\" is never safe on its own β€” SurrealDB does not\\nconflict-check a cross-record `count()` against a concurrent insert\\n(write-skew), and that fires between two tasks in one process exactly as it\\nwould between two machines. The mutex-only design this replaced was already\\nlosing races at one process. Every invariant is therefore guarded where the\\ndatabase itself decides the winner. Three tiers:\\n\\n1. **Single-row conditional writes** β€” compare-and-set (`save_if_unchanged`),\\n `UPDATE … WHERE`, stored counters (`domain::cap`). A single-record write is\\n atomic, so of N concurrent tasks exactly the allowed number get a non-empty\\n result: the database decides the winner, the loser retries\\n (`CAS_UPDATE_RETRIES`) or gets a 409.\\n2. **In-transaction `IF … THROW` gates** β€” the check runs inside the same\\n statement as the write it authorizes, so it is atomic with it. Used where\\n the rule reads the row being written (state machines, delete guards).\\n \\"Is anything still attached?\\" is answered the same way, by a counter on the\\n row being deleted rather than a `SELECT` over the children: a course is\\n deletable while its `enrollment_count` is zero, a term while its\\n `course_count` is (courses claim that reference *before* they write the\\n link, and give it back when the link moves or the course is deleted). A fee\\n plan reads the same way β€” editable *and* deletable while its\\n `assignment_count` is zero, and frozen for good once it is not, since an\\n assignment is never taken back.\\n Where the child also carries a deterministic id β€” one enrollment per\\n (course, user), one registration per (event, user), one fee-plan assignment\\n per (plan, student) β€” the seat and the row\\n are claimed in one transaction (`cap::claim_and_create`), so a duplicate\\n `CREATE` rolls its own seat back instead of costing a stranger their place.\\n3. **Two accepted races**, reviewed and deliberately left open:\\n - *Attempt-seq late save* β€” an exam-room socket writes into the sitting it\\n joined with, a choice made before any lock is taken, so a save racing a\\n retake can stamp an answer onto the just-terminal previous sitting.\\n Damage: one history row; the grade of record (latest `seq`) is never\\n touched.\\n - *Approved-overlap* β€” two approvals landing in the same instant can\\n double-book a teacher. Damage: one overlapping half-hour, visible to both\\n parties, fixable by cancelling either side.\\n\\nIn-process locks remain, and they are a *second* line, never the guarantee:\\n`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional\\n-write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is\\nthe cap β€” the lock only tames the retry loop, and keeps the tests' in-memory\\nengine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in\\nfront of a rule no single-record write can express. Removing one of them costs\\nthroughput or an accepted race; removing the conditional write behind it costs\\nthe invariant.\\n\\nBoot is unconditional: the schema batches, the backfills and the admin seed all\\nrun on every start, because exactly one process ever starts. Deployment is\\nstop-the-world β€” `podman compose down` then `up`, never overlapping β€” and a\\nrelease that adds or renames a stored counter *requires* it. An old binary\\nwrites rows without touching the new counter, the `= NONE` backfill guard\\n(correctly) refuses to re-seed, and the resulting permanent under-count lets a\\nguard approve exactly what it exists to refuse. In-flight work does not survive\\na restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.", "source": "README.md"}, {"id": "layout", "title": "Layout", "body": "```\\nsrc/\\n main.rs bootstrap: config, db, router, serve\\n lib.rs build_router: routes + OpenAPI/Swagger + CORS + /health\\n config.rs env-sourced Config\\n constant.rs validation limits\\n validate.rs field validators (used by every newtype's try_new)\\n error.rs ValidationError + AppError -> HTTP responses\\n database.rs SurrealDB server connect (ws) + SCHEMAFULL migration\\n migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,\\n MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them\\n rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier\\n state.rs AppState { db, files_path, cookie_secure, rate_limit,\\n chatbot_limit, exam_presence, board_hub, db_up, ai }\\n ai/ QUIC bridge to the out-of-process AI services\\n (see \\"AI bridge (QUIC)\\"; the HTTP half is web/ai.rs)\\n protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing\\n server.rs AiBridge: listener, handshake, dispatch over per-request streams\\n registry.rs connected workers, capability routing, least-inflight leases\\n tls.rs listener certificate (PEM or self-signed) + fingerprint\\n error.rs AiError\\n chat.rs the `chat.reply` payload contract (ChatRequestPayload/ChatReplyPayload)\\n domain/ validated newtypes + entities (derive SurrealValue),\\n each owning its persistence\\n user.rs UserId Β· Username Β· Password Β· PasswordHash Β· User (has role)\\n role.rs Role enum (student < teacher < manager < admin), at_least()\\n field_update.rs FieldUpdate: one UPDATE ... SET built from only the fields a\\n PATCH actually carried (an omitted field is never written)\\n monotonic_id.rs next_ulid: ids that sort in write order β€” one process-wide\\n Generator, so same-millisecond rows never scramble\\n key.rs sitting(): the deterministic per-sitting record key shared by\\n attempts, answers, answer images and results (seq 1 stays bare)\\n cap.rs claim()/release(): the count caps the database enforces β€” an\\n atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter\\n column of the parent row, replacing count-then-write mutexes\\n that could not see a concurrent insert;\\n claim_and_create() commits that seat and the child row in\\n one transaction, for children with a deterministic id\\n text_fold.rs case- and diacritic-insensitive folding for search, shared by\\n the Rust needle and the SurrealQL column (Turkish Δ°/Δ±, ΓΌ, â…)\\n session.rs SessionId Β· SessionToken Β· Session (7-day expiry)\\n timestamp.rs Timestamp (unix-millisecond instant)\\n note.rs NoteId Β· NoteTitle Β· NoteContent Β· Note\\n note_file.rs NoteFileId Β· FileName Β· FileContentType Β· NoteFile (metadata row;\\n blob on disk under FILES_PATH, named by the row's ULID)\\n event.rs EventId Β· EventTitle Β· EventDescription Β· Event\\n attendance.rs AttendanceId Β· AttendanceStatus Β· Attendance\\n course.rs CourseId Β· CourseTitle Β· CourseDescription Β· Course\\n course_session.rs CourseSessionId Β· SessionTopic Β· CourseSession (a course's lesson)\\n session_attendance.rs SessionAttendanceId Β· SessionAttendance (roll call; one row per session+user)\\n work_entry.rs WorkEntryId Β· WorkEntry (staff stint; one open per user by construction)\\n enrollment.rs EnrollmentId Β· Enrollment (one row per course+user)\\n exam.rs ExamId Β· ExamTitle Β· ExamDescription Β· ExamKind Β· ExamWeight Β·\\n ExamMode Β· ExamDuration Β· ExamSchedule Β· Exam (belongs to a course)\\n exam_attempt.rs ExamAttemptId Β· AttemptStatus Β· ExamAttempt (numbered sittings per exam+user, metered by max_attempts)\\n exam_question.rs ExamQuestionId Β· QuestionText Β· QuestionKind Β· QuestionPoints Β·\\n ChoiceText Β· QuestionSpec Β· ExamQuestion (choice|text, per exam)\\n exam_answer.rs ExamAnswerId Β· AnswerText Β· ExamAnswer (one row per question+user) Β·\\n auto_score (choice-question suggestion)\\n exam_result.rs ExamResultId Β· Mark Β· ExamResult (one row per exam+user)\\n question_image.rs QuestionImageId Β· QuestionImage (question/choice picture\\n metadata; bytes on disk under FILES_PATH)\\n answer_image.rs AnswerImageId Β· AnswerImage (student answer-drawing\\n metadata; bytes on disk under FILES_PATH)\\n bank_question.rs BankQuestionId Β· BankQuestion (school-wide reusable\\n question template, copied into exams; no exam FK)\\n bank_question_image.rs BankQuestionImageId Β· BankQuestionImage (bank\\n question/choice picture metadata; bytes on disk under FILES_PATH)\\n profile.rs PersonName Β· Email Β· Phone Β· BirthDate (personal-info newtypes)\\n preferences.rs Theme Β· Language Β· PaletteColor (own UI preferences)\\n message.rs MessageId Β· MessageSubject Β· MessageBody Β· MessageLabel Β·\\n Message (per-copy folders: inbox/sent/archive/trash)\\n parent_link.rs ParentLinkId Β· ParentLink (parent↔student tie = the parent's read grant)\\n registration.rs RegistrationId Β· Registration (a seat on a registration event's signup list)\\n subject.rs SubjectId Β· SubjectName Β· SubjectDescription Β· Subject (course curriculum)\\n term.rs TermId Β· TermName Β· Term (school term window)\\n menu.rs MenuId Β· MenuDate Β· MenuSlot Β· Menu (one published menu per\\n calendar day + meal slot; slot snapshotted as text)\\n menu_dish.rs MenuDishId Β· DishName Β· DishDescription Β· DishPrice Β·\\n DishTags Β· MenuDish (a dish on a menu; price in minor units)\\n dietary_profile.rs DietaryProfileId Β· DietaryTags Β· DietaryNote Β·\\n DietaryProfile (what one student may not eat; keyed by the\\n student, tagged from the same `dietary_tags` list a dish is)\\n meal_booking.rs MealBookingId Β· MealBookingStatus Β· MealBooking (one seat\\n per (menu, student); a cancel flips the status, never deletes)\\n meal_attendance.rs MealAttendanceId Β· MealAttendanceStatus Β· MealAttendance\\n (who actually ate; one row per (menu, student), reporting\\n only β€” it never touches the ledger)\\n meal_ledger.rs MealLedgerId Β· MealLedgerKind Β· LedgerAmount Β· LedgerMethod Β·\\n LedgerNote Β· MealLedger (append-only money; the balance is\\n always the fold, never a stored field)\\n fee_plan.rs FeePlanId Β· FeePlanName Β· Installment Β· FeePlan (a school fee\\n plan; installments embedded on the row, past due dates legal)\\n fee_plan_assignment.rs FeePlanAssignmentId Β· FeePlanAssignment (one plan on\\n one student, keyed `<plan>_<student>`; assigning appends\\n every installment charge, a replay appends nothing)\\n payment_ledger.rs PaymentLedgerId Β· PaymentLedgerKind Β· PaymentLedger\\n (append-only school fees: charge/credit/reversal/refund, a\\n credit names its charge and a refund its credit; the balance\\n is always the fold; over-payment cap is advisory)\\n settings.rs ExamKindDef Β· GradeBand Β· Settings (per-school policy)\\n chatbot_thread.rs ChatbotThreadId Β· ChatbotThreadTitle Β· ChatbotThread (one\\n chatbot thread, private to its owner)\\n chatbot_message.rs ChatbotMessageId Β· ChatContent Β· MessageRole Β· MessageStatus Β·\\n ChatbotMessage (one turn; the assistant row is written\\n `pending` before the AI call and settled after)\\n board.rs BoardId Β· BoardTitle Β· Board (a collaborative whiteboard:\\n creator + ad-hoc participant list, `epoch`, the two stroke\\n counters and `closed_at`)\\n board_stroke.rs BoardStrokeId Β· BoardStroke (the\\n append-only stroke log; a `clear` row is the marker that\\n closed an epoch, carrying its final count β€” nothing is\\n ever deleted)\\n appointment_slot.rs AppointmentSlotId Β· SlotSeries Β· SlotNote Β·\\n AppointmentSlot (a teacher's published availability; a\\n recurring publish is expanded into rows sharing a series id)\\n appointment.rs AppointmentId Β· AppointmentStatus Β· AppointmentReason Β·\\n Appointment (a booking on a slot; occupancy is the slot's\\n stored `occupied` cap-1 counter, overlap is derived under\\n APPOINTMENT_LOCK)\\n pomodoro.rs PomodoroSessionId Β· PomodoroSession (student focus log)\\n pool_question.rs PoolQuestionId Β· PoolQuestionTitle Β· PoolQuestionBody Β·\\n PoolQuestion (student-asked question; teacher-approved into\\n the school-wide pool; optional photo as metadata + disk blob)\\n solution.rs SolutionId Β· SolutionBody Β· Solution (discussion thread on an\\n approved pool question; dies with the question)\\n homework.rs HomeworkId Β· HomeworkTitle Β· HomeworkDescription Β· Homework\\n (per-course assignment; required subject; optional `assigned`\\n student subset β€” absent/empty = the whole enrolled course)\\n homework_submission.rs HomeworkSubmissionId Β· SubmissionText Β·\\n HomeworkSubmission (one row per homework+user; immutable\\n submitted_at + moving updated_at β€” `late` is computed)\\n homework_file.rs HomeworkFileId Β· HomeworkFile (submission attachment\\n metadata; any content type; bytes on disk under FILES_PATH)\\n homework_result.rs HomeworkResultId Β· HomeworkStatus Β· HomeworkResult\\n (teacher grade: done/incomplete/missing + optional Mark; one\\n row per homework+user β€” its existence freezes the submission)\\n web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +\\n auth extractors\\n extractor.rs CurrentUser Β· RequireTeacher Β· RequireManager Β· RequireAdmin\\n dto.rs shared UserResponse Β· CourseResponse Β· ExamResponse Β· SessionResponse schemas\\n exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)\\n board_ws.rs the collaborative board room WebSocket (join replay, strokes\\n fanned out to every participant, clear/lock)\\n room.rs the plumbing both rooms share: sending a frame, classifying\\n an incoming message, an AppError as a readable code, and a\\n client_seq echoed untouched\\n page.rs PageParams Β· Page<T> (shared pagination)\\n etag.rs conditional-GET middleware: ETag over a 200 JSON body,\\n If-None-Match β†’ 304 (GET only; SSE and blobs pass through)\\n auth.rs users.rs notes.rs messages.rs events.rs appointments.rs\\n courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs\\n bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs\\n settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs\\n boards.rs\\n limits.rs GET /limits: every constant.rs bound served as JSON\\n```\\n\\nTests: `cargo test` β€” unit (in-source), integration (`tower::oneshot` + in-memory\\ndb), rate-limit (both tiers, proxy-header and peer-address keying, shipped\\nlimits over every route, two limiters sharing one budget over one db), e2e\\n(real TCP + reqwest cookie jar), persistence\\n(tempfile file engine, including close + reopen), ai-bridge (real QUIC on\\nloopback against a fake AI service), ai-protocol (the `hab/1` wire contract,\\ndriven by a client that shares no code with the backend).", "source": "README.md"}];
30+INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "711eb80e75da71b94c688418d680df9e365086460d6ec628b81cb20e19d7b605"}];
31+DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii;
32+DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25;
33+DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25;
34+REMOVE TABLE IF EXISTS endpoint;
35+INSERT INTO endpoint [{"id": "health", "routes": "| GET | `/health` | no | Liveness check |"}, {"id": "root", "routes": "| GET | `/` | no | Same as `/health` |"}, {"id": "time", "routes": "| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |"}, {"id": "limits", "routes": "| GET | `/limits` | no | Every fixed validation bound, grouped by resource \\u2014 see Validation limits |"}, {"id": "swagger", "routes": "| GET | `/swagger` | no | Interactive API docs (Swagger UI) |"}, {"id": "api-docs", "routes": "| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |"}, {"id": "ai", "routes": "| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |"}, {"id": "auth", "routes": "| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken \\u2014 see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |"}, {"id": "users", "routes": "| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` \\u2014 own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) \\u00b7 paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` \\u2014 find users by username/name fragment (pickers); refs only, no contact info \\u00b7 paged |\\n| GET | `/users` | admin | List all users \\u00b7 paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` \\u2014 set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` \\u2014 tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students \\u00b7 paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |"}, {"id": "notes", "routes": "| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes \\u00b7 paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) \\u2014 \\u2264 the school's `max_file_bytes`, \\u2264 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) \\u00b7 paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |"}, {"id": "messages", "routes": "| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` \\u2014 send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` \\u2014 the caller's folder, newest first; `?folder=inbox&read=false&limit=1` \\u2192 `total` is the unread badge \\u00b7 paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` \\u2014 read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** \\u2014 only from the trash (`409` elsewhere); the row vanishes once both sides deleted |"}, {"id": "events", "routes": "| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` \\u2014 `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` \\u2014 mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) \\u00b7 paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` \\u00b7 paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` \\u2014 seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |"}, {"id": "appointments", "routes": "| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` \\u2014 publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, \\u2264 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) \\u2014 a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar \\u2014 future slots only, demoted teachers' slots left out \\u00b7 paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` \\u2014 book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests \\u00b7 paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` \\u2014 call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included \\u2014 they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` \\u2014 counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal \\u2014 this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |"}, {"id": "courses", "routes": "| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` \\u2014 `kind` is `course` (default), `study` (et\\u00fct), or `club` (kul\\u00fcp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) \\u00b7 paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses \\u00b7 paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ \\u2014 **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` \\u2014 assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` \\u2014 enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u00b7 paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` \\u2014 add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` \\u2014 add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` \\u2014 add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) \\u00b7 paged |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` \\u2014 assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, \\u2264 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) \\u00b7 paged |"}, {"id": "subjects", "routes": "| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |"}, {"id": "sessions", "routes": "| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` \\u2014 roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) \\u00b7 paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |"}, {"id": "exams", "routes": "| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist \\u2014 the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` \\u2014 grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) \\u00b7 paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt \\u2014 students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) \\u00b7 paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question \\u2014 the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam \\u2014 copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** \\u2014 copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question \\u2014 text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` \\u2014 autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers \\u22c3 marks), ascending \\u2014 the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first \\u2014 the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** \\u2014 the answer key the caller checks their own sheet against (same review gate) \\u00b7 paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers \\u22c3 marks), ascending \\u2014 only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster \\u00d7 latest attempts \\u00d7 marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |"}, {"id": "bank-questions", "routes": "| GET | `/bank-questions` | teacher | The school-wide question bank \\u2014 `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) \\u00b7 paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist \\u2014 `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question \\u2014 the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |"}, {"id": "homework", "routes": "| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) \\u00b7 paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade \\u2014 the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades \\u2014 file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` \\u2014 hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part \\u2014 **any** content type, \\u2264 `max_file_bytes`, \\u2264 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) \\u2014 the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student \\u00d7 submission/files/grade + computed `late`/`missing`/`unenrolled` \\u2014 a straggler's stale work stays visible (course manager) \\u00b7 paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` \\u2014 grade `done`/`incomplete`/`missing` (+ optional 0\\u2013100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable \\u2014 that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) \\u2014 readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade \\u2014 un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows \\u2014 submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` \\u2014 full, statuses and marks only, never files \\u00b7 paged |"}, {"id": "questions", "routes": "| POST | `/questions` | student | `{title, body}` \\u2014 ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` \\u2014 the pool questions visible to the caller, each with its `solution_count` \\u00b7 paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question \\u2014 publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` \\u2014 offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first \\u2014 a discussion thread \\u00b7 paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` \\u2014 edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |"}, {"id": "marks", "routes": "| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "work", "routes": "| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) \\u00b7 paged |\\n| GET | `/work/{user}` | manager | A staff member's work log \\u00b7 paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` \\u2014 correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |"}, {"id": "pomodoro", "routes": "| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** \\u2014 a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` \\u00b7 paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape \\u00b7 paged; *or a `parent` linked to `{user}` |"}, {"id": "attendance", "routes": "| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "settings", "routes": "| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |"}, {"id": "terms", "routes": "| POST | `/terms` | manager | `{name, starts_at, ends_at}` \\u2014 past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first \\u00b7 paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term \\u2014 `409` while any course still links to it |"}, {"id": "meals", "routes": "| POST | `/meals/menus` | manager | `{date, slot, capacity?}` \\u2014 publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range \\u00b7 paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` \\u2014 the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` \\u2014 add a dish (\\u2264 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` \\u2014 record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` \\u2014 take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first \\u00b7 paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included \\u00b7 paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` \\u2014 mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu \\u00b7 paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day \\u00b7 paged \\u00b7 own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line |"}, {"id": "payments", "routes": "| POST | `/payments/plans` | manager | `{name, installments}` \\u2014 write a fee plan (1\\u201360 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first \\u00b7 paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it \\u2014 its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (\\u2264 200) \\u2014 place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first \\u00b7 paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` \\u2014 record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` \\u2014 hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` \\u2014 undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines \\u2014 charges, payments, refunds, reversals \\u2014 newest first \\u00b7 paged \\u00b7 own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |"}, {"id": "chatbot", "routes": "| POST | `/chatbot/threads` | student | `{title?}` \\u2014 start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first \\u00b7 paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` \\u2014 rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first \\u2014 user and assistant rows alike \\u00b7 paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (\\u2264 `max_chatbot_message_len`) \\u2014 send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` \\u2014 nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` \\u2014 or one `error` \\u2014 and close; an already-finished answer replays (see \\"Chatbot\\") |"}, {"id": "boards", "routes": "| POST | `/boards` | student | `{title, participant_ids?}` \\u2014 open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first \\u00b7 paged |\\n| GET | `/boards/{id}` | student | One board \\u2014 a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first \\u00b7 paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included \\u00b7 `?epoch=` for one epoch \\u00b7 paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) \\u00b7 paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` \\u2014 re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap \\u2014 nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board \\u2014 permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |"}];
36+SELECT VALUE sha256 FROM meta:readme;
37+REMOVE TABLE IF EXISTS doc;
38+REMOVE TABLE IF EXISTS meta;
39+INSERT INTO doc [{"id": "intro", "title": "intro", "body": "# hezarfen_backend\\n\\nNote, attendance, course + weighted exam mark backend. **Rust (edition 2024) Β· axum Β· SurrealDB 3 (server, WebSocket) Β· tokio.**\\n\\nSession-cookie auth with five hierarchical roles (`parent < student < teacher\\n< manager < admin`). A **`parent`** observes and changes nothing: admins tie\\nstudents to a parent account, and the parent reads those students' mark,\\nattendance, pomodoro, and homework reports β€” that's the whole role. Notes are per-user and carry **file attachments** (PDFs, documents,\\n…): blobs live on disk next to the database, metadata in the database, and the\\nper-file size cap is school policy in settings (`max_file_bytes`, default\\n5 MiB). Any two users can **message** each other, mail-style β€” subject +\\nbody into the recipient's inbox, each side filing its own copy through\\narchive/trash with a read flag the sender sees as a receipt (the only place a\\n`parent` writes). Attendance is event + attendees: create an event with an **audience**\\n(the whole school, one role, a course's enrollment, or a **registration**\\nsignup list β€” omit for school-wide), then teachers mark the expected attendees\\npresent / absent / late / excused (students never self-mark), and a **roster\\nreport** shows who was expected and who missed. Registration lists fill seat\\nby seat: teachers register students (never the other way round), staff\\nregister only themselves, an optional `capacity` caps the seats, and the list\\ncloses the moment the event starts (or, for an event with only an end time β€”\\na pure signup deadline β€” the moment that end passes). Every event stays visible to everyone β€”\\nthe audience is a roster, not a wall. Marks are course-shaped\\n(Google Classroom style): a teacher creates a course β€” kind **`course`** (a\\nregular class), **`study`** (a supervised study session β€” *etΓΌt*), or\\n**`club`** (a student club β€” *kulΓΌp*; same behavior, different label),\\noptionally capped by a `capacity` that refuses new enrolls once the roster is\\nfull β€” lays out its **subjects** (curriculum topics β€”\\nevery exam question must be tagged with one of its course's subjects, so\\nresults can later be read per topic), enrolls students, adds\\nexams inside it, and grades β€” enrolling, sitting exams, roll call, and marks are\\nall student-only, staff never take part. A course is run by whoever created it\\nplus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`):\\nan assigned teacher manages everything inside the course β€” exams, sessions,\\nsubjects, roster, grading β€” but can't delete it or change who else teaches it,\\nand a demotion below `teacher` sweeps their assignments away. Students read a per-course weighted average and\\nan overall average from their mark report β€” each exam weighted by its **kind**\\n(midterms can count double, orals once: weights are set per kind in settings,\\nnot per exam). Exams run **sync** (one\\nfixed window), **async** (start anytime inside the window, with a personal\\ntime budget), or **open** (sit anytime, optionally timed per attempt);\\nstudents *sit* them via attempts β€” retakes metered by a per-exam limit\\n(`0` = unlimited), each sitting keeping its own answers, drawings, and mark\\nso staff can read a student's full attempt history, leaving the exam room\\ngoverned by a teacher-controlled rejoin door. Writing an exam takes a while, so it can be saved as a\\n**draft** β€” invisible to students, unsittable, ungradable β€” and published\\nwhen it's ready. Questions can carry **images**: any question may hold one\\nillustration (a map above the prompt), and each option of a choice question\\nmay be a picture of its own (pick the right city off the map) β€” raster\\nuploads capped by the same `max_file_bytes` policy as note files. Good\\nquestions get reused, so a teacher+ can bank one in a school-wide **question\\nbank** β€” detached templates (with their own images) that any teacher copies\\ninto a fresh exam question across years, editable and deletable only by\\nwhoever saved them. Teachers\\nwatch attendance, per-student remaining time,\\nsittings, walk-outs, no-shows (`absent` once the window closes), submissions,\\nand marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out\\n**homework**: assigned to the whole class or a named subset (the unnamed never\\neven see it), tagged with a course subject, due by a required future `due_at`\\nβ€” students hand in text and/or **files of any type** (same size cap, 10 per\\nsubmission, served back only as forced downloads), editable until the teacher\\ngrades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark\\n(grading freezes the hand-in until the grade is removed); lateness is computed\\nfrom two stamps (first hand-in vs last touch), never stored, and homework\\nmarks stay out of the weighted `/marks` averages. Courses also carry **lesson\\nsessions** with teacher-taken roll call (students never self-mark a lesson),\\nstaff clock in/out on a server-stamped **work log**, students track study time\\nwith a server-stamped **pomodoro log** (the timer runs in the frontend; the\\nbackend records the focus stints, and teachers can read any student's log),\\nand every user has an\\n**attendance report** (event + per-course lesson tallies with rates).\\nA school-wide **question pool** runs on moderation: a student asks a question\\n(optionally attaching one photo of the problem β€” raster only, same\\n`max_file_bytes` cap), a teacher+ **approves** it into the pool (or deletes\\nit β€” rejection is deletion, there is no rejected state), and every approved\\nquestion is readable by the whole school with anyone free to offer\\n**solutions** under it (parents stay out) β€” text plus an optional photo of\\nthe worked steps, both editable by the solution's author anytime; pending\\nquestions show only to their asker and to teacher+, and approval freezes the\\ncontent so nothing unmoderated ever reaches the pool.\\nTeachers keep an **appointment calendar**: a teacher+ publishes availability\\nslots (one-off, or repeating weekly up to an `until` date as a series that\\ndeletes as one), and students and parents book a slot with a reason β€” the\\nbooking lands `pending` until the teacher approves it, rejects it, or\\ncounter-proposes another time (which sends it back to `pending` for the\\nrequester to accept or decline); the **requester** may cancel until the meeting\\nstarts β€” a teacher ends a booking by rejecting it, or by counter-proposing and\\nthen rejecting an approved one β€” one live booking holds a slot, a teacher's own\\npublished windows may not overlap each other, and no approved meeting may\\noverlap another for the teacher or the requester (see \\"Appointments\\").\\nSchool-varying policy is data, not code: exam kinds (each with its weight in\\ncourse averages), attendance statuses, grade-display bands, the note-file\\nsize limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms**\\nare plain rows courses can link to (see \\"Per-school policy\\"). Each account\\nalso carries its own **UI preferences** β€” theme (`light`/`dark`), language\\n(`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` β€”\\nany hex, deliberately not a fixed palette) β€” self-managed, admin-editable for\\nanyone, `null` until chosen so the client can fall back to the device\\npreference (or, for the accent, its own default).\\nThe **AI features live in separate projects**, so the backend also opens a\\nQUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in,\\nregister the capabilities they serve, and each request rides its own QUIC\\nstream on that one connection β€” no correlation ids, no head-of-line blocking.\\nThe bridge's certificate is published at `GET /ai/certificate` so a service can\\npin it before dialling (see \\"AI bridge (QUIC)\\").\\nThe first thing riding that bridge is the **chatbot**: every signed-in user\\n(`parent` included) keeps private threads with an AI service, free-form β€”\\nno rule tables, no canned answers, the backend only owns auth, limits,\\npersistence and the payload format. Sending is asynchronous because an\\ninference outlives a request: the turn plus an empty `pending` answer are\\nwritten *first*, the call goes out after, so a reload never loses an answer;\\nthe client then polls the message or reads it off an SSE stream (see\\n\\"Chatbot\\").\\nAny account from `student` upwards can also open a **collaborative\\nwhiteboard** (a `parent` gets no whiteboard access at all β€” it can neither open\\none nor be invited onto one): a titled board whose membership is an **ad-hoc\\ninvite list** β€”\\nthe creator names participant user ids, and no course, session or appointment\\nis involved. Every participant draws over a WebSocket, the creator alone\\nclears, locks, closes or deletes, and someone who is not on a board gets a\\n`404` for it on every route, existence included. Strokes are **append-only and\\na clear deletes nothing** β€” it bumps the board's epoch, so the live canvas\\nempties while every mark ever drawn stays stored and replayable through the\\nhistory reads (see \\"Collaborative whiteboard\\").\\nThe school's **food program** is published here too: a manager puts up one\\n**menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot`\\ndrawn from the school's `meal_slots`, unique per pair), lists its **dishes**\\nwith dietary tags from the school's own list, and prices them in **minor\\nunits** (kuruş) as integers β€” this API never speaks decimals or floats about\\nmoney. A student's own **dietary profile** is tagged from that same list\\n(manager-written β€” an allergen list is a school record, not a self-service\\npreference), so every dish a menu read returns names the tags it `conflicts`\\nwith for whoever is reading. Every authenticated user reads what is being\\nserved; students (or their parents) book a seat, and every seat writes a line into an\\n**append-only** meal ledger whose balance is derived and never stored (see\\n\\"Food program: menus, dishes, bookings & the ledger\\").\\nSchool **fees** are tracked the same way, in a ledger of their own: a manager\\nwrites a **fee plan** (a name and 1–60 installments, each an amount in minor\\nunits and a due date that may sit in the past) and **assigns** it to students,\\nwhich appends every installment as a `charge` at once β€” there is no scheduler,\\nand \\"overdue\\" is derived at read time. Payments are recorded against one named\\ncharge, refunds against one named payment, and nothing is ever edited or\\ndeleted: a mistake is corrected by appending the opposing line. **There is no\\nonline payment integration and none is planned** β€” no gateway, no card data,\\n`method` is free text. Teachers see no money at all (see \\"Payments\\").\\n\\nEvery field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)\\nconstructed only after its restrictions pass β€” invalid input can't be\\nrepresented. Those restrictions are published rather than left to be guessed:\\n**`GET /limits`** (no auth) serves every fixed bound and closed value set the\\nAPI enforces, read straight from the constants the newtypes use, so a frontend\\nvalidates against the server's own rules instead of a hand-kept copy (see\\n\\"Validation limits\\"). Those same types derive `surrealdb::types::SurrealValue`, so one\\ntyped value flows from HTTP request into the `SCHEMAFULL` database. Record ids\\nare ULIDs (time-sortable).", "source": "README.md"}, {"id": "run", "title": "Run", "body": "```sh\\nsurreal start --user root --pass root surrealkv:./data/hezarfen.db # the DB server\\ncp .env.example .env # optional\\ncargo run\\n```\\n\\nBoots on `http://127.0.0.1:8080`, talking to the SurrealDB server at\\n`DB_URL` (default `ws://127.0.0.1:8000`, root credentials via\\n`DB_USER`/`DB_PASS`) and storing uploaded note files in\\n`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs\\n(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at\\n`/api-docs/openapi.json`.", "source": "README.md"}, {"id": "run-in-a-container-podman", "title": "Run in a container (podman)", "body": "```sh\\npodman compose up -d --build # build + start, http://127.0.0.1:8080\\npodman compose logs -f backend\\npodman compose down # stop (data survives in the volume)\\n```\\n\\nThe `Containerfile` is a two-stage build (Rust builder with cargo cache\\nmounts, `debian:trixie-slim` runtime, non-root user). Two services: the\\n`surrealdb` server (official image, surrealkv storage) and the backend, which\\nwaits for the server's healthcheck and connects over `ws://surrealdb:8000`.\\nEach has its own named volume β€” `surreal-data` holds the database,\\n`hezarfen-data` the uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the\\ncontainer so the published port works. Production knobs (`COOKIE_SECURE`,\\n`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in\\n`compose.yaml` β€” uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset\\nmeans dev mirror mode without credentials; a cookie-using browser frontend\\nmust be allowlisted explicitly. Works with `docker compose` too.\\n\\nThe backend survives the database going away, at boot and at runtime.\\n\\nAt boot it retries the connection (1s doubling to 5s) until the server\\nanswers, rather than exiting. Exiting looks tidier but is worse: the container\\nruntime restarts the process, it fails again in milliseconds, and a few\\nseconds of startup skew burns the whole restart budget and leaves the backend\\ndown for good.\\n\\nAt runtime a keepalive query every 5s doubles as a liveness probe. This\\nmatters more than it sounds: a query issued while the socket is down does\\n*not* fail β€” the SDK's reconnect loop stops draining its request queue, so the\\nquery parks until the database returns and only *then* runs. Left alone, a\\nrequest waits out the entire outage and any write it carries lands long after\\nthe caller gave up.\\n\\nSo while the probe says the socket is down, requests are refused at the edge\\nwith `503` and `Retry-After: 1`, before they can reach the database. Nothing\\nis queued, which is what makes that retry safe. Requests that slip through in\\nthe window between the socket dying and the probe noticing are capped at 30s\\nand answer `503` *without* `Retry-After`, with a message saying the write may\\nor may not have applied β€” they were already queued, so retrying them could\\napply the same write twice. WebSocket and SSE routes are unaffected: both\\nreturn their response immediately and stream afterwards.\\n\\nWithout compose:\\n\\n```sh\\npodman build -t hezarfen-backend .\\npodman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backend\\n```", "source": "README.md"}, {"id": "auth-model", "title": "Auth model", "body": "Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, stored\\nserver-side). Send it back on later requests. Every endpoint below whose `Auth`\\ncolumn names a role requires a valid session; the ones marked `no` (`/health`,\\nthe docs pages, `register` / `login` / `logout`) don't (`logout` is idempotent β€”\\nit clears the session if one is present). Set `COOKIE_SECURE=true` when serving\\nbehind TLS to add the cookie's `Secure` attribute.\\n\\n**Register never reveals whether a username is taken.** `POST /auth/register`\\nanswers `201` either way with the *same* body β€” `{username, role}`, the echoed\\nname and the `student` role every fresh account gets. Both outcomes return one\\nvalue built before the insert is even attempted, so they are byte-identical by\\nconstruction. This is deliberate: the route is unauthenticated, so a `409` (or a\\nfaster reply) would let anyone enumerate the school's users. The password is\\nhashed *before* the availability check so both outcomes cost the same ~33ms.\\n\\nThe reply carries **no `id`**: on the taken path there is no row to name, and a\\nfabricated one would leave the client holding an id that matches nothing. Log\\nin and read `GET /auth/me` to learn who you are. The accepted cost: a caller who\\ncollides with an existing account gets no distinct error and simply cannot log\\nin with that password β€” they pick another name. Do not \\"fix\\" this back to a\\n`409`, and do not add an `id` back.", "source": "README.md"}, {"id": "time-policy", "title": "Time policy", "body": "Timezones and clock differences cannot corrupt data, by construction:\\n\\n- **Every instant is a UTC unix-millisecond `i64`** (`domain::timestamp::Timestamp`),\\n stored as an `int`, sent as a plain number. Nothing stores or parses a\\n timezone, so the server's `TZ`, the container's clock config, and the\\n client's locale are all irrelevant β€” clients convert millis to local time\\n for display only.\\n- **One clock choke point.** `Timestamp::now()` is the only wall-clock read.\\n `clippy.toml` bans every other source (`chrono::Local`/`Utc::now`,\\n `SystemTime::now`, `time::OffsetDateTime::now_*`, absolute cookie\\n `Expires`) and `[lints.clippy]` raises that to a hard `cargo clippy` error,\\n so local-time bugs can't be reintroduced.\\n- **Expiry is server-authoritative.** Sessions expire by comparing the stored\\n millis against the server clock; the cookie carries a relative `Max-Age`\\n (never an absolute `Expires`), so a wrong client clock changes nothing.\\n- **Pacing uses the monotonic clock.** The rate limiter runs on `Instant`,\\n immune to NTP steps and wall-clock jumps.\\n- **Calendar dates get a timezone grace.** A birth date is a calendar date on\\n the writer's wall, not an instant: validation accepts up to UTC-tomorrow,\\n since a client ahead of UTC (up to UTC+14) legitimately writes a date the\\n server's UTC calendar hasn't reached yet.\\n- **Times-of-day are UTC too, and staff enter them that way.** A meal slot's\\n `serving_minute` (minutes past midnight, `0`–`1439`) is the one clock-face\\n value a school types in, and it is read as UTC on the menu's `date` β€” there\\n is deliberately **no school-timezone setting** (a rejected feature), so a\\n UTC+3 school enters `540` (09:00 UTC) for a meal served at noon locally.\\n- **Nothing schedules in the past.** A request-supplied schedule instant β€” an\\n exam window, a lesson's `starts_at`/`ends_at`, an event time β€” must not lie\\n before the server's now, on create and on every `PATCH` that sets it: a\\n deadline that starts in the past is dead on arrival, so it's a `400`. A\\n 60-second grace absorbs request latency and client-clock skew (\\"starts now\\"\\n survives its own round trip). Values a `PATCH` merely keeps are exempt β€” a\\n running exam's `starts_at` is legitimately past, and a rename or deadline\\n extension must not trip over it. (Work-log corrections are records of past\\n work, not schedules, and stay free.)\\n- **Frontends can sync to the server clock.** `GET /time` (no auth) returns\\n `{\\"now\\": <UTC unix-millis>}`. Fetch once, keep\\n `offset = now - Date.now()`, and use `Date.now() + offset` for countdowns\\n and past/future checks instead of trusting the device clock.\\n\\nKeep the single server's clock NTP-synced; that's the only clock that matters.", "source": "README.md"}, {"id": "validation-limits", "title": "Validation limits", "body": "Every fixed bound the API enforces is published at `GET /limits` (no auth), so\\na client never has to hard-code a copy that drifts the day a constant moves.\\nThe handler reads `src/constant.rs` directly β€” a changed constant changes the\\nresponse in the same commit.\\n\\n```json\\n{\\n \\"user\\": { \\"min_username_len\\": 3, \\"max_username_len\\": 32,\\n \\"username_separators\\": [\\".\\", \\"_\\", \\"-\\"],\\n \\"reserved_usernames\\": [\\"admin\\", \\"…\\"],\\n \\"min_password_len\\": 6, \\"max_password_len\\": 128,\\n \\"max_name_len\\": 100, \\"max_email_len\\": 254,\\n \\"min_phone_digits\\": 7, \\"max_phone_digits\\": 15,\\n \\"roles\\": [\\"parent\\", \\"student\\", \\"teacher\\", \\"manager\\", \\"admin\\"],\\n \\"themes\\": [\\"light\\", \\"dark\\"], \\"languages\\": [\\"tr\\", \\"en\\"],\\n \\"palette_color_pattern\\": \\"^#[0-9a-fA-F]{6}$\\", \\"palette_color_len\\": 7,\\n \\"session_duration_days\\": 7 },\\n \\"note\\": { \\"max_title_len\\": 200, \\"max_content_len\\": 10000, \\"max_files\\": 10 },\\n \\"file\\": { \\"max_name_len\\": 255, \\"max_content_type_len\\": 100,\\n \\"min_max_file_bytes\\": 1024, \\"max_max_file_bytes\\": 26214400,\\n \\"default_max_file_bytes\\": 5242880,\\n \\"image_content_types\\": [\\"image/png\\", \\"image/jpeg\\", \\"image/webp\\", \\"image/gif\\"] },\\n \\"message\\": { \\"max_subject_len\\": 200, \\"max_body_len\\": 10000, \\"max_label_len\\": 50 },\\n \\"event\\": { \\"max_title_len\\": 200, \\"max_description_len\\": 2000 },\\n \\"course\\": { \\"kinds\\": [\\"course\\", \\"study\\", \\"club\\"], \\"max_title_len\\": 200, \\"…\\": 0 },\\n \\"exam\\": { \\"modes\\": [\\"sync\\", \\"async\\", \\"open\\"],\\n \\"question_kinds\\": [\\"choice\\", \\"text\\"],\\n \\"min_duration_ms\\": 60000, \\"max_duration_ms\\": 86400000,\\n \\"max_attempts\\": 100, \\"unlimited_attempts\\": 0,\\n \\"min_mark\\": 0, \\"max_mark\\": 100, \\"…\\": 0 },\\n \\"homework\\": { \\"statuses\\": [\\"done\\", \\"incomplete\\", \\"missing\\"],\\n \\"max_files_per_submission\\": 10, \\"max_assigned\\": 200, \\"…\\": 0 },\\n \\"question_pool\\": { \\"max_title_len\\": 200, \\"max_body_len\\": 10000, \\"max_solution_body_len\\": 10000 },\\n \\"appointment\\": { \\"max_note_len\\": 500, \\"max_reason_len\\": 1000, \\"max_slot_occurrences\\": 52 },\\n \\"chatbot\\": { \\"max_message_len\\": 8000, \\"max_thread_title_len\\": 200,\\n \\"min_max_message_len\\": 100, \\"…\\": 0 },\\n \\"board\\": { \\"max_title_len\\": 200, \\"max_participants\\": 50,\\n \\"max_stroke_payload_len\\": 4096,\\n \\"max_epoch_strokes\\": 5000, \\"max_board_strokes\\": 50000,\\n \\"max_boards_per_creator\\": 200,\\n \\"stroke_kinds\\": [\\"stroke\\", \\"clear\\"],\\n \\"ws_tick_secs\\": 15, \\"ws_max_board_id_len\\": 64 },\\n \\"settings\\": { \\"max_list_len\\": 20, \\"max_item_len\\": 50,\\n \\"min_exam_kind_weight\\": 1, \\"max_exam_kind_weight\\": 100,\\n \\"max_grade_bands\\": 20, \\"max_grade_label_len\\": 20,\\n \\"required_attendance_statuses\\": [\\"present\\", \\"absent\\", \\"late\\", \\"excused\\"] },\\n \\"request\\": { \\"max_page_limit\\": 500, \\"schedule_past_grace_ms\\": 60000,\\n \\"request_timeout_secs\\": 30 },\\n \\"rate\\": { \\"window_secs\\": 60, \\"auth_per_minute\\": 10,\\n \\"api_per_minute\\": 300, \\"chatbot_per_minute\\": 20 }\\n}\\n```\\n\\nThe `rate` group is the one part that is **not** compile-time: those tiers are\\nenvironment-tunable, so the endpoint serves *this* server's live values (read\\nfrom its running limiters), not the shipped defaults. `0` means the tier is\\noff. A client should read its budget here rather than discovering it by\\ncollecting a `429`.\\n\\n### Two surfaces, one source\\n\\nThe bounds are published twice, on purpose, because clients consume them two\\ndifferent ways:\\n\\n| Surface | Shape | Use it when |\\n|---------|-------|-------------|\\n| `GET /limits` | One JSON document, grouped by resource, closed value sets included | Runtime fetch. No codegen step, survives a deploy skew, and carries things OpenAPI holds awkwardly (`reserved_usernames`, `image_content_types`) |\\n| `/api-docs/openapi.json` | Per-field `maxLength` / `minLength` / `minimum` / `maximum` / `maxItems` on the request schemas | Build-time codegen β€” `openapi-typescript`, `orval`, and friends turn these into types *and* validators automatically |\\n\\nBoth are generated from the same `src/constant.rs`, and **neither is allowed to\\ndrift from it**, which is enforced rather than asked for:\\n\\n- `tests/limits_completeness.rs` parses every `pub const` out of `constant.rs`\\n and fails unless each one is either referenced by `src/web/limits.rs` or\\n listed as a deliberate exclusion *with a reason*. A new constant breaks the\\n suite until someone decides, consciously, whether clients need it.\\n- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 161 published\\n bounds back out of the emitted JSON, and asserts each equals its constant.\\n This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal\\n only** β€” a `const` there does not compile β€” so the annotations are\\n unavoidably a second copy of each number. The test is what makes that copy\\n safe. It also pins the `limit` query parameter's `maximum` to\\n `MAX_PAGE_LIMIT`, a duplication `constant.rs` previously only *asked* a human\\n to maintain.\\n- A third check in `limits_completeness.rs` refuses to let a validation bound\\n be declared **outside** `constant.rs` at all. Without it a limit can hide in\\n a domain module and reach neither surface β€” which is exactly where\\n `MAX_CHATBOT_THREAD_TITLE_LEN` was found sitting, private and unpublished.\\n\\nNotes:\\n\\n- **No auth.** The registration and login forms need the username and password\\n bounds before a session exists, and none of these are secrets β€” they are the\\n same rules a `400` already spells out in prose.\\n- **Answers during a database outage.** `/limits` touches no row, so it is\\n exempt from the guard that answers `503` while the database reconnects β€” a\\n frontend booting against a degraded backend is exactly when it needs the\\n contract. Every route that does read the database still refuses.\\n- **Fetch once.** The values are compile-time constants, so the response only\\n changes with a deploy. Cache it for the session; the `ETag`/`304` path makes\\n a revalidation cheap if you'd rather re-check.\\n- **`/limits` is not `/settings`.** School-adjustable policy β€” the exam kinds\\n and their weights, the attendance statuses, the grade bands, the live\\n `max_file_bytes` and chatbot knobs β€” is on `GET /settings` and changes when a\\n manager edits it. What `/limits` carries for those knobs is the fixed range a\\n manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the\\n attendance statuses no school may remove.\\n- **Open sets travel as a pattern.** `palette_color` accepts any hex accent\\n color, so `/limits` publishes `palette_color_pattern` (a regular expression)\\n and `palette_color_len` instead of a value list β€” validate the shape, not\\n membership in a palette. The pattern describes what the server *accepts*, so\\n it matches either case; the stored (and returned) value is lowercased, which\\n is the one place a response may differ in case from the request.\\n- **Closed value sets ride along.** `roles`, `themes`, `languages`, course\\n `kinds`, exam `modes`, `question_kinds`, homework `statuses`, board\\n `stroke_kinds`, and the\\n uploadable `image_content_types` are the exact accepted spellings β€” build\\n pickers from these rather than from a literal list.", "source": "README.md"}, {"id": "rate-limiting", "title": "Rate limiting", "body": "Requests are limited per client IP over a fixed 60-second window, in two tiers:\\n`/auth/login` + `/auth/register` get a strict budget\\n(`RATE_LIMIT_AUTH_PER_MINUTE`, default 10) against credential brute-force,\\nand every route β€” Swagger included β€” shares a generous catch-all\\n(`RATE_LIMIT_API_PER_MINUTE`, default 300). Exceeding either answers `429` with\\na `Retry-After` header (seconds). Set a limit to `0` to disable that tier β€”\\nuseful for load tests.\\n\\nSending a chatbot message adds a third tier, and it is keyed by **user id**,\\nnot by IP (`RATE_LIMIT_CHATBOT_PER_MINUTE`, default 20), because an inference\\ncosts the school real money and a shared-IP classroom must not spend one\\nstudent's budget on another's. `0` disables it like the other two. It is\\ncharged before anything is written, so a `429` leaves no trace (see\\n\\"Chatbot\\").\\n\\nAll three tiers admit from memory β€” no request ever waits on the database to be\\nlet in β€” but the window **outlives the process**. A background task folds each\\ntier's new admits into one shared `rate_limit` row per tier + client + minute\\nevery 2 seconds, then caps the in-memory bucket by the total that comes back,\\nso a restart mid-minute does not hand every client a fresh budget. One caveat:\\na just-started process can spend up to the tier's budget in the 2 seconds\\nbefore its first fold tightens it. If the database is down the tiers simply\\nfall back to their own local budgets β€” nobody is refused for it.\\n\\nBehind a reverse proxy every connection carries the proxy's address, so also\\nset `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry\\n(the one the proxy itself appends). Leave it off when clients reach the server\\ndirectly β€” the header is client-forged in that case.", "source": "README.md"}, {"id": "cors", "title": "CORS", "body": "Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin`\\n(browsers refuse it on credentialed requests), so origins listed in the\\ncomma-separated `CORS_ALLOWED_ORIGINS` allowlist are echoed back with\\n`Access-Control-Allow-Credentials: true`. When the allowlist is unset the\\nserver reflects the request's `Origin` β€” dev-friendly β€” but **without**\\ncredentials: mirroring with credentials would let any website ride a\\nvisitor's session cookie. A browser frontend that needs the session cookie\\ncross-origin must therefore be allowlisted explicitly.", "source": "README.md"}, {"id": "roles-access-control", "title": "Roles & access control", "body": "Every user has one of five roles, ranked lowest to highest:\\n\\n```\\nparent < student < teacher < manager < admin\\n```\\n\\nThe check is **hierarchical** β€” a higher role satisfies any lower requirement\\n(an admin can do anything a teacher can). New accounts always register as\\n`student`; a role read is re-checked on every request, so a role change takes\\neffect on the user's very next call (no re-login).\\n\\n`parent` is the read-only observer at the bottom of the ladder: an admin ties\\nany number of students to a parent account (`POST /users/{id}/students`), and\\nthe tie is the parent's whole power β€” they list their students\\n(`GET /users/me/students`) and read each one's mark, attendance, pomodoro,\\nand homework reports in full. Student-only checks are exact (`role == student`), so a\\nparent can never enroll, sit an exam, be graded, or land on a roll call; and\\nsitting below every staff bar, they can't touch anything else either β€” except\\nmessages, which any role sends and receives (that's how a parent reaches a\\nteacher). A role\\nchange off either end of a tie (the parent stops being a `parent`, the\\nstudent stops being a `student`) drops the tie, exactly like promotion drops\\ncourse enrollments.\\n\\n| Action | Minimum role | Notes |\\n|------------------------------------------|--------------|-----------------------------------------------|\\n| Register / login / view own account | (any) | Registration always creates a `student` |\\n| View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves |\\n| Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included β€” the role's one write); each party only ever touches their own copy |\\n| Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark β€” a teacher+ may mark anyone expected, themselves included |\\n| Create events | teacher | The audience (school / role / course / registration) is set at creation and editable later |\\n| Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** β€” never for another staff member. Unregistering mirrors the same rule |\\n| List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report |\\n| Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |\\n| View a course's sessions | student | Only inside **visible** courses: enrolled, creator, assigned teacher, or `manager`+ |\\n| List a session's roll call | teacher | The **session's teacher**, or anyone with course-management rights |\\n| Create / edit / delete a course session | teacher | Course-management rights (course creator, an assigned teacher, or `manager`+) |\\n| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights; only students sit on a roster |\\n| Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call β€” the teacher can't self-mark |\\n| Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied |\\n| View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries |\\n| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session |\\n| View **any** user's pomodoro log | teacher | Study oversight β€” same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' |\\n| Ask into the school question pool | student | **Students only** (exact); born `pending` β€” visible to the asker + teacher+ only; the asker may attach/replace/remove one photo while pending |\\n| Read the pool; offer / edit / withdraw own solutions | student | Every `approved` question is school-wide (parents stay out); a solution's author edits its body and photo anytime (solutions never freeze) and deletes it, teacher+ delete any |\\n| Approve a pending pool question; delete any question or solution | teacher | Approval publishes school-wide and **freezes** the content; rejection = deletion β€” moderation never edits, so teacher+ cannot rewrite a solution |\\n| Read the school **question bank**; save / instantiate bank questions | teacher | Every bank row is school-wide (reads + copy into an exam); saving one makes the caller its owner |\\n| Edit / delete a bank question (and its images) | teacher | **Owner only** (admin bypass); bank rows carry no exam link, so they never freeze |\\n| Read **own** attendance report | student | |\\n| Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created + assigned; `manager`+: all); exam **drafts** show only to the course's managers |\\n| Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** β€” staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |\\n| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |\\n| Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |\\n| Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights β€” one teacher can't read another's answer key |\\n| Watch an exam's live monitor (poll the snapshot) | teacher | Course-management rights |\\n| Create courses | teacher | The creator manages the course, and owns it for good |\\n| Assign / unassign a course's teachers | manager | Staffing is the office's call β€” a course's own creator cannot hand rights to peers; the assignee must be `teacher`+ |\\n| Delete a course | teacher | Only the **creator**, or a `manager`+ β€” an assigned teacher runs the course but doesn't own it |\\n| Manage inside a course: edit it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | The **course creator**, a teacher **assigned** to it, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions or homework won't delete (`409`) |\\n| View a course's roster, an exam's result list / statistics | teacher | Course-management rights |\\n| Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself |\\n| Assign / edit / delete homework; grade it; read its roster | teacher | Course-management rights; an `assigned` subset (≀ 200 enrolled students) can't be narrowed over existing work (`409`); a grade (`done`/`incomplete`/`missing` + optional mark) freezes the submission until removed |\\n| Submit **own** homework (text + files); read own submission and grade | student | **Students only** β€” staff never submit; enrolled + in the audience; editable until graded; ≀ 10 files of any type, each ≀ `max_file_bytes`, always downloaded as attachments |\\n| Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full β€” statuses/marks/flags, never files |\\n| Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields |\\n| Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen β€” the client then follows the device preference |\\n| List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports β€” a parent changes nothing, anywhere |\\n| Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |\\n| Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call |\\n| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role |\\n\\n### Bootstrapping the first admin\\n\\nThere is no self-service path to `admin` β€” registration always creates a\\n`student`. The first admin comes from the startup seed: set both\\n\\n```sh\\nADMIN_USERNAME=admin\\nADMIN_PASSWORD=admin123 # local-dev default used by compose.yaml; change it\\n```\\n\\nand on boot the account is created with the `admin` role **if the username\\ndoesn't exist yet**. The seed is idempotent and deliberately conservative: it\\nnever promotes or rewrites an existing account (if the name is taken by a\\nnon-admin it logs a warning and leaves it alone β€” promoting someone else's\\naccount would be an escalation). Setting only one of the two variables aborts\\nstartup. `compose.yaml` ships with the credentials above for local dev.\\n\\nThat admin can then promote everyone else through `PATCH /users/{id}/role`.\\n\\nManual fallback (also the recovery path if the seeded name was squatted or the\\nsole admin locked themselves out): run\\n\\n```surql\\nUPDATE user SET role = 'admin' WHERE username = 'ada';\\n```\\n\\nagainst the SurrealDB server β€” e.g.\\n`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db hezarfen`\\n(in the container setup, `podman exec -it hezarfen-surrealdb /surreal sql ...`).", "source": "README.md"}, {"id": "endpoints", "title": "Endpoints", "body": "`Auth` is the minimum role; `no` means no session required, `student` means any\\nlogged-in user.\\n\\nA course is a regular class (kind `course`, the default), an *etΓΌt* (kind\\n`study` β€” a supervised study session), or a *kulΓΌp* (kind `club` β€” a student\\nclub). The three kinds behave identically everywhere β€” enrollment, exams,\\nsessions, marks β€” the kind is a label the UI renders differently, settable at\\ncreation and editable later. A course may also carry a `capacity`: once the\\nroster reaches it, new enrolls are refused with `409` (members already on the\\nroster are unaffected, even if the cap is later lowered below them; `null`\\nlifts the cap).\\n\\n**Who runs a course.** Its **creator** owns it for good β€” only they (or a\\nmanager+) may delete it. On top of that, a manager can **assign** any\\n`teacher`+ to the course with `POST /courses/{id}/teachers` (`{user_id}`,\\nidempotent) and drop them again with `DELETE /courses/{id}/teachers/{user}`.\\nAn assigned teacher gets full **course-management rights** β€” edit the course,\\nenroll and unenroll students, add exams, sessions and subjects, grade, take\\nroll call β€” but *not* the two owner powers: they cannot delete the course, and\\nthey cannot change who else teaches it. Staffing is deliberately the office's\\ncall, so a course's own creator cannot hand rights to their peers; only\\nmanager+ may touch the list. Every course response carries its `teachers`\\narray alongside `creator`, and a user demoted below `teacher` is swept off\\nevery course they were assigned to (the mirror of promotion dropping\\nenrollments).\\n\\nCourse data is walled per course. A course, its exams, its sessions, and its\\nsubjects are\\n**visible** only to its enrolled users, its creator, its assigned teachers,\\nand manager+ β€” a student\\nsees just the classes they were added to, and the `/courses` / `/exams`\\ncatalogs are filtered accordingly. Teacher-level reads *inside* a course\\n(roster, results, statistics, the question list, answer sheets, the live\\nmonitor) additionally need **course-management rights** (creator, an assigned\\nteacher, or manager+):\\none teacher cannot look into another teacher's course, and the per-user\\nmarks/attendance reports narrow to the courses the caller manages.\\n\\n**Paging.** Every list endpoint below (the rows tagged **Β· paged**) accepts\\n`?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope\\nrather than a bare array. `total` is the full row count *before* the window, so\\na frontend can show \\"100 of 256\\" and page with `offset`. Paging is **opt-in**:\\nomit `limit` and you get every remaining row (the echoed `limit` is then\\n`null`), so a caller that sends no parameters still receives the whole list β€”\\nnothing silently truncates. `limit` must be `1`–`500`, `offset` defaults to `0`\\nand must be β‰₯ 0 (bad values are `400`), and an `offset` at or past the end\\nreturns an empty `items` (not an error). Deliberately **not** paged β€” these keep\\ntheir existing shapes: the student exam-room reads\\n`/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and\\n`/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`.\\n\\n**Schedule window (`GET /events`, `GET /exams`).** Both lists additionally\\naccept `?starts_after=` and `?ends_after=`, UTC unix-millis, both optional and\\nindependent (AND-ed when both are sent). `ends_after=T` keeps rows whose window\\nhas not finished β€” `ends_at > T`, falling back to `starts_at > T` when `ends_at`\\nis `null`; `starts_after=T` keeps rows with `starts_at > T`. A row with no\\nschedule at all (an event without times, an exam with no `mode` or in `open`\\nmode) is excluded by either parameter. Supplying either one flips the order to\\n**ascending by schedule** (`starts_at`, falling back to `ends_at`; ties by id),\\nso `?ends_after=<now>&limit=20` gives the twenty *soonest* rows instead of the\\ntwenty newest-created β€” with neither parameter the list is byte-for-byte the\\nnewest-first list it always was. `total` is the count after visibility *and*\\nwindow filtering, before paging; negative values are a `400` naming the field.\\n\\n| Method | Path | Auth | Description |\\n|--------|----------------------------------|---------|---------------------------------|\\n| GET | `/health` | no | Liveness check |\\n| GET | `/` | no | Same as `/health` |\\n| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |\\n| GET | `/limits` | no | Every fixed validation bound, grouped by resource β€” see Validation limits |\\n| GET | `/swagger` | no | Interactive API docs (Swagger UI) |\\n| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |\\n| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |\\n| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken β€” see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |\\n| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` β€” own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) Β· paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` β€” find users by username/name fragment (pickers); refs only, no contact info Β· paged |\\n| GET | `/users` | admin | List all users Β· paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` β€” set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` β€” tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students Β· paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |\\n| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes Β· paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) β€” ≀ the school's `max_file_bytes`, ≀ 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) Β· paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |\\n| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` β€” send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` β€” the caller's folder, newest first; `?folder=inbox&read=false&limit=1` β†’ `total` is the unread badge Β· paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` β€” read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** β€” only from the trash (`409` elsewhere); the row vanishes once both sides deleted |\\n| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` β€” `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` β€” mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) Β· paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` Β· paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` β€” seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |\\n| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` β€” publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, ≀ 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) β€” a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar β€” future slots only, demoted teachers' slots left out Β· paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` β€” book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests Β· paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` β€” call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included β€” they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` β€” counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal β€” this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |\\n| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` β€” `kind` is `course` (default), `study` (etΓΌt), or `club` (kulΓΌp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) Β· paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses Β· paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ β€” **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` β€” assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` β€” enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) Β· paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β€” add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β€” add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |\\n| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` β€” roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) Β· paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` β€” add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) Β· paged |\\n| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist β€” the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` β€” grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) Β· paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt β€” students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) Β· paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question β€” the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam β€” copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** β€” copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question β€” text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` β€” autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers ⋃ marks), ascending β€” the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first β€” the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** β€” the answer key the caller checks their own sheet against (same review gate) Β· paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers ⋃ marks), ascending β€” only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster Γ— latest attempts Γ— marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |\\n| GET | `/bank-questions` | teacher | The school-wide question bank β€” `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) Β· paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist β€” `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question β€” the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` β€” assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≀ 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) Β· paged |\\n| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) Β· paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade β€” the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades β€” file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` β€” hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part β€” **any** content type, ≀ `max_file_bytes`, ≀ 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) β€” the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student Γ— submission/files/grade + computed `late`/`missing`/`unenrolled` β€” a straggler's stale work stays visible (course manager) Β· paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` β€” grade `done`/`incomplete`/`missing` (+ optional 0–100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable β€” that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) β€” readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade β€” un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows β€” submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` β€” full, statuses and marks only, never files Β· paged |\\n| POST | `/questions` | student | `{title, body}` β€” ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` β€” the pool questions visible to the caller, each with its `solution_count` Β· paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question β€” publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` β€” offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first β€” a discussion thread Β· paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` β€” edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |\\n| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) Β· paged |\\n| GET | `/work/{user}` | manager | A staff member's work log Β· paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` β€” correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |\\n| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** β€” a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` Β· paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape Β· paged; *or a `parent` linked to `{user}` |\\n| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |\\n| POST | `/terms` | manager | `{name, starts_at, ends_at}` β€” past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first Β· paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course still links to it |\\n| POST | `/meals/menus` | manager | `{date, slot, capacity?}` β€” publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first Β· `?from=&to=` inclusive `YYYY-MM-DD` range Β· paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` β€” the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` β€” add a dish (≀ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` β€” record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` β€” take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first Β· paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included Β· paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent β€” cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` β€” mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu Β· paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history Β· `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day Β· paged Β· own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` β€” record money received; **admin only**, appends a `credit` line |\\n| POST | `/payments/plans` | manager | `{name, installments}` β€” write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it β€” its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (≀ 200) β€” place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first Β· paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` β€” record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` β€” hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` β€” undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines β€” charges, payments, refunds, reversals β€” newest first Β· paged Β· own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |\\n| POST | `/chatbot/threads` | student | `{title?}` β€” start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first Β· paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` β€” rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first β€” user and assistant rows alike Β· paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≀ `max_chatbot_message_len`) β€” send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` β€” nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β€” or one `error` β€” and close; an already-finished answer replays (see \\"Chatbot\\") |\\n| POST | `/boards` | student | `{title, participant_ids?}` β€” open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first Β· paged |\\n| GET | `/boards/{id}` | student | One board β€” a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |\\n\\n`status` must be one of the school's attendance statuses (`GET /settings`);\\nthe core four `present | absent | late | excused` always exist, plus whatever\\nthe school added.\\n`kind` must be one of the school's exam kinds (`GET /settings`; defaults:\\n`homework | quiz | midterm | final | project | oral`). The kind carries the\\nexam's weight in the course average β€” an integer `1`–`100` set per **kind** in\\nsettings (defaults all `1`), resolved when a report is read; an exam whose\\nkind was later removed from settings counts with weight `1`.\\nA course may carry a `term_id` (`null` = unassigned); on `PATCH\\n/courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`\\nclears it.\\n`role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are\\nULIDs. `parent` accounts are made by an admin (register as `student`, then\\n`PATCH /users/{id}/role`) and observe only the students an admin tied to them\\nβ€” see \\"Roles & access control\\".\\nAn exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row,\\nnever in a `note`. Students never grade anyone β€” grading is teacher+ with\\ncourse-management rights, and the target must be enrolled in the exam's course;\\na student reads just their own mark via `GET /exams/{id}/result`.\\nA course average is `Ξ£(markΓ—weight) / Ξ£(weight)` over the student's **graded**\\nexams in that course (`null` while nothing is graded β€” ungraded exams are\\nskipped, not zeroed). The overall average is the plain mean of the non-null\\ncourse averages. Unenrolling keeps result rows: the marks drop out of the\\nreport until re-enrollment, but stay visible on the exam itself. A course\\nwith anyone still on its roster refuses deletion (`409`) β€” empty the roster\\nfirst; once empty, deleting it cascades its exams, their results, its\\nsessions and roll call, and its subjects.\\nA **subject** is one topic of a course's curriculum (`name` ≀ 200 chars,\\noptional `description` ≀ 2000): every exam question carries a mandatory\\n`subject_id` naming one of *its own course's* subjects (an unknown or\\nforeign-course subject is a `400`), so exam content is always attributable to\\na topic. A subject's course link is fixed at creation, and a subject still\\nreferenced by questions refuses deletion with a `409` β€” re-tag (PATCH the\\nquestions' `subject_id`) or delete those questions first. Questions written\\nbefore subjects existed are **destroyed on boot** (answers first) β€” the clean\\nbreak instead of inventing a placeholder topic.\\nEvent `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both\\nare given, `ends_at` must not precede `starts_at`, and neither may be set in\\nthe past (else `400`). On `PATCH`, an omitted time keeps its value and an\\nexplicit `null` clears it.\\nAn event's `audience` is a tagged object β€” `{\\"kind\\": \\"school\\"}` (the default),\\n`{\\"kind\\": \\"role\\", \\"role\\": \\"student\\"}` (that exact role, no \\"and above\\"),\\n`{\\"kind\\": \\"course\\", \\"course\\": \\"<id>\\"}` (the course's current enrollment), or\\n`{\\"kind\\": \\"registration\\", \\"capacity\\": 30}` (a signup list; `capacity` optional,\\n`null` = unlimited) β€” and is the event's **expected-attendee roster**, resolved\\nlive at read time: role changes, (un)enrollments, and (un)registrations move\\npeople in and out by themselves. It never hides the event β€” everyone sees every\\nevent. Only audience members can be marked; `GET /events/{id}/roster` joins the\\nlive roster with the recorded marks (`status: null` = expected but never\\nmarked). Attendance rows for people a later audience edit (or unenrollment /\\nrole change) dropped stay stored and listed under `/events/{id}/attendance`,\\nbut leave the roster report.\\nA registration list fills through `POST /events/{id}/register`: teachers place\\nstudents (a student never registers, not even themselves) and take seats only\\nfor themselves β€” registering another staff member is refused. Re-registering\\nsomeone is a no-op, a full list is a `409`, and the list freezes the moment\\nthe event starts β€” or, when only `ends_at` is set (a pure signup deadline),\\nthe moment it passes (register and unregister both). Signup rows survive an\\naudience switch inertly and resurface if the event returns to the registration\\nkind; deleting the event deletes them. Pre-existing hand-picked (`users`)\\naudiences convert on boot: each listed user becomes a signup row credited to\\nthe event's creator, and the audience becomes an uncapped registration list.\\nReading a child collection of a missing parent (`/events/{id}/attendance`,\\n`/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`,\\n`/courses/{id}/sessions`, `/courses/{id}/subjects`, `/courses/{id}/homework`,\\n`/homework/{id}/submissions`, `/sessions/{id}/attendance`) is a `404`, not an\\nempty list.\\nPersonal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same\\noptional set on every account, whatever the role, and is `null` until filled\\nin. On `PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) each field\\nis independent: omitted (or `null`) keeps the current value, an empty string\\n`\\"\\"` clears it, anything else is validated β€” email must look like\\n`name@example.com`, phone is 7–15 digits with an optional `+` and cosmetic\\nseparators, `birth_date` is a real `YYYY-MM-DD` calendar date not in the\\nfuture. Names allow unicode; usernames are strict: lowercase letters and\\ndigits plus non-consecutive interior `.`, `_`, `-` separators, starting and\\nending with a letter or digit (3–32 chars). Staff-looking names (`admin`,\\n`administrator`, `root`, `support`, `system`, `moderator`, `staff`) are\\nrejected at `/auth/register` only β€” the `ADMIN_USERNAME` bootstrap may still\\nseed them.\\nUI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`,\\n`palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the\\nsame account row and come back on every user response (`/auth/me` included).\\n`PATCH /users/me/preferences` (or the admin `PATCH /users/{id}/preferences`)\\nuses the same field semantics as the profile patch: omitted keeps, `\\"\\"` clears\\nback to `null` (\\"never chose\\" β€” the client then follows the device\\npreference, or its own default accent), anything else must be valid or the\\nwhole patch is a `400`. `palette_color` is the one **open** set: any valid hex\\npasses (mixed case in, stored and returned lowercase), so a new frontend\\npalette needs no backend change β€” `/limits` publishes its pattern rather than a\\nlist of colors.", "source": "README.md"}, {"id": "appointments", "title": "Appointments", "body": "Office hours and parent-teacher conferences, booked instead of arranged by\\nmessage. A teacher+ **publishes availability**; a student or a parent\\n**books** one of those windows with a reason; the teacher **decides**. Two\\nrows carry it: an `appointment_slot` (the offer) and an `appointment` (the\\nbooking sitting on it) β€” a slot is never \\"half booked\\", and a refused request\\nstays readable instead of vanishing.\\n\\nA slot is a window on one teacher's calendar: `starts_at`/`ends_at` (unix\\nmilliseconds, `starts_at` strictly before `ends_at`, neither in the past β€” the\\nusual 60-second grace) plus an optional `note` (≀ 500 chars) shown to\\nrequesters (\\"office hours\\", \\"veli gΓΆrüşmesi\\"). Windows are **half-open**, so\\n10:00–10:30 and 10:30–11:00 are two slots, not a collision. A window that *does*\\noverlap one the same teacher has already published is refused with a `409` β€” the\\nguard is **per-teacher** (two teachers may hold office hours at the same hour)\\nand boundary-touching windows are legal by that same half-open rule, which is\\nhow an hour gets carved into back-to-back slots. `POST\\n/appointments/slots` publishes on the caller's *own* calendar (managers and\\nadmins included β€” the calendar always belongs to whoever posted) and **always\\nanswers an array**: one element for a one-off, one per occurrence for a\\nrecurring publish.\\n\\n`repeat_weekly: true` with an `until` expands the same window every seven days\\nup to and including `until`, server-side, into **concrete rows** sharing a\\n`series` id β€” no recurrence rule is stored, so one week can be cancelled\\nwithout touching the rest. At most 52 occurrences (a year); asking for more is\\na `400`, as is `repeat_weekly` without `until` β€” and so is a window sitting so\\nfar ahead that shifting it by a week would run off the end of representable\\ntime (the shift is checked, never wrapped: a wrapped end would land *before*\\nits start, and an inverted window can never overlap anything, which would\\nquietly disable the double-booking guard). A recurring publish is\\n**all-or-nothing**: every occurrence is checked β€” against the slots already\\nstored *and* against the earlier occurrences of the same batch, which a window\\nlonger than a week overlaps itself β€” before a single row is written, so a\\nmid-series collision answers `409` and leaves no stray weeks behind. Delete one\\noccurrence with\\n`DELETE /appointments/slots/{id}`, the whole publish with `DELETE\\n/appointments/slots/series/{series}`.\\n\\n```json\\nPOST /appointments/slots\\n{ \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"repeat_weekly\\": true, \\"until\\": 1901209600000 }\\n\\n201 [ { \\"id\\": \\"01J8…A\\", \\"teacher\\": {\\"id\\": \\"01J8…T\\", \\"username\\": \\"ayse\\",\\n \\"display_name\\": \\"Ayşe YΔ±lmaz\\"},\\n \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"series\\": \\"01J8…S\\", \\"created_at\\": 1899… },\\n { \\"id\\": \\"01J8…B\\", …, \\"starts_at\\": 1900604800000, \\"series\\": \\"01J8…S\\" } ]\\n```\\n\\n`GET /appointments/slots` is two lists behind one path: a teacher+ reads\\n**their own** calendar, past occurrences included; everyone else reads the\\n**bookable** calendar β€” future slots only, earliest first. A teacher demoted\\nafter publishing leaves **inert** slots: their live role is re-read, so those\\nslots drop out of the bookable list and booking one is refused with a `409`.\\nThe list does not say whether a slot is already taken β€” booking a taken one\\nanswers `409`.\\n\\n**Booking.** `POST /appointments` (`{slot, reason}` β€” the reason is required,\\n≀ 1000 chars) is for **students and parents only**; staff arrange between\\nthemselves off this API. A parent books for *themselves* β€” this is the\\nparent-teacher conference, not a booking on behalf of a child. The request\\nlands `pending`, always: publishing availability is not consent to a\\nparticular person and a particular topic, so approve/reject still applies.\\n\\nA booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two\\nare **live** and hold the slot; rejecting or cancelling frees it for someone\\nelse immediately (the slot carries an `occupied` counter, taken by a booking\\nand handed back in the same transaction as the reject or cancel that settles\\nit, so the seat is decided by the database rather than by a count two\\nconcurrent bookings can both read as free). The decisions:\\n\\n- `PATCH /{id}/approve` β€” the slot's teacher (or manager+) confirms. Refused\\n (`409`) when the effective window has already started.\\n- `PATCH /{id}/reject` β€” turns it down; the slot frees up.\\n- `PATCH /{id}/cancel` β€” **the requester only**, from either live state.\\n Anyone else is a `403`, the slot's teacher and a manager/admin included (the\\n guard compares ids, not roles). A teacher ends a booking by **rejecting** it\\n while it is `pending`, and an approved one by counter-proposing another time\\n (`/reschedule`, which sends it back to `pending`) and then rejecting it β€” or\\n simply by rescheduling to a time that works. Refused (`409`) once the\\n meeting's window has started: a\\n meeting that already began is history, not a plan. The guard sits in the\\n domain's `cancel` itself, on a fresh read compared-and-set into the row, so\\n every way of cancelling β€” the decline below included β€” inherits it.\\n- `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) β€” the teacher\\n **counter-proposes**. The times land on the *same* row as\\n `proposed_starts_at`/`proposed_ends_at`, the status goes back to `pending`\\n and `decided_by` clears, because leaving it `approved` would silently move a\\n confirmed appointment. The slot stays held meanwhile. A window that has\\n already opened is refused (`409`): the 60-second grace on the times is for\\n clock skew, not for proposing into a meeting already underway β€” one nobody\\n could then cancel.\\n- `PATCH /{id}/reschedule/accept` β€” the **requester** only: this *is* approval\\n at the new time, so the overlap guard runs again β€” and so does the\\n already-started guard (`409`). Agreeing to a window that has begun does not\\n help: the meeting could never be cancelled. The booking stays `pending`, so\\n the teacher just proposes a time that can still happen.\\n- `PATCH /{id}/reschedule/decline` β€” the requester only, and it **cancels the\\n booking**: the proposal replaced the time that was asked for, so there is\\n nothing to fall back to. The row stays readable as `cancelled` with the\\n refused proposal still on it β€” book another slot instead. Declining *is* a\\n cancel, so it answers to the cancel deadline too (`409` once the effective\\n window has started).\\n\\n**Who settled it, and why.** Every settled booking carries its own audit trail\\non the row: `decided_by` (who approved or rejected β€” cleared again by a\\ncounter-proposal), `cancelled_by` (who called it off, stamped by `cancel` and by\\na declined counter-proposal), plus the optional free text that came with the\\ndecision β€” `reject_reason` on `PATCH /{id}/reject` and `cancel_reason` on\\n`PATCH /{id}/cancel` and `/reschedule/decline`. Both reasons are optional: the\\nwhole body may be omitted, a blank one records nothing (`null`), and a present\\none is validated like the booking's own reason (≀ 1000 chars, `400` past that)\\nbefore it reaches the row. They are **not public**: bookings are only ever\\nrendered to the person who requested them and to the slot's teacher (a\\nmanager/admin acting on one by id sees the response to their own call), so\\n\\"couldn't make it, sorry\\" goes no further than the two people it concerns. Rows\\nwritten before these fields existed simply read back `null`.\\n\\nA booking's effective window is the accepted counter-proposal when there is\\none and the slot's own window otherwise; that is what `starts_at`/`ends_at` on\\nan `AppointmentResponse` report, and what the cancel deadline is judged on.\\n\\n**No double-booking.** Two `approved` meetings may never overlap for the same\\nteacher *or* the same requester (`409`). The guard runs at approval β€” the\\nmoment anyone is actually committed β€” and again on accepting a counter-proposal,\\nbecause the time moved. Approval also refuses (`409`) an **effective window\\nthat has already started** (the proposal's when one stands, the slot's\\notherwise), for the same reason booking one is refused. Requesting is checked more loosely: a booking is\\nrefused up front only when the slot's window has already started (booking it\\nwould create a meeting `cancel` refuses to undo β€” the 60-second publish grace\\nis for clock skew, not for booking into the past), when the slot is already\\ntaken, or when the *requester* is already committed at that hour; a clash on the teacher's side is theirs to\\nresolve when they decide, since refusing a request against a window they\\nthemselves published would only confuse. Touching windows never conflict.\\n\\nDeletion follows the same rule as the rest of the codebase: a slot carrying a\\nlive (pending or approved) booking refuses to go (`409`) β€” reject or cancel\\nthat booking first β€” and a series delete is all-or-nothing, `409` if *any*\\noccurrence still carries one, so the person waiting is dealt with rather than\\nleft stranded on a stray week. Settled (rejected/cancelled) bookings cascade\\naway with their slot.\\n\\n`GET /appointments` is likewise two lists: a teacher+ sees the bookings aimed\\nat their own slots (their request inbox), everyone else the ones they\\nrequested, newest first, paged. Managers and admins read their own inbox here\\ntoo β€” they may still decide any booking by id.", "source": "README.md"}, {"id": "messaging", "title": "Messaging", "body": "One-to-one, mail-style (subject + body + an optional free-text `label` the UI\\nrenders as a badge β€” \\"EtΓΌt\\", \\"SΔ±nav\\"; no threads): any user writes to any\\nuser β€” student to teacher, parent to teacher, teacher to student; only\\nmessaging yourself is refused. A single stored message serves both parties,\\nbut each **owns their copy independently**: the recipient's moves through\\n`inbox` β†’ `archive`/`trash` and carries the `read` flag (the sender sees it\\nas a read receipt); the sender's moves through `sent` β†’ `archive`/`trash`. Filing or\\ndeleting your copy never changes the other side's view.\\n\\nEvery copy remembers where it was filed from, so it can go back there. Moving\\ninto `archive`/`trash` stamps the folder you left onto the copy's\\n`previous_folder`, and restoring is a `PATCH` of `folder` back to that value:\\nan inbox message you archive and then trash returns to `archive`, and from\\nthere to `inbox`. Two folders are never stamped β€” the trash itself (pulling a\\ncopy out of the trash must not leave it pointing back at the discard pile) and\\nthe folder you are already in β€” and moving back to `inbox`/`sent` clears the\\nstamp. `previous_folder` is therefore `null` for any copy sitting in its home\\nfolder, and for copies filed before the field existed; both mean \\"restore to\\n`inbox`\\" (`sent` for the sender's copy).\\n\\nListing is per folder β€” `GET /messages?folder=` with `inbox` (default),\\n`sent`, `archive`, or `trash` (trash shows both received and sent copies you\\ntrashed) β€” newest first, paged, with sender/recipient rendered as person refs\\nplus their role. `?read=false` narrows to unread (`true` to read), and since\\n`total` counts the filtered view, `?folder=inbox&read=false&limit=1` is the\\none-row unread-badge query. `PATCH /messages/{id}` flips `read` (recipient only) or\\nmoves your copy (`folder`), restoring included. `DELETE` is\\npermanent, allowed only while your copy sits in the trash (`409` otherwise),\\nand physically removes the row once both sides have deleted theirs. Replying\\nis just sending a new message back β€” the frontend prefixes the subject if it\\nwants an `Re:`.", "source": "README.md"}, {"id": "question-pool", "title": "Question pool", "body": "Students get stuck; the pool is where the school unsticks them β€” with a\\nmoderation gate so nothing unreviewed goes school-wide. `POST /questions`\\n(students only, exact role) creates the question `pending`: only the asker\\nand teacher+ can see it (anyone else gets a `404`, not a `403` β€” a pending\\nquestion's existence is nobody else's business), and `GET\\n/questions?status=pending` is a teacher's approval queue. The asker may\\nattach **one photo** of the problem (`POST /questions/{id}/image`,\\n`multipart/form-data` with a `file` part β€” raster types only, no SVG, ≀ the\\nschool's `max_file_bytes`), replace it, or remove it β€” while pending only.\\n\\n`POST /questions/{id}/approve` (teacher+) publishes it: the question becomes\\nreadable by every signed-in user above `parent`, and its content β€” title,\\nbody, photo β€” **freezes**, because an edit after approval would bypass the\\nmoderation that just happened. There is no rejected state and no edit\\nendpoint: to fix a typo the asker deletes and re-asks; to reject, a teacher+\\ndeletes. Approving twice is a `409`; the response records `approved_by`.\\n\\nAnyone in the school (student through admin β€” not parents) may then offer a\\n**solution**: `POST /questions/{id}/solutions` with a text body, listed\\noldest-first like a discussion thread (`GET`, paged). Solutions are the\\nunmoderated half of the pool, so nothing about them ever freezes: the author\\nβ€” and only the author, teacher+ included out β€” may edit the body (`PATCH\\n/questions/{id}/solutions/{sid}`) and attach one **photo** of the worked\\nsteps (`POST /questions/{id}/solutions/{sid}/image`, same raster-only rules\\nand `max_file_bytes` cap as the question's photo), replace it, or remove it,\\nat any time; moderation stays delete-only β€” a teacher+ removes a bad\\nsolution, never rewrites someone else's words. A solution is deleted by its\\nauthor or by teacher+, its photo blob going with it; deleting a question β€”\\nasker withdrawing, or teacher+ moderating β€” takes its solutions and every\\nphoto blob (its own and its solutions') with it. Each question row reports\\nits `solution_count`, and questions and solutions embed their people as\\nperson refs (`{id, username, display_name}`), so the UI never shows a raw\\nULID.", "source": "README.md"}, {"id": "per-school-policy-settings-terms", "title": "Per-school policy (settings & terms)", "body": "Every school runs differently; the parts that vary are data, not code. One\\neditable `settings` singleton (`GET /settings` for any signed-in user,\\n`PATCH /settings` for manager+) carries seven knobs:\\n\\n- **`exam_kinds`** β€” the accepted `kind` values for new exams, each an\\n object `{name, weight}`. The weight (`1`–`100`) is how many times an exam\\n of that kind counts into its course average β€” weighting is school policy,\\n set once per kind, never per exam. Defaults to `homework, quiz, midterm,\\n final, project, oral`, all weighing `1` (a plain average); replace the\\n list with whatever the school grades and weighs (`{\\"name\\": \\"final\\",\\n \\"weight\\": 3}`, …). Reports resolve weights live: editing a weight\\n re-weights every exam of that kind at once. For the same reason a kind\\n whose exams already carry marks cannot be removed from the list (`409`):\\n those marks would silently re-weight. An unmarked kind leaves freely, and\\n an exam keeping a since-removed kind counts with weight `1` β€” but it can no\\n longer be graded (`409`) until the school offers that kind again, which is\\n what keeps \\"a marked kind cannot be removed\\" true from both ends. The same\\n rule pointed at one exam: an exam that already carries marks keeps its\\n `kind` (`PATCH /exams/{id}` answers `409`), because re-pointing it would\\n re-weight those marks just as silently.\\n- **`attendance_statuses`** β€” what attendance marking accepts. The core four\\n (`present`, `absent`, `late`, `excused`) are mandatory because the\\n attendance rate is defined over them (`(present+late) /\\n (present+absent+late)`); school extras (say `online`) are **rate-neutral**\\n and tally under `custom` in the attendance reports.\\n- **`grade_bands`** β€” how numeric marks display: a list of `{min, label}`\\n bands (`85 β†’ \\"AA\\"`, `50 β†’ \\"CC\\"`, …). One band must start at `0` so every\\n mark maps; an empty list (the default) means numeric-only. Storage and\\n averaging stay `0`–`100` forever β€” bands only add `grade`,\\n `average_grade`, and `overall_grade` labels to the mark report, so a school\\n can switch display scales without touching a single stored mark.\\n- **`max_file_bytes`** β€” the per-file size cap for uploads (note files and\\n exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;\\n a server hard cap β€” uploads buffer in memory), default `5242880` (5 MiB).\\n Checked at upload time only: lowering it never touches already-stored files.\\n- **`chatbot_history_turns`** β€” how many prior **messages** of a thread the\\n chatbot is given as context, `1`–`50` (default `10`). The unit is messages,\\n not exchanges: a question and its answer are two, so the default remembers\\n five question/answer pairs. Every one of them is re-sent on every reply, so\\n the number is both what the bot remembers and what each answer costs.\\n- **`max_chatbot_threads`** β€” how many chatbot threads one user may\\n keep, `1`–`500` (default `50`); at the cap the user deletes an old one\\n first. Storage protection, not a usage quota β€” that is the per-minute\\n message limit.\\n- **`max_chatbot_message_len`** β€” character limit on one chat message,\\n `100`–`8000` (default `4000`); the ceiling is a server hard cap, because\\n the message and its history must fit one bridge frame.\\n\\nA `PATCH` replaces only the fields it carries, each wholesale, and validation\\nis all-or-nothing. Concurrent edits are safe: each save applies only if the\\npolicy still matches the snapshot it merged from (retrying over the fresh row\\notherwise), so two managers patching different fields both land instead of\\nthe later write silently reverting the earlier one. Editing a list never\\nrewrites history: an exam keeps its retired kind, a roll-call row keeps its\\nretired status β€” only **new writes** are held to the current lists (which is\\nwhy grading an exam whose kind has left the list is refused).\\n\\nThe kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see \\"Food program: menus, dishes, bookings & the ledger\\").\\n\\nAcademic structure is data too. **Terms** (`/terms`) model whatever calendar\\nthe school runs β€” semester, trimester, quarter systems are just rows with a\\nname and a date range. Courses may link to one via `term_id` (nullable), and\\ndeleting a term is refused with a `409` while any course still links to it β€”\\nunlink those courses (`PATCH /courses/{id}` with `\\"term_id\\": null`) or delete\\nthem first, so the calendar never disappears under them. Term dates may lie in the past,\\ndeliberately: a school adopting the app mid-year backfills its calendar β€”\\nunlike exam/lesson/event times, which reject backdating.\\n\\nWhat stays fixed is deliberate too: the four roles, the `0`–`100` mark scale,\\nvalidation bounds, and the UTC time policy are invariants, not preferences\\n(rename role labels in the frontend if a school says \\"principal\\" instead of\\n\\"manager\\"). Deployment knobs (ports, rate limits, admin seed, CORS) remain\\nenvironment variables β€” the model is **one school per deployment**, which\\nkeeps every school's data physically isolated.", "source": "README.md"}, {"id": "food-program-menus-dishes-bookings-attendance-the-ledger", "title": "Food program: menus, dishes, bookings, attendance & the ledger", "body": "The school publishes **one menu per calendar day and meal slot** (`POST\\n/meals/menus`). Two shapes there are deliberate:\\n\\n- **`date` is text**, `YYYY-MM-DD`, not a timestamp. \\"One menu per day and\\n slot\\" is an equality test on the school's own day, and a midnight-in-millis\\n day is only unique for one timezone. Fixed-width and zero-padded, so the\\n text sorts chronologically β€” which is what the inclusive `?from=&to=` range\\n filter and the newest-day-first ordering are built on.\\n- **`slot` is a snapshot**, not a link into settings. It must be one of the\\n school's `meal_slots` (`GET /settings`) *when the menu is written*, and it\\n is stored as text β€” so retiring a slot later never rewrites a menu already\\n published under it. The slot's `serving_minute` is *not* snapshotted: the\\n booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any\\n menu was published for cannot be removed from the list (`409`), same\\n contract exam kinds have with graded exams.\\n\\nThe day+slot pair is unique: a second publish for the same meal answers `409`\\nβ€” edit the first one instead. Only `capacity` is patchable (`null` = uncapped)\\nβ€” `date` and `slot` are immutable, because a menu on another day is another\\nmenu.\\n\\n**Dishes** hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, then\\n`PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional\\ndescription (blank or `null` clears it), dietary `tags` drawn from the\\nschool's `dietary_tags` list β€” an unknown tag is a `400`, never a stored\\nstring β€” and a `price_minor`.\\n\\n### Dietary profiles and conflicts\\n\\nA student carries a **dietary profile**: a list of tags plus a free-text note\\nfor the kitchen, one row per student (the record key *is* the student's id).\\nThe tags come from the *same* `dietary_tags` list a dish is tagged from β€”\\nthere is deliberately no second vocabulary, because one shared list is exactly\\nwhat makes \\"is this dish a problem for this student\\" answerable as a set\\nintersection, without the backend knowing any nutrition.\\n\\nWriting it is **manager+** (`PATCH /meals/profiles/{user}`, first write\\ncreates the row). A student does *not* edit their own allergen list: it is a\\nsafety record the school keeps on their behalf, and a mistyped β€” or quietly\\nremoved β€” allergy would otherwise reach the kitchen with the school's\\nauthority behind it. Reading is `GET /meals/profiles/me`, or\\n`GET /meals/profiles/{user}` under the usual per-student gate (own id always,\\notherwise teacher+ or a parent link). A student who was never recorded reads\\nback as an *empty* profile rather than a `404` β€” \\"nothing known\\" is an answer.\\n\\nEvery dish a menu read returns therefore carries a **`conflicts`** list: the\\nintersection of that dish's `tags` with the **calling user's** profile tags.\\nIt is empty when the two do not overlap, and empty for every reader without a\\nprofile β€” a manager reading a menu sees `conflicts: []`, which is correct and\\nnot a bug (the field answers \\"may *I* eat this\\", and there is no \\"conflicts\\nfor student X\\" parameter). The caller's profile is loaded **once per request**,\\nnot per dish, so the menu list stays at its fixed query count no matter how\\nmany menus or dishes the page holds.\\n\\n**Money is minor units** (kuruş) as an integer, at every layer: `4550` is\\n45,50 β‚Ί. This API never speaks decimals or floats about money, so no rounding\\nis ever introduced by transport or by a client's JSON number parser.\\n\\nReads are open to every authenticated user β€” a student has to see what is\\nbeing served β€” and every write is manager+. Deleting a menu takes its dishes\\nwith it: a dish has no meaning apart from the menu it was published on.\\n\\n**Bookings** are seats on a published menu (`POST\\n/meals/menus/{id}/bookings`). One row per (menu, student), keyed by a\\ndeterministic composite id, so booking twice is the same seat and never a\\nsecond one. A **student books only for themselves**; a **parent books for a\\nstudent they hold a link to** β€” the one write a `parent_link` authorises, since\\npaying for lunch is a parent's job. Nobody else books through this route: a\\nteacher or manager ordering a child's lunch is a `403`.\\n\\n- **Cancelling is a status flip, not a delete** (`DELETE\\n /meals/bookings/{bid}` answers `200` with the flipped row): the row survives\\n as `cancelled` with a `cancelled_at` stamp, so a freed seat stays auditable\\n against the money it moved. Only `booked` rows count against `capacity`,\\n which is what genuinely frees the seat β€” and re-booking is the same row\\n flipped back. The call is **idempotent**: cancelling an already-cancelled\\n seat answers `200` with the row as it stands *and replays the refund*, so a\\n cancel cut short between the flip and the reversal (the tab closed, a proxy\\n timed out) is recovered by sending it again. Refusing it as a `409` β€” as it\\n once did β€” made that state permanent: no route could append the missing\\n reversal, and the student stayed billed for a seat they no longer held.\\n- **The capacity check is serialized in-process.** Counting rows and then\\n writing one is write-skew: SurrealDB does not conflict-check a cross-record\\n count against a concurrent insert, so 24 students racing for 3 seats would\\n otherwise all pass the count. The whole check-then-write runs under the same\\n lock a menu publish takes, and the cap is re-read inside it.\\n- **One cutoff closes both ends.** Within the school's\\n `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new\\n booking nor a cancellation lands (`409`) β€” the kitchen's headcount has to\\n settle at some point. `null` (the default) means no cutoff at all. The\\n cutoff is measured back from the menu's `date` **plus the slot's\\n `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served\\n at `720` closes at 10:00 UTC that morning, not at 22:00 the night before.\\n **That minute is UTC**: `date` carries no timezone and the backend stores no\\n school timezone β€” deliberately, it is a rejected feature β€” so a UTC+3 school\\n enters `540` (09:00 UTC) for a meal served at noon locally. A slot with no\\n `serving_minute` falls back to **midnight UTC starting the meal's day**, the\\n behaviour every booking had before the field existed; the booking is never\\n refused for want of a serving time.\\n- **The serving time is read live, not snapshotted onto the menu.** The cutoff\\n minutes are already read live, so freezing the other half of the same\\n deadline would make one policy edit apply and its twin not; a kitchen that\\n moves lunch an hour later wants today's menus to move with it. The menu\\n still snapshots the slot *name* (that is what keeps a retired slot's history\\n readable), so a menu whose slot has since left the list simply has no\\n serving time and falls back to midnight UTC.\\n- A menu somebody still holds a seat on **cannot be unpublished** (`409`) β€”\\n cancel the bookings first, so nothing is left pointing at a deleted meal.\\n\\n`GET /meals/bookings/me` is the caller's own list: the seats held *for* them\\nplus, for a parent, the seats held for every student they **currently** hold a\\nlink to β€” so a parent's list is their children's meals. The links are re-read\\non every call rather than trusted from the booking's `booked_by` stamp: an\\nunlinked parent stops seeing the child's seats at once, including the ones\\nthey booked and paid for themselves, exactly like every other parent read. `GET /meals/menus/{id}/bookings` is the kitchen's list for\\none menu (manager+), cancelled rows included so the changes are visible.\\n\\n### Meal attendance\\n\\nWhoever stands at the canteen door records who actually ate:\\n`POST /meals/menus/{id}/attendance` with `{student_id, status}`, teacher+ (a\\nstudent never marks, not even themselves). The status is the fixed pair\\n`served` / `missed` β€” deliberately **not** the school's editable\\n`attendance_statuses`, since a canteen line has no \\"late\\" or \\"excused\\", and one\\nlist meaning two things would let a school change one by editing the other.\\nOne row per (menu, student) keyed by a composite id, so a correction re-marks\\nthe same row instead of stacking a second one.\\n\\n**Attendance has zero billing effect.** Booking is the sole charge trigger, so\\na student who booked and did not eat still pays β€” the kitchen bought the food.\\nThere is no no-show penalty, no refund-on-missed, and no auto-reversal:\\nnothing under `meal_attendance` writes to the ledger. A walk-in with no live\\nbooking *can* be marked `served` (the record is operationally true) and is\\nlikewise not charged for it β€” charging there would be a ledger write. The\\ntarget only has to *exist*: a canteen also feeds staff, so any user may be\\nmarked, not only a student. A mark is a record of what happened, not a check\\nof who was entitled, and since it moves no money it costs nobody anything.\\n\\n`GET /meals/menus/{id}/attendance` is the per-menu list (teacher+), and\\n`GET /meals/attendance/{user}` is one student's history, narrowable with\\n`?from=&to=` β€” inclusive `YYYY-MM-DD` bounds compared against the *menu's*\\nday, a lexical compare that is chronological for that format. Same gate as the\\nbalance and the ledger: the caller's own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`meal_ledger`): one line per `charge`,\\n`credit`, or `reversal`, every field `READONLY`, and **no code path anywhere\\nthat updates or deletes one**. A ledger line that can be edited or dropped\\nsilently rewrites a student's financial history with no trace of the rewrite β€”\\nthis is the one genuinely irreversible part of the food program, so a mistake\\nis corrected by appending the opposing line, which leaves both the mistake and\\nthe correction visible.\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer.\\nA *negative* balance means the student owes the school; a positive one is\\nmoney on account. Amounts are stored positive; the sign lives in the `kind`.\\n\\n- **Booking is what charges, at a price snapshot.** The menu's dishes are\\n summed the moment the seat is taken and that number is frozen onto the\\n charge. Editing a dish's price afterwards moves no existing charge β€” what a\\n student owes is what the menu cost the day they booked. The price is\\n snapshotted *before* the seat is given, so a menu that cannot be charged\\n refuses the booking rather than leaving a booked-but-unbilled row (`400`,\\n when the dishes sum past 10 000 000). A free menu writes no line at all β€”\\n but the booking row records that it *was* free, so \\"free when taken\\" is\\n never confused with \\"not billed yet\\": pricing the menu afterwards leaves\\n every seat already taken on it free.\\n- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its\\n money move together under one in-process lock, and the ledger id is derived\\n from the seat plus how many times it has been taken β€” so eight simultaneous\\n `POST`s of one seat write one charge, a retried cancel refunds once, and a\\n write that failed halfway heals when the request is repeated. Booking the\\n same seat twice bills once because the *identity* is the same, never\\n because a scan happened to see the first charge in time.\\n- **Cancelling appends a `reversal`** for the charge's exact amount, with\\n `source` pointing at the charge it undoes. The charge row itself stays. A\\n cancel past the cutoff is already a `409`, so a reversal only ever follows a\\n legal cancel β€” and repeating a cancel replays the reversal, which is what\\n makes the refund recoverable rather than a one-shot the network can lose.\\n Re-booking afterwards is a **fresh** charge at the then-current price.\\n- **The price snapshot is taken under the booking lock**, and dish\\n create/edit/delete take that same lock. Taken outside it, a dish added\\n between the sum and the seat would be frozen onto the row as \\"the menu was\\n free then\\" β€” and nothing heals it, since a seat already held is returned\\n as-is, never re-priced.\\n- **A no-show still pays.** Meal attendance has zero billing effect β€” nothing\\n in the ledger reads or writes it. The seat was reserved and the food was\\n cooked; there is no no-show penalty and no no-show refund.\\n- **`POST /meals/credits` is admin-only**, not manager: writing down cash\\n received is the highest-trust action in the app. It appends a `credit` for a\\n student with a positive `amount_minor` (≀ 10 000 000), an optional `method`\\n (\\"cash\\", \\"havale\\", …) and `note`, and records the admin as `recorded_by`.\\n There is no payment gateway and no card data, ever. An over-credit is\\n corrected with a compensating line, never a fix-up.\\n\\n`GET /meals/balance/me` is the caller's own balance. `GET\\n/meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line\\nfirst) read a student's: your own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student. A charge's `source` is the\\nbooking id it came from, a reversal's is the charge line it reverses, and a\\ncredit has none.", "source": "README.md"}, {"id": "payments-fee-plans-assignment-the-fee-ledger", "title": "Payments: fee plans, assignment & the fee ledger", "body": "School fees live in their own tables (`fee_plan`, `fee_plan_assignment`,\\n`payment_ledger`) and their own balance. **Meal money is separate** β€” two\\nledgers, two balances, and no route folds one into the other: what a family\\nowes the canteen and what it owes the school are different debts, and mixing\\nthem would make either statement unreadable.\\n\\nEvery write here is **manager+**. Reads are narrower than the other\\nper-student reports: the student themselves, a parent holding a live link to\\nthem, or manager+ β€” **a teacher gets a `403` on every `/payments` route**,\\nbecause what a family owes the school is not classroom information.\\n\\n### Fee plans and what turns them into money\\n\\nA **fee plan** (`POST /payments/plans`) is a name and 1 to 60 **installments**,\\neach `{amount_minor, due_at}` β€” minor units (kuruş) as an integer, and unix\\nmilliseconds. `due_at` **may be in the past**: a school adopting the app\\nmid-year assigns plans whose first installments were already due, so there is\\nno future-date rule here.\\n\\nWriting a plan bills nobody. **Assigning it does** (`POST\\n/payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call):\\nthat appends *every* installment as a `charge` line right away, each carrying\\nits own due date. There is no scheduler, no nightly sweep, and nothing that\\nwakes up when a date passes β€” the whole schedule is written once, and lateness\\nis read off it.\\n\\nAssignment is **replay-safe by identity**: the assignment row is keyed\\n(plan, student) and every charge it raises is keyed (plan, student,\\ninstallment), so re-assigning bills nothing a second time (that student comes\\nback `already_assigned`), and an assignment cut short after three of twelve\\ncharges landed completes itself when the call is simply repeated. Only\\nstudents carry a fee record, so any other target comes back `rejected` β€” one\\nbad id never loses the rest of the batch.\\n\\nA plan that has been assigned to anyone can no longer be edited or deleted\\n(`409`). Its charges are frozen copies of the installments as they stood, so\\nan edit would only make the plan and the money tell different stories β€” write\\na new plan instead.\\n\\nThat freeze is a **counter on the plan row** (`assignment_count`), incremented\\nin the *same transaction* as the assignment row it counts, and the edit and the\\ndelete are single-record conditional writes against it β€” the same shape as a\\nterm's `course_count`. It used to be a `SELECT` taken before the write, which a\\nconcurrent assign could land behind, leaving a plan edited *and* assigned, or\\ndeleted with a live assignment naming it. Now the two contend on one record: an\\nassign either freezes the plan first (and the edit or delete is a `409`) or\\narrives after it (and bills the edited plan β€” the installments a first\\nassignment charges are re-read from the *stored* plan at the instant it\\nfreezes, never from the copy the request first looked at). A plan deleted out\\nfrom under a running batch is `rejected` for that student on, in the same\\nper-student report as every other outcome β€” the students it already billed are\\nnever dropped from the answer. A `PATCH`\\ncarrying no field at all writes nothing, so it is not refused.\\n\\nBecause an assignment is never removed, the counter is only ever claimed and\\nnever released: once assigned, a plan stays frozen for good. Plans written\\nbefore the counter existed are seeded from their assignment rows at boot,\\nbefore the server accepts a request β€” an absent counter reads as zero, and a\\nzero would have re-opened every already-assigned plan on an existing volume.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`payment_ledger`), exactly like the\\nmeal one: every field `READONLY`, and **no code path anywhere that updates or\\ndeletes a line**. A ledger line that can be edited or dropped silently\\nrewrites a family's financial history with no trace of the rewrite, so a\\nmistake is corrected by appending the **opposing line**, which leaves both the\\nmistake and the correction visible.\\n\\nFour kinds, and the sign lives in the `kind` β€” amounts are always stored\\npositive:\\n\\n| Kind | Sign | What it records | `source` points at |\\n| ---------- | ---- | ------------------------------------------------ | ------------------ |\\n| `charge` | βˆ’1 | An installment billed by a plan assignment | the assignment |\\n| `credit` | +1 | Money received, against one named charge | the charge paid |\\n| `reversal` | +1 | A `charge` or `refund` entered in error, undone | the undone line |\\n| `refund` | βˆ’1 | Money handed back, against one named payment | the credit returned |\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge) - SUM(refund)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer. A\\n*negative* balance means the family owes the school; a positive one is money on\\naccount.\\n\\n- **A payment names the charge it settles.** `POST /payments/credits` takes\\n `{charge_id, amount_minor, method?, note?}`: allocation is *recorded*, never\\n inferred from a balance, so a statement can say which installment is still\\n open rather than only how much is outstanding. **Partial payments are the\\n norm** β€” several credits accumulate against one charge.\\n- **A refund names the payment it returns.** `POST /payments/refunds` takes\\n `{credit_id, …}`, partials allowed, capped by what that credit was worth.\\n This is also the **only** way a mistaken credit is corrected: a credit is\\n never reversed, so money leaving the school is always spelled the one way.\\n- **A retry is not a second payment β€” when the client says so.** Both routes\\n take an optional `request_key` (`[A-Za-z0-9-]`, 1 to 64 characters β€” `_` is\\n the separator inside a ledger id, so a key may not carry one). With\\n one, the line is keyed `<charge>_k_<key>` (a refund: `<credit>_kr_<key>`), so\\n a client retrying after a network timeout gets **the line the first attempt\\n wrote**, not a second charge on the family β€” idempotence by identity, the\\n same rule that keeps a replayed assignment from billing twice, never a \\"has\\n this been recorded yet?\\" scan two concurrent requests can both walk past. The\\n replay is answered **before** the over-payment cap is consulted, so a payment\\n that filled its charge to the penny still replays as itself instead of coming\\n back \\"already paid in full\\". Sending that key again with a **different**\\n `amount_minor` or a different target is a `409`, never the stored line: that\\n is a client bug, and a `201` would bury it. Omit the key and nothing changes\\n from before β€” two identical posts are two payments, which is exactly what a\\n desk taking the same amount twice means.\\n- **A reversal only undoes a `charge` or a `refund`**, for its exact amount and\\n nothing else (`400` on any other kind). It is keyed `<line>_r`, so a line has\\n at most one reversal however often the call is retried, and the reversed line\\n itself stays on the record beside it.\\n- **A refund frees the charge's room.** The cap on a payment is folded over the\\n target's whole source subtree, so refunding a payment gives that charge its\\n room back and the charge **can be paid again** β€” and reversing that refund\\n takes the room back with it. Money that came back out is not money the school\\n still holds.\\n- **The over-payment cap is not the database's.** The `409` past a charge's or\\n a credit's worth is a cross-record fold, which SurrealDB cannot enforce on\\n its own; it holds because the backend is one process and the fold, and the\\n append it authorizes, are taken under one lock. Should an over-payment ever\\n be recorded anyway it is not a crisis: this is human data entry at an office\\n desk, the outcome is an over-paid charge that is plainly visible in the\\n statement, and it is undone by appending a refund. Both lines are true\\n records of money that really arrived β€” refusing them would be the worse lie.\\n- **There is no payment gateway and no card data, ever**, and none is planned:\\n nothing here talks to a bank, a PSP, or a card network. `method` is free text\\n (\\"cash\\", \\"havale\\", …) describing how money that already arrived was handed\\n over, and `note` is whatever the office needs to remember (a receipt number,\\n say).\\n\\n### Statements, balances and `overdue`\\n\\n`GET /payments/ledger/{user}` is the raw lines, newest first, paged.\\n`GET /payments/statement/me` and `/payments/statement/{user}` are the\\n**per-charge rollup** (its rows paged by the usual opt-in `?limit=&offset=`,\\nin an `entries: {items, total, limit, offset}` envelope): one row per charge with its plan, the installment's\\namount and due date, what it collected, what went back out, what is still\\noutstanding, whether the charge itself was reversed (such a charge owes\\nnothing), and whether it is **`overdue`** β€” still owed, and its `due_at` has\\npassed.\\n\\nAll of that is folded from the raw lines **on every request and stored\\nnowhere**, `overdue` included. Paging windows the *returned rows* only, after\\nthat fold: `balance_minor` β€” and every row's own arithmetic β€” is identical on\\nevery page, because it is read from all of the student's lines either way. There is no overdue flag, no sweep that sets\\none, and no stored rollup: a stored rollup is a second version of the truth,\\nand the ledger is the first. `GET /payments/balance/me` and\\n`/payments/balance/{user}` are the same fold reduced to one number.", "source": "README.md"}, {"id": "exam-modes-attempts-retakes-rejoin-live-monitoring", "title": "Exam modes, attempts, retakes, rejoin & live monitoring", "body": "Preparing an exam is slow work, so an exam can be created as a **draft**\\n(`draft: true`): only the course's managers see it (to students it's a `404`\\nthat might as well not exist β€” lists, direct reads, and attempts all hide\\nit), nobody can sit it, and grading it is a `409`. The teacher builds the\\nquestions in peace and publishes with `PATCH /exams/{id}` `{\\"draft\\": false}`.\\nAn exam can go back into hiding the same way β€” but only while it has **no\\nattempts and no results**; after that, re-drafting is a `409` (students never\\nlose sight of an exam they've sat or been graded on). Existing exams (and\\nthose created without the flag) are published from the start.\\n\\nSeparately from drafts, a published exam without a `mode` (all schedule\\nfields `null`) is **offline-graded** β€” a paper exam whose marks are entered\\nby hand; students see it and their marks, but attempts on it are a `409`\\n(\\"nothing to sit\\"). Making an exam sittable means giving it a `mode`, as one\\nconsistent unit (validated together on create and after every `PATCH` merge):\\n\\n- `mode: \\"sync\\"` + `starts_at` + `ends_at` β€” everyone sits inside one window;\\n every attempt's deadline is `ends_at`.\\n- `mode: \\"async\\"` + `starts_at` + `ends_at` + `duration_ms` β€” each student\\n starts anywhere inside the window and gets\\n `min(started_at + duration_ms, ends_at)` as their personal deadline.\\n- `mode: \\"open\\"` β€” no window at all: students sit anytime. `duration_ms` is\\n *optional* β€” set it for a per-attempt countdown (`started_at +\\n duration_ms`), omit it for unlimited time (the attempt only ends by\\n submission).\\n- `duration_ms` is 1 minute to 24 hours wherever it appears, and for `async`\\n cannot exceed the `starts_at`..`ends_at` window (equal to it is fine).\\n `ends_at` must be strictly after `starts_at`, and neither may be *set* in\\n the past β€” on create or `PATCH` (kept values are exempt, so a running exam\\n stays editable). All instants are the usual UTC unix-milliseconds, judged\\n only by the server clock (`GET /time` for sync).\\n\\nTwo per-exam policy knobs ride along, both **live-editable** at any point:\\n\\n- `max_attempts` (default `1`, `0` = unlimited) β€” how many sittings each\\n student gets. Raising it mid-exam grants retakes on the spot; lowering it\\n never kills a running attempt, it only blocks future starts.\\n- `allow_rejoin` (default `true`) β€” whether a student who *left the exam room*\\n may come back in and keep answering (see the exam-room section).\\n- `allow_review` (default `false`) β€” opt-in door to the student self-review\\n reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A\\n student may review only when this is on **and** the teacher has marked them\\n (an `ExamResult` row exists); own-scoped, so no student reads another's sheet.\\n\\nA student **sits** an exam through attempts (sitting 1, 2, … β€” each row id is\\nthe composite `exam_user[_seq]` key, so a sitting exists at most once by\\nconstruction):\\n\\n- `POST /exams/{id}/attempt` starts, resumes, or retakes (students only β€”\\n staff never sit; enrolled; window open where one exists β€” `open` exams start\\n anytime). While the latest\\n sitting runs, re-posting returns it unchanged (`200`, not `201`):\\n reconnecting never resets the clock. Once it is submitted or expired,\\n re-posting mints the next sitting (`201`) **from a blank answer sheet** β€”\\n the previous sitting's answers are wiped β€” until `max_attempts` is spent\\n (`409` after that). Starting is the live-attendance signal.\\n- `GET /exams/{id}/attempt` is the student's exam screen: the latest sitting's\\n `status` (`in_progress` | `submitted` | `expired`), `attempt` (its number),\\n `attempts_used`/`max_attempts`, `deadline`/`remaining_ms` (`null` for an\\n untimed open exam), `left_at`, own `mark` once graded, and the server `now`.\\n- `POST /exams/{id}/attempt/finish` submits. After the deadline the attempt is\\n `expired` β€” a valid terminal state (the student used their full time), and\\n finishing answers `409`. Grading stays per exam+user (one mark), whatever\\n the sitting count β€” the sheet a grader sees is always the latest sitting's.\\n\\nDeadlines are **recomputed from the exam's current schedule on every read**,\\nnever stored: a teacher who `PATCH`es `ends_at` (or a `duration_ms`)\\nwhile the exam runs moves every running deadline instantly. What's frozen once\\nanyone has started is only `mode` (including back to unscheduled) β€” swapping\\nthe deadline rules mid-sitting would be a different exam (`409`).\\n\\nThe course's manager (its creator, or manager+) watches it all live:\\n`GET /exams/{id}/live` returns one snapshot β€”\\nthe enrolled roster joined with attempts and marks (`not_started` | `absent` |\\n`in_progress` | `submitted` | `expired`, per-student `attempt` /\\n`attempts_used` / `left_at` / `deadline` / `remaining_ms` / `mark`, always the\\nlatest sitting) plus summary counts, all judged at a single `now`. Once the\\nwindow closes, `not_started` hardens into `absent` β€” the no-shows, flagged\\nright in the roster (open exams have no window, so never an `absent`). The\\nflag is informational: an absent student still has no mark until the teacher\\nrecords one through `POST /exams/{id}/results`. Poll `GET /exams/{id}/live` to\\nkeep a monitor current β€” attendance, ticking clocks, submissions, and marks all\\nride in each snapshot.\\n\\nDeleting an exam (or its course) cascades attempts, questions, answers, and\\nquestion + answer images (blobs included) along with results; unenrolling mid-exam\\nhides the student from the monitor roster but keeps the attempt and mark\\nrows, mirroring the marks report.\\n\\n> **Upgrading a pre-course database**: `exam` rows created before courses\\n> existed lack the now-required `course` field and will fail to deserialize.\\n> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data,\\n> backfill manually with the SurrealDB CLI (server stopped), e.g.\\n> `UPDATE exam SET course = course:<id> WHERE course = NONE;`\\n> after creating a course to attach them to.\\n>\\n> **Upgrading to the attempts/rejoin build needs nothing manual**: the boot\\n> migration backfills `max_attempts = 1`, `allow_rejoin = true`, and attempt\\n> `seq = 1` on existing rows, and swaps the single-attempt unique index for\\n> the per-sitting one. Pre-upgrade attempts keep their record ids and count\\n> as sitting #1.\\n>\\n> **Upgrading to the kind-weight build is a clean break**: weights moved off\\n> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with\\n> no data migration. A database from an older build has string kinds and a\\n> per-exam `weight` column the code no longer understands β€” delete\\n> `./data/hezarfen.db` and reboot.", "source": "README.md"}, {"id": "taking-an-exam-questions-answers-the-exam-room", "title": "Taking an exam: questions, answers & the exam room", "body": "Teachers author a question list per exam; students answer inside their\\nattempt, autosaved as they go; choice questions are machine-checked as a\\n**suggestion** β€” the final mark stays a human call through the existing\\n`POST /exams/{id}/results`.\\n\\n**Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`,\\ncourse-management rights): each has a mandatory `subject_id` (one of the\\ncourse's subjects, `GET /courses/{id}/subjects` β€” the topic the question\\nbelongs to), `text` (≀ 2000 chars), `points` `1`–`100`\\n(its share of the auto-score), and a `kind`:\\n\\n- `kind: \\"choice\\"` β€” carries `choices` (2–10 options, each ≀ 500 chars) and\\n `correct`, the zero-based index of the right option. Auto-scorable.\\n- `kind: \\"text\\"` β€” free text, judged by the grader; carries neither.\\n\\nThe kind bundle is validated as a unit (create and after every `PATCH` merge):\\nswitching a question to `text` needs explicit `\\"choices\\": null, \\"correct\\":\\nnull`, switching to `choice` must bring both along. Presentation order is\\ncreation order. The whole list **freezes once anyone has started an attempt**\\n(`409` on create/edit/delete) β€” editing questions under a sitting student\\nwould fork what \\"the exam\\" means. Deleting a question cascades its answers\\nand images.\\n\\n**Question images**: any question may carry one **illustration** (`POST\\n/exams/{id}/questions/{qid}/image` β€” the map the prompt asks about, on\\n`choice` and `text` questions alike), and each option of a `choice` question\\nmay carry a **picture** of its own (`POST .../choices/{choice_id}/image` β€” so\\nthe options themselves can be images: four map crops, pick the right one).\\nUploads are `multipart/form-data` with a single `file` part, capped by the\\nschool's `max_file_bytes`; the declared content type must be `image/png`,\\n`image/jpeg`, `image/webp`, or `image/gif` (rasters only β€” SVG can script,\\nand these bytes render inline for the whole class). One image per slot:\\nre-uploading replaces, `DELETE` on the same paths removes, and replacing a\\nquestion's `choices` list drops all its option pictures (the illustration\\nstays β€” re-upload against the new list). Image writes follow question\\nauthoring exactly: course-management rights, frozen once attempts exist.\\nBoth question views (`GET /exams/{id}/questions` and the sitting view)\\nembed the metadata as `image: {content_type, size} | null` and\\n`choice_images: [...|null]` aligned with `choices`; the bytes come from the\\n`GET` endpoints above β€” course managers anytime, students through the same\\nenrollment + started-attempt wall as the sitting view (no early peek at the\\npictures either), served with `Cache-Control: private, no-store`.\\n\\n**Answering** (student, attempt `in_progress`, deadline judged by the server\\nclock on every save):\\n\\n- `GET /exams/{id}/attempt/questions` β€” the sitting view. Requires\\n enrollment (`403` β€” the questions are course content, so leaving the course\\n closes them) and an attempt (`404` before `POST /exams/{id}/attempt`; also\\n the anti-peek gate), never contains `correct`, and embeds the caller's own\\n saved answer per question (`{selected, text, updated_at}` or `null`). Still\\n readable after submitting/expiry, for review.\\n- `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` β€” an\\n upsert: one row per question+user, re-answering overwrites. The payload must\\n match the question's kind (`selected` indexing a choice, or `text`\\n ≀ 10 000 chars β€” empty clears the draft); mismatches are `400`s. Requires\\n the student role and enrollment (`403`): a promotion out of `student` or an\\n unenrollment mid-exam closes the sheet (the exam room's door checks,\\n re-applied to every save β€” finishing stays open). Once the\\n attempt is submitted or past its deadline every save is a `409` β€” likewise\\n while the student has left the exam room with `allow_rejoin` off; answers\\n saved in time survive untouched for grading. Each sitting keeps its own\\n answers, drawings, and mark, keyed by the attempt's `seq` β€” a retake starts\\n from a blank sheet without erasing the prior one, so the full per-attempt\\n history stays readable (see the grading view).\\n\\n**Answer images**: the student side mirrors the teacher's question images. A\\nstudent may attach one **drawing** to any question in their attempt β€” a\\nsketched answer or worked steps β€” via `POST\\n/exams/{id}/attempt/answers/{qid}/image` (`multipart/form-data`, one `file`\\npart, the same raster allowlist and `max_file_bytes` cap as question images).\\nOne image per question: re-uploading replaces, `DELETE` on the same path\\nremoves. Writes ride the exact `POST /exams/{id}/attempt/answers` gate β€” the\\nstudent role, enrollment, an `in_progress` attempt, and the rejoin door β€” so a\\ndrawing is just another autosaved answer; a drawing-only answer (nothing\\ntyped) still surfaces, and clearing it grooms the empty row away. The bytes\\ncome from `GET` on the same path (the caller's own, behind the sitting-view\\nwall) and, for the grader, `GET /exams/{id}/attempts/{user}/answers/{qid}/image`\\n(course-management rights); both serve inline with `Cache-Control: private,\\nno-store`. The metadata rides the answer as `answer_image: {content_type,\\nsize} | null` on both the sitting view and the grading sheet. To the backend\\nit is a normal raster PNG; the frontend piggybacks its editable stroke data in\\na PNG `tEXt` chunk, opaque here β€” stored on disk under `Config::files_path`\\nby a ULID, metadata in the `answer_image` table, structurally identical to\\nquestion images.\\n\\n**Grading view** (course-management rights): `GET /exams/{id}/attempts/{user}/answers` returns\\nthe student's **latest** sitting's sheet β€” every saved answer with `is_correct`\\n(`true`/`false` for choice, `null` for text: that's the grader's call) plus\\n`auto_score: {earned, possible}` summing the choice questions' points. It is a\\nsuggestion to read while grading, never written anywhere.\\n\\n**Per-attempt history** (course-management rights): prior sittings stay\\nreadable. `GET /exams/{id}/students/{user}/attempts` lists the sitting numbers\\na student has (every `seq` carrying answers or a mark, ascending);\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers` is the grading sheet\\nfor one of them (drawing bytes at\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image`); and\\n`GET /exams/{id}/students/{user}/marks` is the full per-sitting mark history,\\noldest first. Grading (`POST /exams/{id}/results`) always lands on the current\\nsitting, and the latest seq is the grade-of-record β€” the roster, report, and\\nstatistics reads all show it. Every result payload carries its `seq`, so a mark\\nlinks straight to that sitting's answer sheet β€” without it a marked retake's\\nanswers would be unreachable from the mark.\\n\\n**The exam room (WebSocket)** β€” `GET /exams/{id}/attempt/ws`, cookie-authed\\nlike everything else; REST above remains the full fallback. Gates run before\\nthe upgrade: unknown or draft exam `404`, unscheduled (no mode) `409`, not a\\nstudent `403`, not enrolled `403`, no attempt yet `404` (start it first),\\nsubmitted/expired `409`, left while rejoin is closed `409`. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| server β†’ | `{\\"type\\":\\"state\\", status, attempt, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save |\\n| client β†’ | `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"selected\\":1}` or `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"text\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` |\\n| server β†’ | `{\\"type\\":\\"saved\\", question_id, updated_at, client_seq?}` β€” the autosave ack |\\n| client β†’ | `{\\"type\\":\\"finish\\"}` β€” submit the attempt |\\n| server β†’ | `{\\"type\\":\\"finished\\", finished_at}`, then Close |\\n| server β†’ | `{\\"type\\":\\"expired\\"}`, then Close β€” a tick noticed the deadline |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", message, question_id?, client_seq?}` β€” bad JSON, wrong kind, deadline, … |\\n\\nAn `answer` may carry a `client_seq`: any number the client picks, echoed verbatim on\\nthat message's `saved` or `error` and on nothing else. The server never reads\\nit β€” no uniqueness, no ordering, no dedupe, all the client's business β€” and\\nomits the key entirely when the request omitted it, so leaving it out keeps\\ntoday's frames byte for byte. It exists because `question_id` is not an\\nidentity: save a question, time out, save it again, and two sends are\\noutstanding for the same id β€” the first reply would settle the second and the\\nUI would claim \\"Saved\\" for an answer the server never took. `question_id` on\\nan `error` is the separate, orthogonal question: whether the failure belongs\\nto that one question (payload or question) or to the room, in which case every\\nsave in flight is equally refused. An error can carry `client_seq` without\\n`question_id`.\\n\\nEvery tick and every save re-read the exam, so a mid-exam `ends_at` extension\\nmoves the room's countdown on the next tick, and no stale socket can write\\npast its real deadline β€” the socket shares the exact REST write path. Each\\nroom acts only on the sitting it was opened for: once that sitting is over,\\nits `answer`/`finish` are `error` frames, so a lingering socket can never\\nscribble on (or instantly submit) a retake started elsewhere.\\n\\nThe room is also the presence signal behind the **rejoin door**: connecting\\nclears the attempt's `left_at`, and the *last* socket of the sitting to close\\nwhile it is still running stamps it (visible on the live monitor β€” \\"left the\\nroom three minutes ago\\" at a glance). Closing one of two tabs is not leaving,\\nand a lingering socket from an already-finished sitting never marks a later\\nretake as left β€” each room is bound to the sitting it was opened for. With the exam's `allow_rejoin` off, a stamped\\n`left_at` refuses re-entry *and* any further saves, over the socket or REST,\\nuntil the teacher flips the door back open (`PATCH /exams/{id}\\n{\\"allow_rejoin\\": true}` β€” live, like the times). Finishing stays allowed: a\\nlocked-out student can always submit what they saved. The timer never pauses\\neither way. Students who only ever use REST never trip the door β€” the room is\\nwhat marks leaving.\\nExample client:\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/exams/${id}/attempt/ws`);\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"state\\") renderCountdown(m.remaining_ms, m.answered, m.question_count);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.question_id);\\n};\\nlet clientSeq = 0;\\nconst save = (question_id, selected) =>\\n ws.send(JSON.stringify({ type: \\"answer\\", question_id, selected, client_seq: ++clientSeq }));\\n```\\n\\nThe live monitor rides along: each roster row now carries `answered` and\\n`last_activity` (latest save instant), and the snapshot a top-level\\n`question_count`, so \\"stuck at 3/10 for five minutes\\" is visible at a glance.\\nThe student's own `GET /exams/{id}/attempt` echoes the same\\n`answered`/`question_count` pair.", "source": "README.md"}, {"id": "question-bank", "title": "Question bank", "body": "Writing good questions is slow, and the same one gets asked year after year, so\\nthe school keeps a reusable **question bank**. A bank question is an\\n`ExamQuestion` cut loose from any exam: it has the same shape (`subject_id`,\\n`text`, `kind`, `points`, and β€” for a `choice` β€” `choices` + `correct`), the\\nsame image slots (one illustration, plus a picture per option), and the same\\nnewtype validation, but it carries **no exam link**. Because nothing sits it,\\na bank row **never freezes** β€” its owner can edit or delete it forever.\\n\\n`POST /bank-questions` (teacher+) saves one, stamping the caller as its\\n**owner**. `subject_id` is origin metadata, but it must **exist** β€” an unknown\\nsubject is a `400` (create and PATCH alike). The reverse guard does **not**\\nhold here, unlike exam questions and homework: a template never blocks a\\nsubject delete, which simply clears `subject` off every template that carried\\nit (only a template's owner may re-tag it, so a `409` would be one a manager\\ncould never clear β€” and a private template raising it would leak its\\nexistence). Reads are school-wide: `GET /bank-questions` lists the\\nwhole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` β€” or\\n`?owner=me` β€” by owner) and `GET /bank-questions/{bid}` fetches one with\\n`correct` included β€” any teacher+ can browse and reuse what any colleague\\nbanked. Each response carries its **image metadata** β€” an `image` meta for the\\nillustration and a `choice_images` array aligned with `choices` (per-slot\\n`{content_type, size}`, `null` where a slot has no picture) β€” the same shape an\\nexam question's response uses; the bytes still come from the image endpoints.\\nMutation is **owner-only** (an `admin` bypasses): `PATCH /bank-questions/{bid}`\\nrevalidates the kind bundle as a unit, `DELETE /bank-questions/{bid}` drops the\\nrow and its image blobs. The illustration and option pictures work exactly like\\nan exam question's β€” `POST|GET|DELETE /bank-questions/{bid}/image` and\\n`…/choices/{choice_id}/image`, `multipart/form-data` with one `file` part, raster\\nonly (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` β€” reads school-wide,\\nwrites owner-only.\\n\\nThe bank feeds exams by **copying**, never linking. `POST\\n/exams/{id}/questions/from-bank/{bid}` instantiates a bank question into the\\nexam: it mints a **fresh** exam-scoped question (new id, its own answer rows,\\nits image blobs copied to new files), so later edits on either side never\\ntouch the other. The subject on the bank row is origin metadata only β€” the\\ncall takes its own `{subject_id}`, re-checked against the target course's\\nsubjects (`400` on a cross-course subject), and instantiating into an exam\\nthat already has attempts is a `409`, the same freeze that guards hand-authored\\nquestions. The instantiated question records the template it came from in\\n`source_bank`. The reverse, `POST /exams/{id}/questions/{qid}/to-bank`, copies\\nan existing exam question **into** the bank (new detached row, images copied to\\nnew files, owner = caller); the source question is left untouched, and the new\\ntemplate records the origin exam in `source_exam`. Both provenance fields are\\nnullable β€” a hand-authored question or template carries `null` β€” and one-way\\nmetadata (the copies stay fully detached). All bank routes are course-agnostic\\nand require teacher+.\\n\\nCopying means a template edit never reaches the copies, so there is one escape\\nhatch for that divergence: `POST /exams/{id}/questions/{qid}/refresh-from-bank`\\nre-copies the template's *current* content over one exam question β€” text,\\npoints, kind, choices (adopting the **template's** choice ids, so the option\\npictures re-land on the right options), `correct`, the illustration and the\\noption pictures. The question keeps its own id, its exam, its `subject` (the\\ntemplate's is unrelated origin metadata) and its provenance links; anything\\nedited on the copy is overwritten, deliberately. A question with no\\n`source_bank` β€” hand-authored, or its template deleted β€” is a `400`, a template\\nthe caller may not see is a `404` (never a 403), and the usual freeze applies:\\nonce any attempt exists, `409`. Every source blob is read before anything is\\nwritten, so a missing blob is a `500` with the question untouched rather than a\\nhalf-applied refresh.", "source": "README.md"}, {"id": "homework", "title": "Homework", "body": "A course hands out **homework**: `POST /courses/{id}/homework` with a title,\\nan optional description, a **required subject** (one of the course's own β€” and\\nthe same delete guard questions have: a subject with homework refuses deletion\\nwith a `409` until the homework is re-tagged via `PATCH /homework/{id}` or\\ndeleted), and a **required `due_at`** that must not lie in the past (same 60s\\ngrace as every schedule field; late *submissions* are fine β€” a late\\n*assignment* is not).\\n\\n**Audience.** By default the whole course, resolved live: whoever is enrolled\\n*when they act* β€” a student enrolled after the assignment sees and submits it\\nlike everyone else. `assigned` (at create or PATCH) instead pins a named\\nsubset of currently enrolled students (at most 200). The unnamed must not even\\nlearn a subset exists: lists omit it, and direct reads and submits answer\\n`404` β€” the same no-leak a hidden exam draft gets. Narrowing the subset later\\nis refused with a `409` that names the blockers while any submission or grade\\nbelongs to a student the new list would strand.\\n\\n**Submitting.** Students only β€” staff and parents never submit β€” enrolled and\\nin the audience, re-checked on every write. A submission is optional text plus\\nup to **10 files of any content type** (each ≀ the school's\\n`max_file_bytes`): text is replaced whole on each `POST` (omit to clear),\\nfiles are added and removed one by one, and a file upload with no prior\\nsubmission auto-creates an empty one, so a photo-only homework is a single\\nrequest. Two stamps tell the lateness story: `submitted_at` pins the **first**\\nhand-in forever, `updated_at` moves on every text edit and file add/remove,\\nand `late` is **computed on read** (`updated_at > due_at`), never stored β€” so\\ntouching work after the deadline flips it late, and a `due_at` edit re-grades\\nlateness for free. Late submissions are always accepted, only flagged. File\\nbytes always come back as a forced download (`Content-Disposition:\\nattachment`): homework accepts any content type, so rendering an uploaded\\nHTML/SVG inline would run it in the viewer's session.\\n\\n**Grading.** A course manager records a status β€” `done`, `incomplete`, or\\n`missing` β€” plus an optional 0–100 `mark` per student\\n(`POST /homework/{id}/results`, one upsert row per homework+student; the\\nexam walls apply: live students only, enrolled, in the audience, never the\\ngrader themselves). A stored grade **freezes** that submission β€” text edits,\\nfile changes, withdrawal all `409` β€” until\\n`DELETE /homework/{id}/results/{user}` removes it and reopens editing.\\nGrading before the due date, or before anything was submitted, is allowed β€”\\nthe latter is how never-handed-in work gets its `missing` verdict, and\\n`GET /homework/{id}/result` is where its student reads it (their submission\\nendpoints have nothing to show). The teacher-set `missing` **status** is a\\ndeliberate verdict; the roster and the report *also* compute a `missing`\\n**flag** for anyone unsubmitted past due β€” the two are independent. Homework\\nmarks stay out of `/marks`: the weighted course average remains exam-only\\n(the exam *kind* named `homework` still lives there), so nothing\\ndouble-counts.\\n\\n**Roster & report.** `GET /homework/{id}/submissions` (course manager) is the\\ngrading table: one row per audience student β€” plus any straggler outside the\\naudience who still owns a submission or grade (an unenrollment, a promotion,\\nor an audience change leaves work behind; it stays visible, flagged\\n`unenrolled`, though a stale student can neither submit nor be graded).\\n`GET /homework/report/{user}` is the fourth observer read beside marks,\\nattendance, and pomodoro: teacher+ (an exactly-teacher caller narrowed to the\\ncourses they manage), or a **parent linked** to the student β€” per-homework\\nrows of submitted/late/missing plus the grade; statuses and marks only,\\n**never the files**.\\n\\nEvery delete collects its garbage: withdrawing a submission, deleting a\\nhomework, and deleting the whole course each cascade the rows (submissions,\\nfiles, grades) and unlink the file blobs from disk. Role changes never sweep\\nhomework rows: a promoted student's work stays readable on the roster behind\\nthe `unenrolled` flag, while the live-role gates refuse fresh edits and\\ngrades.", "source": "README.md"}, {"id": "lesson-sessions-roll-call-the-work-log-pomodoro-attendance-reports", "title": "Lesson sessions, roll call, the work log, pomodoro & attendance reports", "body": "Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session\\nbelongs to a course and carries a `teacher` (defaults to whoever creates it;\\nany explicit `teacher_id` must hold teacher+ β€” a student cannot teach), an\\noptional `topic`, a required `starts_at`, and an optional `ends_at` (when both\\nare set, `ends_at` must not precede `starts_at`; neither may be set in the\\npast). Sessions are created, edited,\\nand deleted under course-management rights, exactly like exams; session lists\\nare ordered by `starts_at` (a timetable, not a creation log).\\n\\n**Roll call** (`/sessions/{id}/attendance`) deliberately differs from event\\nattendance: students never mark themselves. The session's teacher or a course\\nmanager marks **enrolled** students β€” only students attend classes, so a\\nnon-student or unenrolled target is a `400` β€” and the\\n**session teacher's own** presence row can only be written or removed by\\nmanager+ β€” staff presence is management's call, so a teacher can't declare\\nthemselves present. Listing the roll call follows the same rights as taking\\nit; a student reads their own tallies through the attendance report instead.\\nRe-marking overwrites: one row per session+user, by construction. Deleting a\\nsession (or its course) cascades its roll-call rows.\\n\\nThe **work log** (`/work`) is the staff timesheet, for teachers and above.\\n`POST /work/check-in` opens a stint and `POST /work/check-out` closes it, both\\nstamped by the **server clock** β€” a request never carries an instant, so a\\nwrong device clock (or a crafted request) can't forge presence. At most one\\nopen stint per user holds atomically: double check-ins and check-outs without\\nan open stint answer `409`, and a reconnecting double-click can't reset a\\nrunning clock. `GET /work/me` lists your stints newest-first (the open one has\\n`check_out: null`, closed ones a convenience `duration_ms`); manager+ reads\\nanyone's log (`GET /work/{user}`), corrects a **closed** stint's instants\\n(`PATCH /work/entries/{id}`, `409` while open β€” check out or delete instead),\\nand deletes entries.\\n\\nThe **pomodoro log** (`/pomodoro`) is the students' study-time twin of the\\nwork log. The frontend owns the timer β€” the visible countdown, the work/break\\nrhythm, the durations; the backend stores no timing policy and records only\\n**focus stints**, stamped by the server clock exactly like work stints.\\n`POST /pomodoro/start` opens a session and β€” unlike a work check-in β€” always\\nsucceeds for a student: a dangling unfinished session (a laptop closed\\nmid-timer) is **discarded and replaced**, because it recorded no focus and\\nmust not lock the student out of the next one. `POST /pomodoro/finish` closes\\nthe running session (`409` when nothing runs); breaks are never reported.\\nLogs return the usual page envelope plus `total_focus_ms`, the unpaged sum of\\nevery finished session's duration: `GET /pomodoro/me` for your own,\\n`GET /pomodoro/{user}` for teacher+ (study oversight). Only students start\\nsessions β€” pomodoro is the study tool, the work log is the staff timesheet.\\n\\n**Attendance reports** mirror the marks report: `GET /attendance/me` for any\\nlogged-in user, `GET /attendance/{user}` for teacher+ β€” narrowed to the\\ncourses the caller manages (manager+ sees every course; event tallies are\\nschool-wide either way). The report tallies event attendance and lesson roll\\ncall separately, plus a per-course breakdown:\\n\\n```json\\n{\\n \\"user\\": \\"01J…\\",\\n \\"events\\": { \\"present\\": 4, \\"absent\\": 1, \\"late\\": 0, \\"excused\\": 1, \\"total\\": 6, \\"rate\\": 0.8 },\\n \\"sessions\\": { \\"present\\": 9, \\"absent\\": 2, \\"late\\": 1, \\"excused\\": 0, \\"total\\": 12, \\"rate\\": 0.8333 },\\n \\"courses\\": [ { \\"course\\": { \\"id\\": \\"01J…\\", \\"title\\": \\"algebra\\", … }, \\"counts\\": { … } } ]\\n}\\n```\\n\\n`rate = (present + late) / (present + absent + late)`: arriving late still\\ncounts as attending, and an excused absence counts against no one (`rate` is\\n`null` when every row is excused, or there are none). Per-course blocks appear\\nfor every course the user has roll-call rows in β€” attendance is a historical\\nrecord, so unenrolling hides marks from the marks report but never hides an\\nabsence.", "source": "README.md"}, {"id": "quick-tour-curl", "title": "Quick tour (curl)", "body": "```sh\\nBASE=http://127.0.0.1:8080\\nJAR=/tmp/hz.cookies\\n\\ncurl -s $BASE/auth/register -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\ncurl -s -c $JAR $BASE/auth/login -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\n# notes\\ncurl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"first\\",\\"content\\":\\"hello\\"}'\\ncurl -s -b $JAR $BASE/notes\\n\\n# note files (multipart; -F sets filename + content type from the file)\\nNO=$(curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"with file\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nFI=$(curl -s -b $JAR $BASE/notes/$NO/files -F 'file=@plan.pdf' \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/notes/$NO/files # list metadata\\ncurl -s -b $JAR -OJ $BASE/notes/$NO/files/$FI # download, original filename\\n\\n# events + attendance\\n# Creating events needs teacher+; grant it first (see \\"Bootstrapping\\" above β€”\\n# e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403.\\nEV=$(curl -s -b $JAR $BASE/events -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"standup\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json' \\\\\\n -d '{\\"status\\":\\"present\\"}'\\ncurl -s -b $JAR $BASE/events/$EV/attendance\\n\\n# courses + weighted marks (as a teacher)\\n# optional, manager+: weigh midterms triple β€” school policy, per kind\\ncurl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \\\\\\n -d '{\\"exam_kinds\\":[{\\"name\\":\\"midterm\\",\\"weight\\":3},{\\"name\\":\\"quiz\\",\\"weight\\":1}]}'\\n# find the student to enroll (here: a registered user \\"veli\\"): fragment\\n# search over username/name, role-narrowed (teacher+)\\nSID=$(curl -s -b $JAR \\"$BASE/users/search?q=vel&role=student\\" \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nCO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"algebra\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\nEX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"midterm\\",\\"kind\\":\\"midterm\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"mark\\\\\\":90,\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\ncurl -s -b $JAR $BASE/exams/$EX/statistics\\n\\n# lesson sessions + roll call (course manager creates; the session's teacher\\n# or a course manager marks enrolled students)\\nSE=$(curl -s -b $JAR $BASE/courses/$CO/sessions -H 'content-type: application/json' \\\\\\n -d '{\\"topic\\":\\"limits\\",\\"starts_at\\":1900000000000}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/sessions/$SE/attendance -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"status\\\\\\":\\\\\\"present\\\\\\",\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\n\\n# staff work log (instants are server-stamped)\\ncurl -s -b $JAR -X POST $BASE/work/check-in\\ncurl -s -b $JAR -X POST $BASE/work/check-out\\ncurl -s -b $JAR $BASE/work/me\\n\\n# ...and as the student:\\ncurl -s -b $STUDENT_JAR $BASE/marks/me\\ncurl -s -b $STUDENT_JAR $BASE/attendance/me\\n# pomodoro: start when the timer starts, finish when it rings\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/finish\\ncurl -s -b $STUDENT_JAR $BASE/pomodoro/me\\n```", "source": "README.md"}, {"id": "ai-bridge-quic", "title": "AI bridge (QUIC)", "body": "The AI features are separate projects β€” separate repos, separate processes,\\nprobably not Rust. They talk to this backend over a QUIC bridge rather than\\nHTTP.\\n\\nWhy QUIC: stream multiplexing lives in the transport. Each request rides its\\nown **bidirectional stream** on the service's single long-lived connection, so\\nconcurrent requests need no correlation-id bookkeeping and never head-of-line\\nblock each other β€” a 30-second inference on one stream does not delay the\\nanswer on another. Connection setup (and the TLS handshake) happens once, not\\nper request.\\n\\n**The backend listens; the services dial in.** A service can therefore sit\\nbehind NAT, restart without the backend knowing its address, and scale out by\\nopening a second connection β€” each connection is an independent worker.\\n\\nOff by default: with `AI_QUIC_ADDR` unset the bridge never starts and the rest\\nof the API is unaffected.\\n\\n### Handshake\\n\\nThe service connects with ALPN `hab/1`, then opens the **control stream** (the\\nfirst client-initiated bidi stream) and writes one `Hello`:\\n\\n```json\\n{ \\"protocol\\": \\"hab/1\\", \\"service\\": \\"ocr\\", \\"capabilities\\": [\\"ocr.extract\\"],\\n \\"token\\": \\"<AI_SHARED_TOKEN>\\", \\"max_concurrent\\": 8 }\\n```\\n\\nThe backend answers one `Greeting` and leaves the stream open:\\n\\n```json\\n{ \\"type\\": \\"welcome\\", \\"worker_id\\": \\"01J...\\", \\"protocol\\": \\"hab/1\\" }\\n{ \\"type\\": \\"rejected\\", \\"code\\": \\"unauthorized\\", \\"message\\": \\"invalid token\\" }\\n```\\n\\nReject codes: `unsupported_protocol`, `unauthorized`, `no_capabilities`,\\n`malformed`. The token is compared in constant time; the handshake must\\ncomplete within 10s.\\n\\nThe control stream carries no further frames. **Its closure is the goodbye** β€”\\nthere is no heartbeat. A service that dies silently is dropped by the QUIC idle\\ntimeout (30s, with a 10s keepalive) and deregistered then.\\n\\n`max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests\\nbeyond it are refused with \\"busy\\" rather than queued.\\n\\n### Requests\\n\\nFor each request the **backend** opens a bidi stream, writes one `Request`,\\nfinishes its send side, and reads one `Response`:\\n\\n```json\\n{ \\"id\\": \\"01J...\\", \\"capability\\": \\"ocr.extract\\", \\"deadline_ms\\": 30000,\\n \\"payload\\": { \\"image\\": \\"<base64>\\" } }\\n```\\n\\n```json\\n{ \\"status\\": \\"ok\\", \\"id\\": \\"01J...\\", \\"payload\\": { \\"text\\": \\"...\\" } }\\n{ \\"status\\": \\"err\\", \\"id\\": \\"01J...\\", \\"code\\": \\"unsupported_image\\",\\n \\"message\\": \\"only png and jpeg\\" }\\n```\\n\\n`id` is a trace id for logs on both sides β€” correlation is the stream, not the\\nid. It must still be echoed: an answer carrying a different id means the\\nservice lost track of whose work it is, and the payload is refused. `payload`\\nis opaque to the transport; its shape belongs to the capability.\\n\\n`deadline_ms` is when the backend gives up. A service should abandon the work\\nrather than answer late. A handled failure is an `err` frame; a crash is just a\\ndropped stream.\\n\\n### Framing\\n\\n`u32` big-endian byte length, then that many bytes of JSON. One frame per\\nmessage. The length is validated against the 8 MiB cap **before** any buffer is\\nallocated. JSON rather than a binary codec so a service in any language can\\nspeak it in ~20 lines.\\n\\n### Routing\\n\\nRequests route by exact capability string to the **least-loaded** worker\\noffering it (ties broken by worker id). Least-inflight rather than\\nround-robin because AI request costs are wildly uneven β€” round-robin would\\npile a second long inference onto a busy worker while an idle one sits next\\nto it. Selection and the in-flight increment happen under one lock, so\\nconcurrent dispatches cannot overshoot `max_concurrent`.\\n\\nFailure modes the caller sees: `NoWorker` (nothing registered β€” retryable),\\n`Busy` (all at capacity β€” retryable), `Timeout` (may still be running on the\\nfar side, so it promises nothing), `Remote` (the service's considered no β€”\\nnot retryable), `Protocol` / `IdMismatch` (broken peer), `Transport`.\\n\\n### Conformance suite\\n\\n`tests/ai_protocol.rs` is the wire contract, enforced on every `cargo test`. It\\nspeaks `hab/1` with a client that imports none of the crate's protocol types β€”\\nframes built as byte literals, answers parsed as untyped JSON β€” so it fails on\\nexactly the changes a service in another language would notice: a renamed\\nfield, a re-tagged enum, a flipped length-prefix endianness, a newly-required\\n`Hello` field. (`tests/ai_bridge.rs` drives real QUIC clients too, but shares\\nthe Rust structs with the backend, so it cannot see those.)\\n\\nIt is also the reference implementation: its `raw` module is the whole client\\nside of the protocol in about a hundred lines β€” handshake, framing, request\\nloop β€” and is the shortest thing to port when writing a new service.\\n\\nGuarantees it pins beyond the frame shapes: unknown fields in `Hello` and in a\\nresponse are accepted (a newer service may run against an older backend);\\npayloads pass through byte-for-byte whatever their JSON shape; request ids are\\nunique; answers may come back in any order; a service that drops one request\\nstream fails only that request; a service that ignores `deadline_ms` finds its\\nstream torn down rather than delivering a late answer.\\n\\n### TLS, auth & finding the certificate\\n\\nQUIC has no plaintext mode. With `AI_TLS_CERT`/`AI_TLS_KEY` unset, a\\nself-signed certificate is generated at boot and its sha256 fingerprint logged\\nβ€” services pin that instead of installing a CA. The certificate authenticates\\n*the backend*; the shared token in `Hello` authenticates *the service*.\\n\\nSo a service does not have to be handed a file out of band, the certificate is\\npublished over HTTP:\\n\\n```\\nGET /ai/certificate # no auth; 404 when the bridge is disabled\\n{ \\"protocol\\": \\"hab/1\\",\\n \\"certificate_pem\\": \\"-----BEGIN CERTIFICATE-----\\\\n...\\",\\n \\"fingerprint_sha256\\": \\"6745e8...\\" }\\n```\\n\\nUnauthenticated on purpose: a server certificate is handed to every peer during\\nthe TLS handshake anyway, so publishing it discloses nothing. The private key\\nnever leaves the process, and the shared token β€” the thing that actually\\nauthenticates a service β€” is *not* served here.\\n\\n**A service must re-fetch this on every reconnect, not once at startup.** With\\nno PEM pair configured the bridge re-selfsigns at each boot, so a certificate\\npinned once goes stale the moment the backend restarts; a reconnect loop that\\nonly redials would then fail forever. The service startup sequence is: `GET\\n/ai/certificate` β†’ trust that PEM β†’ dial QUIC β†’ `Hello` β†’ serve; on any\\nconnection loss, start again from the fetch.\\n\\nNote what this is not: fetch-then-pin over plain HTTP is trust-on-first-use,\\nonly as trustworthy as that HTTP hop. On an untrusted network set\\n`AI_TLS_CERT`/`AI_TLS_KEY` to a real certificate and distribute it out of band\\nβ€” the endpoint then simply serves that, stable across restarts.", "source": "README.md"}, {"id": "chatbot", "title": "Chatbot", "body": "Every signed-in user β€” `parent` included β€” keeps private threads with an\\nAI service. The backend is a **relay**: it owns auth, the limits, the thread,\\nthe payload format, and the last look at the answer before anyone sees it; the\\nwords are the service's. There are deliberately **no rule, intent or\\ncanned-answer tables** β€” the thread is free-form, and a school that wants\\ndifferent behaviour changes its AI service, not this backend. A thread is\\nprivate to its owner: no teacher, no admin, nobody reads someone else's, and\\nanother user's thread is a `404`, never a `403`.\\n\\n### Sending is two-phase, and that is the point\\n\\n`POST /chatbot/threads/{id}/messages` answers `202 {message_id, status:\\n\\"pending\\"}` instead of the answer, because an inference outlives a normal\\nrequest (and the request-timeout layer that guards every handler). Before the\\nAI is even called, two rows are written: the user's turn, and an **empty\\n`pending` assistant row** β€” `message_id` is that row. That order is the whole\\ndesign: a reload, a dropped connection, a closed laptop can no longer lose an\\nanswer, because the place it will land already exists and the answering task\\noutlives the HTTP request.\\n\\nThe client then reads that row either way it likes:\\n\\n- **poll** `GET /chatbot/threads/{id}/messages/{mid}` β€” `pending` until it\\n settles, then `complete` with `content` or `failed` with `error_code`;\\n- **stream** `GET /chatbot/threads/{id}/messages/{mid}/stream` β€” the same\\n row over Server-Sent Events.\\n\\nBoth read the same row, so they can never disagree, in any state.\\n\\n### The SSE stream\\n\\n```\\nevent: delta\\ndata: {\\"text\\":\\"Newton'un ikinci yasasΔ± \\"}\\n\\nevent: delta\\ndata: {\\"text\\":\\"kuvvet ile ivme arasΔ±ndaki …\\"}\\n\\nevent: done\\ndata: {\\"message\\":{ …the message DTO… }}\\n```\\n\\nOne to eight `delta` events, then exactly one `done` carrying the finished\\nmessage; or, if the turn failed, a single `error` event\\n(`{\\"code\\":\\"timed_out\\",\\"message\\":\\"…\\"}`) and nothing else. Then the stream\\ncloses. A stream opened *after* the answer already landed still emits\\n`delta`s and a `done` β€” the replay is deliberate, so a client that connects\\nlate (or reconnects) never hangs waiting for events that already happened.\\n\\n**The deltas are sliced by the backend from the finished answer.** `hab/1` is\\nunary β€” the service returns the whole reply text, not tokens β€” so today the\\nchunking is cosmetic pacing, not real streaming. The event shape exists now so\\nthat the day a service streams, it becomes a drop-in change behind an\\nunchanged frontend.\\n\\n### The message DTO\\n\\n```json\\n{ \\"id\\": \\"01J8…\\", \\"thread_id\\": \\"01J8…\\", \\"role\\": \\"assistant\\",\\n \\"status\\": \\"complete\\", \\"content\\": \\"…\\", \\"truncated\\": false, \\"error_code\\": null,\\n \\"created_at\\": 1761820800000, \\"completed_at\\": 1761820803120 }\\n```\\n\\n`role` is `user` or `assistant`; `status` is `pending`, `complete`, or\\n`failed` (a user turn is always `complete`). `content` is empty while pending,\\n`error_code` is set only when failed, `completed_at` is `null` until the turn\\nsettles. `truncated` is `true` when `content` is only the first part of what\\nthe assistant answered β€” the rest was over `max_chatbot_message_len` and was cut;\\nit is always `false` for a user turn and for a failed one. Show it: a clipped\\nanswer that looks whole is worse than one the reader knows is clipped. The same\\nDTO is what the SSE `done` event carries, so the streaming and polling reads\\nagree about `truncated` exactly as they do about every other field.\\n\\n### Status codes\\n\\n| code | when |\\n| --- | --- |\\n| `202` | the turn was accepted; the answer is on its way |\\n| `400` | empty message, or longer than the school's `max_chatbot_message_len` |\\n| `404` | no such thread or message β€” or not the caller's |\\n| `409` | already at `max_chatbot_threads`; delete a thread first |\\n| `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |\\n| `503` | no connected service offers `chat.reply` β€” **nothing was written**, retry later |\\n\\nThe `503` ordering matters: availability is checked before the rows exist, so\\nan unavailable service leaves no dead `pending` row behind, and the rate limit\\nis charged before that, so a refused turn leaves no trace at all. The check is\\nthe backend's own worker registry, which owns the QUIC sockets and is therefore\\nthe whole truth about what can be answered.\\n\\n### A turn always settles\\n\\nOnce the two rows exist the answer never stays `pending` forever, through\\nthree independent mechanisms:\\n\\n- the task that owns the bridge round trip stamps `complete` or `failed` β€”\\n the normal path;\\n- a reader **projects** a `pending` row older than 300 seconds as\\n `failed`/`timed_out` (a read-time projection, not a write β€” the row is left\\n for the task that may still own it);\\n- a **boot sweep** flips every leftover `pending` past the 300-second horizon\\n to `failed`/`interrupted`, which is what a process death mid-inference looks\\n like. Younger rows are left alone, since one may still be in flight.\\n\\nA restart therefore loses a turn that was in flight: it settles\\n`failed`/`interrupted` rather than being answered. Accepted β€” the backend is a\\nsingle process with stop-the-world deploys, so there is no peer that could have\\ntaken it over.\\n\\nTwo more verdicts come from inspecting the answer: an **empty** reply is\\nreported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a\\nbug), and an **over-long** one is truncated to `max_chatbot_message_len` β€” a\\nclipped answer still helps, a discarded one does not β€” with `truncated: true`\\non the stored turn, so the clip is never passed off as the whole answer.\\n\\n`error_code` values a client may see: `unavailable` (no worker, or the bridge\\nis off), `busy`, `timed_out`, `transport`, `protocol`, `bad_reply` (the\\nservice's payload did not parse), `empty_reply`, `service_error`,\\n`interrupted`, `not_found`, `internal` β€” **or a code the AI service itself\\nreturned**, verbatim. Treat it as an open set: branch on the ones you handle,\\nfall back to the human-readable text for the rest.\\n\\n### The `chat.reply` capability (for AI-service authors)\\n\\nA chat service declares `chat.reply` in its `Hello` (see \\"AI bridge (QUIC)\\").\\nRequests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:\\n\\n```json\\n{ \\"message\\": \\"and the second law?\\",\\n \\"history\\": [ {\\"role\\":\\"user\\",\\"content\\":\\"what is the first law?\\"},\\n {\\"role\\":\\"assistant\\",\\"content\\":\\"an object at rest …\\"} ] }\\n```\\n\\n`history` is **oldest first** (index 0 is furthest back), optional (absent or\\n`[]` = a fresh thread), and **excludes** the new message β€” that one is\\n`message`. It carries the last `chatbot_history_turns` **settled messages** β€”\\nentries, not exchanges: the default `10` is five question/answer pairs, and\\n`history` is exactly that many entries long whenever the thread holds enough\\nof them. Only settled turns count: a failed answer is skipped and the window\\nreaches further back for a usable one, rather than coming up short. All of it\\nis re-sent on every request, which is why the service may be stateless: it can\\nrestart, scale out, or be replaced mid-thread without losing context.\\n\\nThe answer is a `Response::Ok` whose payload is:\\n\\n```json\\n{ \\"text\\": \\"the complete reply, not chunked, not partial\\" }\\n```\\n\\nFailures reuse the existing `Response::Err {code, message}` β€” one failure\\nshape on the bridge for every capability β€” and that `code` reaches the client\\nas the message's `error_code`.\\n\\n**Unknown extra keys are ignored on both sides, on purpose.** A service may\\nadd fields (a model name, token counts) and a future backend may send more\\ncontext without either end having to be redeployed in lockstep.", "source": "README.md"}, {"id": "collaborative-whiteboard", "title": "Collaborative whiteboard", "body": "A board is a shared canvas whose membership is an **ad-hoc invite list**: the\\ncreator names participant user ids at `POST /boards` and that is the whole\\nmodel β€” no course, no lesson session, no appointment. Any account from\\n`student` upwards may open one. **Every participant draws; the creator\\nalone clears, locks, closes or deletes.**\\n\\n**No parents, anywhere.** The `parent` role is the school's read-only observer,\\nand it has no whiteboard access at all β€” not a view-only tier, none. It is\\nrefused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named*\\nin an invite list either: `resolve_participants` rejects a parent id with a\\n`400`, so a parent is never on a roster in the first place. That one cut is\\nwhat closes the rest β€” never on a roster means the id-scoped routes and the\\nroom's door already answer the outsider's `404` (never a `403`, which would\\nconfirm the board is there), and no socket opens, so no `stroke` frame can be\\nsent. The role bar is re-checked on the read path and at the door as well, so a\\nboard row written before this rule that still lists a parent is inert: that\\nparent sees a `404` for it like any stranger.\\n\\n**Two doors, two statuses.** A caller who is not on a board gets a `404` on\\nevery route, its existence included β€” an outsider must never learn a board is\\nthere. A participant who is not the creator has already been told it exists, so\\nthe four creator-only commands answer them a `403`: hiding it at that point\\nwould be a lie their client cannot act on. Over the socket the same refusal is\\n`error{code:\\"forbidden\\"}` and the socket **stays open** β€” someone clicking a\\nbutton they don't own must not lose the canvas they were drawing on.\\n\\n**A clear deletes nothing.** Strokes are append-only. `POST /boards/{id}/clear`\\nbumps the board's `epoch` and appends a `clear` **marker** carrying the epoch\\nit closed, that epoch's final stroke count, who cleared and when β€” so the live\\ncanvas empties while every mark ever drawn stays stored and replayable. Those\\nmarkers *are* the epoch index, which is why there is no epochs table and why\\nthe open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.\\n`DELETE /boards/{id}` is the one operation here that really destroys marks.\\n\\n**Three caps, and only one of them is terminal** (all three published at `GET\\n/limits` under `board`):\\n\\n- `max_epoch_strokes` bounds the **live** canvas β€” `epoch_stroke_count`, which\\n every clear resets. Hitting it is **recoverable**: the creator clears, the\\n history is kept, drawing resumes.\\n- `max_board_strokes` bounds the board's **lifetime** storage β€”\\n `total_stroke_count`, which never resets, because a clear keeps its history.\\n Hitting it stamps `closed_at` and the board becomes **permanently\\n read-only**: still fully readable and replayable, never deleted, and there is\\n no reopen β€” open a new board. `POST /boards/{id}/close` is the manual form of\\n the same thing, and idempotent.\\n- `max_boards_per_creator` bounds how many boards one creator holds\\n (`board_count` on the user row). Deleting a board frees a seat; closing one\\n does not β€” a closed board is still stored.\\n\\n**Two ways to read the marks, and the difference matters most to a client\\nauthor.** A socket `join` replays the **current epoch only**; history never\\nrides the socket. History is an explicit paged REST read:\\n`GET /boards/{id}/history` (the board's whole life, oldest first, `clear`\\nmarkers included, `?epoch=` for a single one) and `GET /boards/{id}/epochs`\\n(the marker index β€” enough to offer \\"replay session 3\\" without scanning the\\nlog). `GET /boards/{id}/strokes` is the current epoch over REST, the catch-up\\nand fallback path for the same canvas the socket replays β€” with one deliberate\\ndifference: the REST read is *not* filtered by kind, while the socket serves\\n`kind: \\"stroke\\"` rows only. In the steady state that is a distinction without a\\ndifference, since a marker is written with the epoch it *closed* and the open\\nepoch has none; the case where it shows is a clear landing between the board\\nread and the row read, which surfaces that epoch's closing marker in the page.\\nFor a live canvas the socket is the authority.\\n\\n**The board room (WebSocket)** β€” `GET /boards/{id}/ws`, cookie-authed like\\neverything else and, like the exam room, outside the OpenAPI spec (an upgrade\\nis not describable there); REST remains the full fallback. The gate before the\\nupgrade is the same `404` door: not a participant, no room. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| client β†’ | `{\\"type\\":\\"join\\", \\"after\\":\\"<last stroke id>\\", \\"epoch\\":3}` β€” both optional; replay the current epoch |\\n| server β†’ | `{\\"type\\":\\"state\\", board, epoch, locked, closed_at, creator, participants, now}` on connect and every `ws_tick_secs` |\\n| server β†’ | `{\\"type\\":\\"strokes\\", epoch, strokes:[{id, author, payload}]}` β€” one replay chunk, repeated until the epoch is served |\\n| server β†’ | `{\\"type\\":\\"synced\\", epoch, cursor}` β€” the replay is complete; `cursor` is what to resume from |\\n| client β†’ | `{\\"type\\":\\"stroke\\", \\"payload\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` β€” any participant |\\n| server β†’ | `{\\"type\\":\\"saved\\", id, client_seq?}` β€” your stroke landed |\\n| server β†’ | `{\\"type\\":\\"stroke\\", id, author, payload, epoch}` β€” someone *else* drew |\\n| client β†’ | `{\\"type\\":\\"clear\\"}` / `{\\"type\\":\\"lock\\", \\"locked\\":true}` β€” **creator only** |\\n| server β†’ | `{\\"type\\":\\"cleared\\", …}` / `{\\"type\\":\\"locked\\", locked, by}` β€” the canvas was emptied / drawing was paused |\\n| server β†’ | `{\\"type\\":\\"closed\\", …}` / `{\\"type\\":\\"deleted\\"}` β€” the board is finished; both end the room |\\n| server β†’ | `{\\"type\\":\\"participants\\", creator, participants}` β€” the roster changed; a socket no longer on it is dropped |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", code, message, client_seq?}` |\\n\\nA `stroke` may carry a `client_seq` exactly as an exam-room `answer` does: any\\nvalue the client picks, echoed **verbatim** on that message's `saved` or\\n`error` and on nothing else, omitted entirely when the request omitted it. The\\nserver never reads it.\\n\\n`error` codes are a closed set: `epoch_full` (the live canvas is full β€” clear\\nit and keep drawing), `board_closed` (permanently read-only), `locked`,\\n`forbidden` (a creator-only command from a participant), `resync` (below),\\n`invalid` (bad JSON, an unknown frame, an over-long payload), `not_found`,\\n`unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\n**Persist, then publish.** A stroke is fanned out only after its row has\\nlanded, so the channel can never carry a mark the database refused (a locked\\nboard, a full epoch, a closed board). The database is the canvas; the channel\\nis a notification *about* it β€” which is why a client dedupes by stroke `id`,\\nwhy a resync deliberately re-serves marks it already drew, and why a frame is\\nnever the authority: every stroke, clear and lock re-reads the board and\\nre-checks the roster, so a socket that missed a `participants` or `locked`\\nframe is refused all the same. One consequence of the same read-then-write\\nshape: a stroke carries the epoch the server read for it, so a clear landing in\\nthat instant can file one stroke under the epoch it just closed β€” the stroke is\\nkept and stays replayable in `/history`, it simply is not on the new canvas.\\n\\n**Reconnecting.** `join` carries a cursor: `after`, the last stroke id already\\ndrawn, plus the `epoch` it belongs to. Same epoch and only what is newer is\\nreplayed; an older epoch β€” or no cursor at all β€” gets a `cleared` frame first\\nand then the whole current epoch, because a cursor into a closed epoch no\\nlonger means anything. If the room falls behind a slow socket the server sends\\n`error{code:\\"resync\\"}` and immediately replays the current epoch **out of the\\ndatabase**: the client does not re-join, it throws its canvas away and takes\\nwhat follows. The database is always the source of truth, never the channel.\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/boards/${id}/ws`);\\nlet epoch = null, cursor = null, seq = 0;\\nws.onopen = () => ws.send(JSON.stringify({ type: \\"join\\", after: cursor, epoch }));\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"cleared\\") wipeCanvas();\\n if (m.type === \\"strokes\\") m.strokes.forEach(draw); // dedupe by m.id\\n if (m.type === \\"synced\\") ({ epoch, cursor } = m);\\n if (m.type === \\"stroke\\") draw(m);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.id);\\n if (m.type === \\"error\\" && m.code === \\"resync\\") wipeCanvas();\\n};\\nconst send = (payload) =>\\n ws.send(JSON.stringify({ type: \\"stroke\\", payload, client_seq: ++seq }));\\n```", "source": "README.md"}, {"id": "concurrency-model", "title": "Concurrency model", "body": "The backend runs as **one process against one database**, and that buys less\\nthan it sounds like: every request is an async task, dozens are in flight at\\nonce, and each of them awaits the database in the middle of its work. So\\n\\"read, decide, write\\" is never safe on its own β€” SurrealDB does not\\nconflict-check a cross-record `count()` against a concurrent insert\\n(write-skew), and that fires between two tasks in one process exactly as it\\nwould between two machines. The mutex-only design this replaced was already\\nlosing races at one process. Every invariant is therefore guarded where the\\ndatabase itself decides the winner. Three tiers:\\n\\n1. **Single-row conditional writes** β€” compare-and-set (`save_if_unchanged`),\\n `UPDATE … WHERE`, stored counters (`domain::cap`). A single-record write is\\n atomic, so of N concurrent tasks exactly the allowed number get a non-empty\\n result: the database decides the winner, the loser retries\\n (`CAS_UPDATE_RETRIES`) or gets a 409.\\n2. **In-transaction `IF … THROW` gates** β€” the check runs inside the same\\n statement as the write it authorizes, so it is atomic with it. Used where\\n the rule reads the row being written (state machines, delete guards).\\n \\"Is anything still attached?\\" is answered the same way, by a counter on the\\n row being deleted rather than a `SELECT` over the children: a course is\\n deletable while its `enrollment_count` is zero, a term while its\\n `course_count` is (courses claim that reference *before* they write the\\n link, and give it back when the link moves or the course is deleted). A fee\\n plan reads the same way β€” editable *and* deletable while its\\n `assignment_count` is zero, and frozen for good once it is not, since an\\n assignment is never taken back.\\n Where the child also carries a deterministic id β€” one enrollment per\\n (course, user), one registration per (event, user), one fee-plan assignment\\n per (plan, student) β€” the seat and the row\\n are claimed in one transaction (`cap::claim_and_create`), so a duplicate\\n `CREATE` rolls its own seat back instead of costing a stranger their place.\\n3. **Two accepted races**, reviewed and deliberately left open:\\n - *Attempt-seq late save* β€” an exam-room socket writes into the sitting it\\n joined with, a choice made before any lock is taken, so a save racing a\\n retake can stamp an answer onto the just-terminal previous sitting.\\n Damage: one history row; the grade of record (latest `seq`) is never\\n touched.\\n - *Approved-overlap* β€” two approvals landing in the same instant can\\n double-book a teacher. Damage: one overlapping half-hour, visible to both\\n parties, fixable by cancelling either side.\\n\\nIn-process locks remain, and they are a *second* line, never the guarantee:\\n`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional\\n-write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is\\nthe cap β€” the lock only tames the retry loop, and keeps the tests' in-memory\\nengine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in\\nfront of a rule no single-record write can express. Removing one of them costs\\nthroughput or an accepted race; removing the conditional write behind it costs\\nthe invariant.\\n\\nBoot is unconditional: the schema batches, the backfills and the admin seed all\\nrun on every start, because exactly one process ever starts. Deployment is\\nstop-the-world β€” `podman compose down` then `up`, never overlapping β€” and a\\nrelease that adds or renames a stored counter *requires* it. An old binary\\nwrites rows without touching the new counter, the `= NONE` backfill guard\\n(correctly) refuses to re-seed, and the resulting permanent under-count lets a\\nguard approve exactly what it exists to refuse. In-flight work does not survive\\na restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.", "source": "README.md"}, {"id": "layout", "title": "Layout", "body": "```\\nsrc/\\n main.rs bootstrap: config, db, router, serve\\n lib.rs build_router: routes + OpenAPI/Swagger + CORS + /health\\n config.rs env-sourced Config\\n constant.rs validation limits\\n validate.rs field validators (used by every newtype's try_new)\\n error.rs ValidationError + AppError -> HTTP responses\\n database.rs SurrealDB server connect (ws) + SCHEMAFULL migration\\n migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,\\n MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them\\n rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier\\n state.rs AppState { db, files_path, cookie_secure, rate_limit,\\n chatbot_limit, exam_presence, board_hub, db_up, ai }\\n ai/ QUIC bridge to the out-of-process AI services\\n (see \\"AI bridge (QUIC)\\"; the HTTP half is web/ai.rs)\\n protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing\\n server.rs AiBridge: listener, handshake, dispatch over per-request streams\\n registry.rs connected workers, capability routing, least-inflight leases\\n tls.rs listener certificate (PEM or self-signed) + fingerprint\\n error.rs AiError\\n chat.rs the `chat.reply` payload contract (ChatRequestPayload/ChatReplyPayload)\\n domain/ validated newtypes + entities (derive SurrealValue),\\n each owning its persistence\\n user.rs UserId Β· Username Β· Password Β· PasswordHash Β· User (has role)\\n role.rs Role enum (student < teacher < manager < admin), at_least()\\n field_update.rs FieldUpdate: one UPDATE ... SET built from only the fields a\\n PATCH actually carried (an omitted field is never written)\\n monotonic_id.rs next_ulid: ids that sort in write order β€” one process-wide\\n Generator, so same-millisecond rows never scramble\\n key.rs sitting(): the deterministic per-sitting record key shared by\\n attempts, answers, answer images and results (seq 1 stays bare)\\n cap.rs claim()/release(): the count caps the database enforces β€” an\\n atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter\\n column of the parent row, replacing count-then-write mutexes\\n that could not see a concurrent insert;\\n claim_and_create() commits that seat and the child row in\\n one transaction, for children with a deterministic id\\n text_fold.rs case- and diacritic-insensitive folding for search, shared by\\n the Rust needle and the SurrealQL column (Turkish Δ°/Δ±, ΓΌ, â…)\\n session.rs SessionId Β· SessionToken Β· Session (7-day expiry)\\n timestamp.rs Timestamp (unix-millisecond instant)\\n note.rs NoteId Β· NoteTitle Β· NoteContent Β· Note\\n note_file.rs NoteFileId Β· FileName Β· FileContentType Β· NoteFile (metadata row;\\n blob on disk under FILES_PATH, named by the row's ULID)\\n event.rs EventId Β· EventTitle Β· EventDescription Β· Event\\n attendance.rs AttendanceId Β· AttendanceStatus Β· Attendance\\n course.rs CourseId Β· CourseTitle Β· CourseDescription Β· Course\\n course_session.rs CourseSessionId Β· SessionTopic Β· CourseSession (a course's lesson)\\n session_attendance.rs SessionAttendanceId Β· SessionAttendance (roll call; one row per session+user)\\n work_entry.rs WorkEntryId Β· WorkEntry (staff stint; one open per user by construction)\\n enrollment.rs EnrollmentId Β· Enrollment (one row per course+user)\\n exam.rs ExamId Β· ExamTitle Β· ExamDescription Β· ExamKind Β· ExamWeight Β·\\n ExamMode Β· ExamDuration Β· ExamSchedule Β· Exam (belongs to a course)\\n exam_attempt.rs ExamAttemptId Β· AttemptStatus Β· ExamAttempt (numbered sittings per exam+user, metered by max_attempts)\\n exam_question.rs ExamQuestionId Β· QuestionText Β· QuestionKind Β· QuestionPoints Β·\\n ChoiceText Β· QuestionSpec Β· ExamQuestion (choice|text, per exam)\\n exam_answer.rs ExamAnswerId Β· AnswerText Β· ExamAnswer (one row per question+user) Β·\\n auto_score (choice-question suggestion)\\n exam_result.rs ExamResultId Β· Mark Β· ExamResult (one row per exam+user)\\n question_image.rs QuestionImageId Β· QuestionImage (question/choice picture\\n metadata; bytes on disk under FILES_PATH)\\n answer_image.rs AnswerImageId Β· AnswerImage (student answer-drawing\\n metadata; bytes on disk under FILES_PATH)\\n bank_question.rs BankQuestionId Β· BankQuestion (school-wide reusable\\n question template, copied into exams; no exam FK)\\n bank_question_image.rs BankQuestionImageId Β· BankQuestionImage (bank\\n question/choice picture metadata; bytes on disk under FILES_PATH)\\n profile.rs PersonName Β· Email Β· Phone Β· BirthDate (personal-info newtypes)\\n preferences.rs Theme Β· Language Β· PaletteColor (own UI preferences)\\n message.rs MessageId Β· MessageSubject Β· MessageBody Β· MessageLabel Β·\\n Message (per-copy folders: inbox/sent/archive/trash)\\n parent_link.rs ParentLinkId Β· ParentLink (parent↔student tie = the parent's read grant)\\n registration.rs RegistrationId Β· Registration (a seat on a registration event's signup list)\\n subject.rs SubjectId Β· SubjectName Β· SubjectDescription Β· Subject (course curriculum)\\n term.rs TermId Β· TermName Β· Term (school term window)\\n menu.rs MenuId Β· MenuDate Β· MenuSlot Β· Menu (one published menu per\\n calendar day + meal slot; slot snapshotted as text)\\n menu_dish.rs MenuDishId Β· DishName Β· DishDescription Β· DishPrice Β·\\n DishTags Β· MenuDish (a dish on a menu; price in minor units)\\n dietary_profile.rs DietaryProfileId Β· DietaryTags Β· DietaryNote Β·\\n DietaryProfile (what one student may not eat; keyed by the\\n student, tagged from the same `dietary_tags` list a dish is)\\n meal_booking.rs MealBookingId Β· MealBookingStatus Β· MealBooking (one seat\\n per (menu, student); a cancel flips the status, never deletes)\\n meal_attendance.rs MealAttendanceId Β· MealAttendanceStatus Β· MealAttendance\\n (who actually ate; one row per (menu, student), reporting\\n only β€” it never touches the ledger)\\n meal_ledger.rs MealLedgerId Β· MealLedgerKind Β· LedgerAmount Β· LedgerMethod Β·\\n LedgerNote Β· MealLedger (append-only money; the balance is\\n always the fold, never a stored field)\\n fee_plan.rs FeePlanId Β· FeePlanName Β· Installment Β· FeePlan (a school fee\\n plan; installments embedded on the row, past due dates legal)\\n fee_plan_assignment.rs FeePlanAssignmentId Β· FeePlanAssignment (one plan on\\n one student, keyed `<plan>_<student>`; assigning appends\\n every installment charge, a replay appends nothing)\\n payment_ledger.rs PaymentLedgerId Β· PaymentLedgerKind Β· PaymentLedger\\n (append-only school fees: charge/credit/reversal/refund, a\\n credit names its charge and a refund its credit; the balance\\n is always the fold; over-payment cap is advisory)\\n settings.rs ExamKindDef Β· GradeBand Β· Settings (per-school policy)\\n chatbot_thread.rs ChatbotThreadId Β· ChatbotThreadTitle Β· ChatbotThread (one\\n chatbot thread, private to its owner)\\n chatbot_message.rs ChatbotMessageId Β· ChatContent Β· MessageRole Β· MessageStatus Β·\\n ChatbotMessage (one turn; the assistant row is written\\n `pending` before the AI call and settled after)\\n board.rs BoardId Β· BoardTitle Β· Board (a collaborative whiteboard:\\n creator + ad-hoc participant list, `epoch`, the two stroke\\n counters and `closed_at`)\\n board_stroke.rs BoardStrokeId Β· BoardStroke (the\\n append-only stroke log; a `clear` row is the marker that\\n closed an epoch, carrying its final count β€” nothing is\\n ever deleted)\\n appointment_slot.rs AppointmentSlotId Β· SlotSeries Β· SlotNote Β·\\n AppointmentSlot (a teacher's published availability; a\\n recurring publish is expanded into rows sharing a series id)\\n appointment.rs AppointmentId Β· AppointmentStatus Β· AppointmentReason Β·\\n Appointment (a booking on a slot; occupancy is the slot's\\n stored `occupied` cap-1 counter, overlap is derived under\\n APPOINTMENT_LOCK)\\n pomodoro.rs PomodoroSessionId Β· PomodoroSession (student focus log)\\n pool_question.rs PoolQuestionId Β· PoolQuestionTitle Β· PoolQuestionBody Β·\\n PoolQuestion (student-asked question; teacher-approved into\\n the school-wide pool; optional photo as metadata + disk blob)\\n solution.rs SolutionId Β· SolutionBody Β· Solution (discussion thread on an\\n approved pool question; dies with the question)\\n homework.rs HomeworkId Β· HomeworkTitle Β· HomeworkDescription Β· Homework\\n (per-course assignment; required subject; optional `assigned`\\n student subset β€” absent/empty = the whole enrolled course)\\n homework_submission.rs HomeworkSubmissionId Β· SubmissionText Β·\\n HomeworkSubmission (one row per homework+user; immutable\\n submitted_at + moving updated_at β€” `late` is computed)\\n homework_file.rs HomeworkFileId Β· HomeworkFile (submission attachment\\n metadata; any content type; bytes on disk under FILES_PATH)\\n homework_result.rs HomeworkResultId Β· HomeworkStatus Β· HomeworkResult\\n (teacher grade: done/incomplete/missing + optional Mark; one\\n row per homework+user β€” its existence freezes the submission)\\n web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +\\n auth extractors\\n extractor.rs CurrentUser Β· RequireTeacher Β· RequireManager Β· RequireAdmin\\n dto.rs shared UserResponse Β· CourseResponse Β· ExamResponse Β· SessionResponse schemas\\n exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)\\n board_ws.rs the collaborative board room WebSocket (join replay, strokes\\n fanned out to every participant, clear/lock)\\n room.rs the plumbing both rooms share: sending a frame, classifying\\n an incoming message, an AppError as a readable code, and a\\n client_seq echoed untouched\\n page.rs PageParams Β· Page<T> (shared pagination)\\n etag.rs conditional-GET middleware: ETag over a 200 JSON body,\\n If-None-Match β†’ 304 (GET only; SSE and blobs pass through)\\n auth.rs users.rs notes.rs messages.rs events.rs appointments.rs\\n courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs\\n bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs\\n settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs\\n boards.rs\\n limits.rs GET /limits: every constant.rs bound served as JSON\\n```\\n\\nTests: `cargo test` β€” unit (in-source), integration (`tower::oneshot` + in-memory\\ndb), rate-limit (both tiers, proxy-header and peer-address keying, shipped\\nlimits over every route, two limiters sharing one budget over one db), e2e\\n(real TCP + reqwest cookie jar), persistence\\n(tempfile file engine, including close + reopen), ai-bridge (real QUIC on\\nloopback against a fake AI service), ai-protocol (the `hab/1` wire contract,\\ndriven by a client that shares no code with the backend).", "source": "README.md"}];
40+INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "16d576ae0877dbc7b21a88f129316c5b7eb833c95a064763ad4d7557b1dab3f2"}];
41+DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii;
42+DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25;
43+DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25;
44+REMOVE TABLE IF EXISTS endpoint;
45+INSERT INTO endpoint [{"id": "health", "routes": "| GET | `/health` | no | Liveness check |"}, {"id": "root", "routes": "| GET | `/` | no | Same as `/health` |"}, {"id": "time", "routes": "| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |"}, {"id": "limits", "routes": "| GET | `/limits` | no | Every fixed validation bound, grouped by resource \\u2014 see Validation limits |"}, {"id": "swagger", "routes": "| GET | `/swagger` | no | Interactive API docs (Swagger UI) |"}, {"id": "api-docs", "routes": "| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |"}, {"id": "ai", "routes": "| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |"}, {"id": "auth", "routes": "| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken \\u2014 see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |"}, {"id": "users", "routes": "| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` \\u2014 own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) \\u00b7 paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` \\u2014 find users by username/name fragment (pickers); refs only, no contact info \\u00b7 paged |\\n| GET | `/users` | admin | List all users \\u00b7 paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` \\u2014 set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` \\u2014 tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students \\u00b7 paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |"}, {"id": "notes", "routes": "| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes \\u00b7 paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) \\u2014 \\u2264 the school's `max_file_bytes`, \\u2264 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) \\u00b7 paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |"}, {"id": "messages", "routes": "| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` \\u2014 send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` \\u2014 the caller's folder, newest first; `?folder=inbox&read=false&limit=1` \\u2192 `total` is the unread badge \\u00b7 paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` \\u2014 read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** \\u2014 only from the trash (`409` elsewhere); the row vanishes once both sides deleted |"}, {"id": "events", "routes": "| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` \\u2014 `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` \\u2014 mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) \\u00b7 paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` \\u00b7 paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` \\u2014 seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |"}, {"id": "appointments", "routes": "| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` \\u2014 publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, \\u2264 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) \\u2014 a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar \\u2014 future slots only, demoted teachers' slots left out \\u00b7 paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` \\u2014 book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests \\u00b7 paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` \\u2014 call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included \\u2014 they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` \\u2014 counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal \\u2014 this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |"}, {"id": "courses", "routes": "| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` \\u2014 `kind` is `course` (default), `study` (et\\u00fct), or `club` (kul\\u00fcp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) \\u00b7 paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses \\u00b7 paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ \\u2014 **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` \\u2014 assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` \\u2014 enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u00b7 paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` \\u2014 add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` \\u2014 add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` \\u2014 add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) \\u00b7 paged |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` \\u2014 assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, \\u2264 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) \\u00b7 paged |"}, {"id": "subjects", "routes": "| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |"}, {"id": "sessions", "routes": "| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` \\u2014 roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) \\u00b7 paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |"}, {"id": "exams", "routes": "| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist \\u2014 the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` \\u2014 grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) \\u00b7 paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt \\u2014 students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) \\u00b7 paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question \\u2014 the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam \\u2014 copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** \\u2014 copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question \\u2014 text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` \\u2014 autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers \\u22c3 marks), ascending \\u2014 the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first \\u2014 the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** \\u2014 the answer key the caller checks their own sheet against (same review gate) \\u00b7 paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers \\u22c3 marks), ascending \\u2014 only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster \\u00d7 latest attempts \\u00d7 marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |"}, {"id": "bank-questions", "routes": "| GET | `/bank-questions` | teacher | The school-wide question bank \\u2014 `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) \\u00b7 paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist \\u2014 `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question \\u2014 the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |"}, {"id": "homework", "routes": "| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) \\u00b7 paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade \\u2014 the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades \\u2014 file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` \\u2014 hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part \\u2014 **any** content type, \\u2264 `max_file_bytes`, \\u2264 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) \\u2014 the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student \\u00d7 submission/files/grade + computed `late`/`missing`/`unenrolled` \\u2014 a straggler's stale work stays visible (course manager) \\u00b7 paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` \\u2014 grade `done`/`incomplete`/`missing` (+ optional 0\\u2013100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable \\u2014 that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) \\u2014 readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade \\u2014 un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows \\u2014 submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` \\u2014 full, statuses and marks only, never files \\u00b7 paged |"}, {"id": "questions", "routes": "| POST | `/questions` | student | `{title, body}` \\u2014 ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` \\u2014 the pool questions visible to the caller, each with its `solution_count` \\u00b7 paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question \\u2014 publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` \\u2014 offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first \\u2014 a discussion thread \\u00b7 paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` \\u2014 edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |"}, {"id": "marks", "routes": "| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "work", "routes": "| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) \\u00b7 paged |\\n| GET | `/work/{user}` | manager | A staff member's work log \\u00b7 paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` \\u2014 correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |"}, {"id": "pomodoro", "routes": "| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** \\u2014 a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` \\u00b7 paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape \\u00b7 paged; *or a `parent` linked to `{user}` |"}, {"id": "attendance", "routes": "| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "settings", "routes": "| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |"}, {"id": "terms", "routes": "| POST | `/terms` | manager | `{name, starts_at, ends_at}` \\u2014 past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first \\u00b7 paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term \\u2014 `409` while any course still links to it |"}, {"id": "meals", "routes": "| POST | `/meals/menus` | manager | `{date, slot, capacity?}` \\u2014 publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range \\u00b7 paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` \\u2014 the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` \\u2014 add a dish (\\u2264 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` \\u2014 record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` \\u2014 take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first \\u00b7 paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included \\u00b7 paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` \\u2014 mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu \\u00b7 paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day \\u00b7 paged \\u00b7 own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line |"}, {"id": "payments", "routes": "| POST | `/payments/plans` | manager | `{name, installments}` \\u2014 write a fee plan (1\\u201360 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first \\u00b7 paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it \\u2014 its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (\\u2264 200) \\u2014 place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first \\u00b7 paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` \\u2014 record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` \\u2014 hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` \\u2014 undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines \\u2014 charges, payments, refunds, reversals \\u2014 newest first \\u00b7 paged \\u00b7 own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |"}, {"id": "chatbot", "routes": "| POST | `/chatbot/threads` | student | `{title?}` \\u2014 start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first \\u00b7 paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` \\u2014 rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first \\u2014 user and assistant rows alike \\u00b7 paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (\\u2264 `max_chatbot_message_len`) \\u2014 send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` \\u2014 nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` \\u2014 or one `error` \\u2014 and close; an already-finished answer replays (see \\"Chatbot\\") |"}, {"id": "boards", "routes": "| POST | `/boards` | student | `{title, participant_ids?}` \\u2014 open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first \\u00b7 paged |\\n| GET | `/boards/{id}` | student | One board \\u2014 a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first \\u00b7 paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included \\u00b7 `?epoch=` for one epoch \\u00b7 paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) \\u00b7 paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` \\u2014 re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap \\u2014 nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board \\u2014 permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |"}];
46+REMOVE TABLE IF EXISTS doc;
47+REMOVE TABLE IF EXISTS meta;
48+INSERT INTO doc [{"id": "intro", "title": "intro", "body": "# hezarfen_backend\\n\\nNote, attendance, course + weighted exam mark backend. **Rust (edition 2024) Β· axum Β· SurrealDB 3 (server, WebSocket) Β· tokio.**\\n\\nSession-cookie auth with five hierarchical roles (`parent < student < teacher\\n< manager < admin`). A **`parent`** observes and changes nothing: admins tie\\nstudents to a parent account, and the parent reads those students' mark,\\nattendance, pomodoro, and homework reports β€” that's the whole role. Notes are per-user and carry **file attachments** (PDFs, documents,\\n…): blobs live on disk next to the database, metadata in the database, and the\\nper-file size cap is school policy in settings (`max_file_bytes`, default\\n5 MiB). Any two users can **message** each other, mail-style β€” subject +\\nbody into the recipient's inbox, each side filing its own copy through\\narchive/trash with a read flag the sender sees as a receipt (the only place a\\n`parent` writes). Attendance is event + attendees: create an event with an **audience**\\n(the whole school, one role, a course's enrollment, or a **registration**\\nsignup list β€” omit for school-wide), then teachers mark the expected attendees\\npresent / absent / late / excused (students never self-mark), and a **roster\\nreport** shows who was expected and who missed. Registration lists fill seat\\nby seat: teachers register students (never the other way round), staff\\nregister only themselves, an optional `capacity` caps the seats, and the list\\ncloses the moment the event starts (or, for an event with only an end time β€”\\na pure signup deadline β€” the moment that end passes). Every event stays visible to everyone β€”\\nthe audience is a roster, not a wall. Marks are course-shaped\\n(Google Classroom style): a teacher creates a course β€” kind **`course`** (a\\nregular class), **`study`** (a supervised study session β€” *etΓΌt*), or\\n**`club`** (a student club β€” *kulΓΌp*; same behavior, different label),\\noptionally capped by a `capacity` that refuses new enrolls once the roster is\\nfull β€” lays out its **subjects** (curriculum topics β€”\\nevery exam question must be tagged with one of its course's subjects, so\\nresults can later be read per topic), enrolls students, adds\\nexams inside it, and grades β€” enrolling, sitting exams, roll call, and marks are\\nall student-only, staff never take part. A course is run by whoever created it\\nplus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`):\\nan assigned teacher manages everything inside the course β€” exams, sessions,\\nsubjects, roster, grading β€” but can't delete it or change who else teaches it,\\nand a demotion below `teacher` sweeps their assignments away. Students read a per-course weighted average and\\nan overall average from their mark report β€” each exam weighted by its **kind**\\n(midterms can count double, orals once: weights are set per kind in settings,\\nnot per exam). Exams run **sync** (one\\nfixed window), **async** (start anytime inside the window, with a personal\\ntime budget), or **open** (sit anytime, optionally timed per attempt);\\nstudents *sit* them via attempts β€” retakes metered by a per-exam limit\\n(`0` = unlimited), each sitting keeping its own answers, drawings, and mark\\nso staff can read a student's full attempt history, leaving the exam room\\ngoverned by a teacher-controlled rejoin door. Writing an exam takes a while, so it can be saved as a\\n**draft** β€” invisible to students, unsittable, ungradable β€” and published\\nwhen it's ready. Questions can carry **images**: any question may hold one\\nillustration (a map above the prompt), and each option of a choice question\\nmay be a picture of its own (pick the right city off the map) β€” raster\\nuploads capped by the same `max_file_bytes` policy as note files. Good\\nquestions get reused, so a teacher+ can bank one in a school-wide **question\\nbank** β€” detached templates (with their own images) that any teacher copies\\ninto a fresh exam question across years, editable and deletable only by\\nwhoever saved them. Teachers\\nwatch attendance, per-student remaining time,\\nsittings, walk-outs, no-shows (`absent` once the window closes), submissions,\\nand marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out\\n**homework**: assigned to the whole class or a named subset (the unnamed never\\neven see it), tagged with a course subject, due by a required future `due_at`\\nβ€” students hand in text and/or **files of any type** (same size cap, 10 per\\nsubmission, served back only as forced downloads), editable until the teacher\\ngrades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark\\n(grading freezes the hand-in until the grade is removed); lateness is computed\\nfrom two stamps (first hand-in vs last touch), never stored, and homework\\nmarks stay out of the weighted `/marks` averages. Courses also carry **lesson\\nsessions** with teacher-taken roll call (students never self-mark a lesson),\\nstaff clock in/out on a server-stamped **work log**, students track study time\\nwith a server-stamped **pomodoro log** (the timer runs in the frontend; the\\nbackend records the focus stints, and teachers can read any student's log),\\nand every user has an\\n**attendance report** (event + per-course lesson tallies with rates).\\nA school-wide **question pool** runs on moderation: a student asks a question\\n(optionally attaching one photo of the problem β€” raster only, same\\n`max_file_bytes` cap), a teacher+ **approves** it into the pool (or deletes\\nit β€” rejection is deletion, there is no rejected state), and every approved\\nquestion is readable by the whole school with anyone free to offer\\n**solutions** under it (parents stay out) β€” text plus an optional photo of\\nthe worked steps, both editable by the solution's author anytime; pending\\nquestions show only to their asker and to teacher+, and approval freezes the\\ncontent so nothing unmoderated ever reaches the pool.\\nTeachers keep an **appointment calendar**: a teacher+ publishes availability\\nslots (one-off, or repeating weekly up to an `until` date as a series that\\ndeletes as one), and students and parents book a slot with a reason β€” the\\nbooking lands `pending` until the teacher approves it, rejects it, or\\ncounter-proposes another time (which sends it back to `pending` for the\\nrequester to accept or decline); the **requester** may cancel until the meeting\\nstarts β€” a teacher ends a booking by rejecting it, or by counter-proposing and\\nthen rejecting an approved one β€” one live booking holds a slot, a teacher's own\\npublished windows may not overlap each other, and no approved meeting may\\noverlap another for the teacher or the requester (see \\"Appointments\\").\\nSchool-varying policy is data, not code: exam kinds (each with its weight in\\ncourse averages), attendance statuses, grade-display bands, the note-file\\nsize limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms**\\nare plain rows courses can link to (see \\"Per-school policy\\"). Each account\\nalso carries its own **UI preferences** β€” theme (`light`/`dark`), language\\n(`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` β€”\\nany hex, deliberately not a fixed palette) β€” self-managed, admin-editable for\\nanyone, `null` until chosen so the client can fall back to the device\\npreference (or, for the accent, its own default).\\nThe **AI features live in separate projects**, so the backend also opens a\\nQUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in,\\nregister the capabilities they serve, and each request rides its own QUIC\\nstream on that one connection β€” no correlation ids, no head-of-line blocking.\\nThe bridge's certificate is published at `GET /ai/certificate` so a service can\\npin it before dialling (see \\"AI bridge (QUIC)\\").\\nThe first thing riding that bridge is the **chatbot**: every signed-in user\\n(`parent` included) keeps private threads with an AI service, free-form β€”\\nno rule tables, no canned answers, the backend only owns auth, limits,\\npersistence and the payload format. Sending is asynchronous because an\\ninference outlives a request: the turn plus an empty `pending` answer are\\nwritten *first*, the call goes out after, so a reload never loses an answer;\\nthe client then polls the message or reads it off an SSE stream (see\\n\\"Chatbot\\").\\nAny account from `student` upwards can also open a **collaborative\\nwhiteboard** (a `parent` gets no whiteboard access at all β€” it can neither open\\none nor be invited onto one): a titled board whose membership is an **ad-hoc\\ninvite list** β€”\\nthe creator names participant user ids, and no course, session or appointment\\nis involved. Every participant draws over a WebSocket, the creator alone\\nclears, locks, closes or deletes, and someone who is not on a board gets a\\n`404` for it on every route, existence included. Strokes are **append-only and\\na clear deletes nothing** β€” it bumps the board's epoch, so the live canvas\\nempties while every mark ever drawn stays stored and replayable through the\\nhistory reads (see \\"Collaborative whiteboard\\").\\nThe school's **food program** is published here too: a manager puts up one\\n**menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot`\\ndrawn from the school's `meal_slots`, unique per pair), lists its **dishes**\\nwith dietary tags from the school's own list, and prices them in **minor\\nunits** (kuruş) as integers β€” this API never speaks decimals or floats about\\nmoney. A student's own **dietary profile** is tagged from that same list\\n(manager-written β€” an allergen list is a school record, not a self-service\\npreference), so every dish a menu read returns names the tags it `conflicts`\\nwith for whoever is reading. Every authenticated user reads what is being\\nserved; students (or their parents) book a seat, and every seat writes a line into an\\n**append-only** meal ledger whose balance is derived and never stored (see\\n\\"Food program: menus, dishes, bookings & the ledger\\").\\nSchool **fees** are tracked the same way, in a ledger of their own: a manager\\nwrites a **fee plan** (a name and 1–60 installments, each an amount in minor\\nunits and a due date that may sit in the past) and **assigns** it to students,\\nwhich appends every installment as a `charge` at once β€” there is no scheduler,\\nand \\"overdue\\" is derived at read time. Payments are recorded against one named\\ncharge, refunds against one named payment, and nothing is ever edited or\\ndeleted: a mistake is corrected by appending the opposing line. **There is no\\nonline payment integration and none is planned** β€” no gateway, no card data,\\n`method` is free text. Teachers see no money at all (see \\"Payments\\").\\n\\nEvery field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)\\nconstructed only after its restrictions pass β€” invalid input can't be\\nrepresented. Those restrictions are published rather than left to be guessed:\\n**`GET /limits`** (no auth) serves every fixed bound and closed value set the\\nAPI enforces, read straight from the constants the newtypes use, so a frontend\\nvalidates against the server's own rules instead of a hand-kept copy (see\\n\\"Validation limits\\"). Those same types derive `surrealdb::types::SurrealValue`, so one\\ntyped value flows from HTTP request into the `SCHEMAFULL` database. Record ids\\nare ULIDs (time-sortable).", "source": "README.md"}, {"id": "run", "title": "Run", "body": "```sh\\nsurreal start --user root --pass root surrealkv:./data/hezarfen.db # the DB server\\ncp .env.example .env # optional\\ncargo run\\n```\\n\\nBoots on `http://127.0.0.1:8080`, talking to the SurrealDB server at\\n`DB_URL` (default `ws://127.0.0.1:8000`, root credentials via\\n`DB_USER`/`DB_PASS`) and storing uploaded note files in\\n`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs\\n(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at\\n`/api-docs/openapi.json`.", "source": "README.md"}, {"id": "run-in-a-container-podman", "title": "Run in a container (podman)", "body": "```sh\\npodman compose up -d --build # build + start, http://127.0.0.1:8080\\npodman compose logs -f backend\\npodman compose down # stop (data survives in the volume)\\n```\\n\\nThe `Containerfile` is a two-stage build (Rust builder with cargo cache\\nmounts, `debian:trixie-slim` runtime, non-root user). Two services: the\\n`surrealdb` server (official image, surrealkv storage) and the backend, which\\nwaits for the server's healthcheck and connects over `ws://surrealdb:8000`.\\nEach has its own named volume β€” `surreal-data` holds the database,\\n`hezarfen-data` the uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the\\ncontainer so the published port works. Production knobs (`COOKIE_SECURE`,\\n`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in\\n`compose.yaml` β€” uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset\\nmeans dev mirror mode without credentials; a cookie-using browser frontend\\nmust be allowlisted explicitly. Works with `docker compose` too.\\n\\nThe backend survives the database going away, at boot and at runtime.\\n\\nAt boot it retries the connection (1s doubling to 5s) until the server\\nanswers, rather than exiting. Exiting looks tidier but is worse: the container\\nruntime restarts the process, it fails again in milliseconds, and a few\\nseconds of startup skew burns the whole restart budget and leaves the backend\\ndown for good.\\n\\nAt runtime a keepalive query every 5s doubles as a liveness probe. This\\nmatters more than it sounds: a query issued while the socket is down does\\n*not* fail β€” the SDK's reconnect loop stops draining its request queue, so the\\nquery parks until the database returns and only *then* runs. Left alone, a\\nrequest waits out the entire outage and any write it carries lands long after\\nthe caller gave up.\\n\\nSo while the probe says the socket is down, requests are refused at the edge\\nwith `503` and `Retry-After: 1`, before they can reach the database. Nothing\\nis queued, which is what makes that retry safe. Requests that slip through in\\nthe window between the socket dying and the probe noticing are capped at 30s\\nand answer `503` *without* `Retry-After`, with a message saying the write may\\nor may not have applied β€” they were already queued, so retrying them could\\napply the same write twice. WebSocket and SSE routes are unaffected: both\\nreturn their response immediately and stream afterwards.\\n\\nWithout compose:\\n\\n```sh\\npodman build -t hezarfen-backend .\\npodman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backend\\n```", "source": "README.md"}, {"id": "auth-model", "title": "Auth model", "body": "Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, stored\\nserver-side). Send it back on later requests. Every endpoint below whose `Auth`\\ncolumn names a role requires a valid session; the ones marked `no` (`/health`,\\nthe docs pages, `register` / `login` / `logout`) don't (`logout` is idempotent β€”\\nit clears the session if one is present). Set `COOKIE_SECURE=true` when serving\\nbehind TLS to add the cookie's `Secure` attribute.\\n\\n**Register never reveals whether a username is taken.** `POST /auth/register`\\nanswers `201` either way with the *same* body β€” `{username, role}`, the echoed\\nname and the `student` role every fresh account gets. Both outcomes return one\\nvalue built before the insert is even attempted, so they are byte-identical by\\nconstruction. This is deliberate: the route is unauthenticated, so a `409` (or a\\nfaster reply) would let anyone enumerate the school's users. The password is\\nhashed *before* the availability check so both outcomes cost the same ~33ms.\\n\\nThe reply carries **no `id`**: on the taken path there is no row to name, and a\\nfabricated one would leave the client holding an id that matches nothing. Log\\nin and read `GET /auth/me` to learn who you are. The accepted cost: a caller who\\ncollides with an existing account gets no distinct error and simply cannot log\\nin with that password β€” they pick another name. Do not \\"fix\\" this back to a\\n`409`, and do not add an `id` back.", "source": "README.md"}, {"id": "time-policy", "title": "Time policy", "body": "Timezones and clock differences cannot corrupt data, by construction:\\n\\n- **Every instant is a UTC unix-millisecond `i64`** (`domain::timestamp::Timestamp`),\\n stored as an `int`, sent as a plain number. Nothing stores or parses a\\n timezone, so the server's `TZ`, the container's clock config, and the\\n client's locale are all irrelevant β€” clients convert millis to local time\\n for display only.\\n- **One clock choke point.** `Timestamp::now()` is the only wall-clock read.\\n `clippy.toml` bans every other source (`chrono::Local`/`Utc::now`,\\n `SystemTime::now`, `time::OffsetDateTime::now_*`, absolute cookie\\n `Expires`) and `[lints.clippy]` raises that to a hard `cargo clippy` error,\\n so local-time bugs can't be reintroduced.\\n- **Expiry is server-authoritative.** Sessions expire by comparing the stored\\n millis against the server clock; the cookie carries a relative `Max-Age`\\n (never an absolute `Expires`), so a wrong client clock changes nothing.\\n- **Pacing uses the monotonic clock.** The rate limiter runs on `Instant`,\\n immune to NTP steps and wall-clock jumps.\\n- **Calendar dates get a timezone grace.** A birth date is a calendar date on\\n the writer's wall, not an instant: validation accepts up to UTC-tomorrow,\\n since a client ahead of UTC (up to UTC+14) legitimately writes a date the\\n server's UTC calendar hasn't reached yet.\\n- **Times-of-day are UTC too, and staff enter them that way.** A meal slot's\\n `serving_minute` (minutes past midnight, `0`–`1439`) is the one clock-face\\n value a school types in, and it is read as UTC on the menu's `date` β€” there\\n is deliberately **no school-timezone setting** (a rejected feature), so a\\n UTC+3 school enters `540` (09:00 UTC) for a meal served at noon locally.\\n- **Nothing schedules in the past.** A request-supplied schedule instant β€” an\\n exam window, a lesson's `starts_at`/`ends_at`, an event time β€” must not lie\\n before the server's now, on create and on every `PATCH` that sets it: a\\n deadline that starts in the past is dead on arrival, so it's a `400`. A\\n 60-second grace absorbs request latency and client-clock skew (\\"starts now\\"\\n survives its own round trip). Values a `PATCH` merely keeps are exempt β€” a\\n running exam's `starts_at` is legitimately past, and a rename or deadline\\n extension must not trip over it. (Work-log corrections are records of past\\n work, not schedules, and stay free.)\\n- **Frontends can sync to the server clock.** `GET /time` (no auth) returns\\n `{\\"now\\": <UTC unix-millis>}`. Fetch once, keep\\n `offset = now - Date.now()`, and use `Date.now() + offset` for countdowns\\n and past/future checks instead of trusting the device clock.\\n\\nKeep the single server's clock NTP-synced; that's the only clock that matters.", "source": "README.md"}, {"id": "validation-limits", "title": "Validation limits", "body": "Every fixed bound the API enforces is published at `GET /limits` (no auth), so\\na client never has to hard-code a copy that drifts the day a constant moves.\\nThe handler reads `src/constant.rs` directly β€” a changed constant changes the\\nresponse in the same commit.\\n\\n```json\\n{\\n \\"user\\": { \\"min_username_len\\": 3, \\"max_username_len\\": 32,\\n \\"username_separators\\": [\\".\\", \\"_\\", \\"-\\"],\\n \\"reserved_usernames\\": [\\"admin\\", \\"…\\"],\\n \\"min_password_len\\": 6, \\"max_password_len\\": 128,\\n \\"max_name_len\\": 100, \\"max_email_len\\": 254,\\n \\"min_phone_digits\\": 7, \\"max_phone_digits\\": 15,\\n \\"roles\\": [\\"parent\\", \\"student\\", \\"teacher\\", \\"manager\\", \\"admin\\"],\\n \\"themes\\": [\\"light\\", \\"dark\\"], \\"languages\\": [\\"tr\\", \\"en\\"],\\n \\"palette_color_pattern\\": \\"^#[0-9a-fA-F]{6}$\\", \\"palette_color_len\\": 7,\\n \\"session_duration_days\\": 7 },\\n \\"note\\": { \\"max_title_len\\": 200, \\"max_content_len\\": 10000, \\"max_files\\": 10 },\\n \\"file\\": { \\"max_name_len\\": 255, \\"max_content_type_len\\": 100,\\n \\"min_max_file_bytes\\": 1024, \\"max_max_file_bytes\\": 26214400,\\n \\"default_max_file_bytes\\": 5242880,\\n \\"image_content_types\\": [\\"image/png\\", \\"image/jpeg\\", \\"image/webp\\", \\"image/gif\\"] },\\n \\"message\\": { \\"max_subject_len\\": 200, \\"max_body_len\\": 10000, \\"max_label_len\\": 50 },\\n \\"event\\": { \\"max_title_len\\": 200, \\"max_description_len\\": 2000 },\\n \\"course\\": { \\"kinds\\": [\\"course\\", \\"study\\", \\"club\\"], \\"max_title_len\\": 200, \\"…\\": 0 },\\n \\"exam\\": { \\"modes\\": [\\"sync\\", \\"async\\", \\"open\\"],\\n \\"question_kinds\\": [\\"choice\\", \\"text\\"],\\n \\"min_duration_ms\\": 60000, \\"max_duration_ms\\": 86400000,\\n \\"max_attempts\\": 100, \\"unlimited_attempts\\": 0,\\n \\"min_mark\\": 0, \\"max_mark\\": 100, \\"…\\": 0 },\\n \\"homework\\": { \\"statuses\\": [\\"done\\", \\"incomplete\\", \\"missing\\"],\\n \\"max_files_per_submission\\": 10, \\"max_assigned\\": 200, \\"…\\": 0 },\\n \\"question_pool\\": { \\"max_title_len\\": 200, \\"max_body_len\\": 10000, \\"max_solution_body_len\\": 10000 },\\n \\"appointment\\": { \\"max_note_len\\": 500, \\"max_reason_len\\": 1000, \\"max_slot_occurrences\\": 52 },\\n \\"chatbot\\": { \\"max_message_len\\": 8000, \\"max_thread_title_len\\": 200,\\n \\"min_max_message_len\\": 100, \\"…\\": 0 },\\n \\"board\\": { \\"max_title_len\\": 200, \\"max_participants\\": 50,\\n \\"max_stroke_payload_len\\": 4096,\\n \\"max_epoch_strokes\\": 5000, \\"max_board_strokes\\": 50000,\\n \\"max_boards_per_creator\\": 200,\\n \\"stroke_kinds\\": [\\"stroke\\", \\"clear\\"],\\n \\"ws_tick_secs\\": 15, \\"ws_max_board_id_len\\": 64 },\\n \\"settings\\": { \\"max_list_len\\": 20, \\"max_item_len\\": 50,\\n \\"min_exam_kind_weight\\": 1, \\"max_exam_kind_weight\\": 100,\\n \\"max_grade_bands\\": 20, \\"max_grade_label_len\\": 20,\\n \\"required_attendance_statuses\\": [\\"present\\", \\"absent\\", \\"late\\", \\"excused\\"] },\\n \\"request\\": { \\"max_page_limit\\": 500, \\"schedule_past_grace_ms\\": 60000,\\n \\"request_timeout_secs\\": 30 },\\n \\"rate\\": { \\"window_secs\\": 60, \\"auth_per_minute\\": 10,\\n \\"api_per_minute\\": 300, \\"chatbot_per_minute\\": 20 }\\n}\\n```\\n\\nThe `rate` group is the one part that is **not** compile-time: those tiers are\\nenvironment-tunable, so the endpoint serves *this* server's live values (read\\nfrom its running limiters), not the shipped defaults. `0` means the tier is\\noff. A client should read its budget here rather than discovering it by\\ncollecting a `429`.\\n\\n### Two surfaces, one source\\n\\nThe bounds are published twice, on purpose, because clients consume them two\\ndifferent ways:\\n\\n| Surface | Shape | Use it when |\\n|---------|-------|-------------|\\n| `GET /limits` | One JSON document, grouped by resource, closed value sets included | Runtime fetch. No codegen step, survives a deploy skew, and carries things OpenAPI holds awkwardly (`reserved_usernames`, `image_content_types`) |\\n| `/api-docs/openapi.json` | Per-field `maxLength` / `minLength` / `minimum` / `maximum` / `maxItems` on the request schemas | Build-time codegen β€” `openapi-typescript`, `orval`, and friends turn these into types *and* validators automatically |\\n\\nBoth are generated from the same `src/constant.rs`, and **neither is allowed to\\ndrift from it**, which is enforced rather than asked for:\\n\\n- `tests/limits_completeness.rs` parses every `pub const` out of `constant.rs`\\n and fails unless each one is either referenced by `src/web/limits.rs` or\\n listed as a deliberate exclusion *with a reason*. A new constant breaks the\\n suite until someone decides, consciously, whether clients need it.\\n- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 161 published\\n bounds back out of the emitted JSON, and asserts each equals its constant.\\n This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal\\n only** β€” a `const` there does not compile β€” so the annotations are\\n unavoidably a second copy of each number. The test is what makes that copy\\n safe. It also pins the `limit` query parameter's `maximum` to\\n `MAX_PAGE_LIMIT`, a duplication `constant.rs` previously only *asked* a human\\n to maintain.\\n- A third check in `limits_completeness.rs` refuses to let a validation bound\\n be declared **outside** `constant.rs` at all. Without it a limit can hide in\\n a domain module and reach neither surface β€” which is exactly where\\n `MAX_CHATBOT_THREAD_TITLE_LEN` was found sitting, private and unpublished.\\n\\nNotes:\\n\\n- **No auth.** The registration and login forms need the username and password\\n bounds before a session exists, and none of these are secrets β€” they are the\\n same rules a `400` already spells out in prose.\\n- **Answers during a database outage.** `/limits` touches no row, so it is\\n exempt from the guard that answers `503` while the database reconnects β€” a\\n frontend booting against a degraded backend is exactly when it needs the\\n contract. Every route that does read the database still refuses.\\n- **Fetch once.** The values are compile-time constants, so the response only\\n changes with a deploy. Cache it for the session; the `ETag`/`304` path makes\\n a revalidation cheap if you'd rather re-check.\\n- **`/limits` is not `/settings`.** School-adjustable policy β€” the exam kinds\\n and their weights, the attendance statuses, the grade bands, the live\\n `max_file_bytes` and chatbot knobs β€” is on `GET /settings` and changes when a\\n manager edits it. What `/limits` carries for those knobs is the fixed range a\\n manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the\\n attendance statuses no school may remove.\\n- **Open sets travel as a pattern.** `palette_color` accepts any hex accent\\n color, so `/limits` publishes `palette_color_pattern` (a regular expression)\\n and `palette_color_len` instead of a value list β€” validate the shape, not\\n membership in a palette. The pattern describes what the server *accepts*, so\\n it matches either case; the stored (and returned) value is lowercased, which\\n is the one place a response may differ in case from the request.\\n- **Closed value sets ride along.** `roles`, `themes`, `languages`, course\\n `kinds`, exam `modes`, `question_kinds`, homework `statuses`, board\\n `stroke_kinds`, and the\\n uploadable `image_content_types` are the exact accepted spellings β€” build\\n pickers from these rather than from a literal list.", "source": "README.md"}, {"id": "rate-limiting", "title": "Rate limiting", "body": "Requests are limited per client IP over a fixed 60-second window, in two tiers:\\n`/auth/login` + `/auth/register` get a strict budget\\n(`RATE_LIMIT_AUTH_PER_MINUTE`, default 10) against credential brute-force,\\nand every route β€” Swagger included β€” shares a generous catch-all\\n(`RATE_LIMIT_API_PER_MINUTE`, default 300). Exceeding either answers `429` with\\na `Retry-After` header (seconds). Set a limit to `0` to disable that tier β€”\\nuseful for load tests.\\n\\nSending a chatbot message adds a third tier, and it is keyed by **user id**,\\nnot by IP (`RATE_LIMIT_CHATBOT_PER_MINUTE`, default 20), because an inference\\ncosts the school real money and a shared-IP classroom must not spend one\\nstudent's budget on another's. `0` disables it like the other two. It is\\ncharged before anything is written, so a `429` leaves no trace (see\\n\\"Chatbot\\").\\n\\nAll three tiers admit from memory β€” no request ever waits on the database to be\\nlet in β€” but the window **outlives the process**. A background task folds each\\ntier's new admits into one shared `rate_limit` row per tier + client + minute\\nevery 2 seconds, then caps the in-memory bucket by the total that comes back,\\nso a restart mid-minute does not hand every client a fresh budget. One caveat:\\na just-started process can spend up to the tier's budget in the 2 seconds\\nbefore its first fold tightens it. If the database is down the tiers simply\\nfall back to their own local budgets β€” nobody is refused for it.\\n\\nBehind a reverse proxy every connection carries the proxy's address, so also\\nset `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry\\n(the one the proxy itself appends). Leave it off when clients reach the server\\ndirectly β€” the header is client-forged in that case.", "source": "README.md"}, {"id": "cors", "title": "CORS", "body": "Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin`\\n(browsers refuse it on credentialed requests), so origins listed in the\\ncomma-separated `CORS_ALLOWED_ORIGINS` allowlist are echoed back with\\n`Access-Control-Allow-Credentials: true`. When the allowlist is unset the\\nserver reflects the request's `Origin` β€” dev-friendly β€” but **without**\\ncredentials: mirroring with credentials would let any website ride a\\nvisitor's session cookie. A browser frontend that needs the session cookie\\ncross-origin must therefore be allowlisted explicitly.", "source": "README.md"}, {"id": "roles-access-control", "title": "Roles & access control", "body": "Every user has one of five roles, ranked lowest to highest:\\n\\n```\\nparent < student < teacher < manager < admin\\n```\\n\\nThe check is **hierarchical** β€” a higher role satisfies any lower requirement\\n(an admin can do anything a teacher can). New accounts always register as\\n`student`; a role read is re-checked on every request, so a role change takes\\neffect on the user's very next call (no re-login).\\n\\n`parent` is the read-only observer at the bottom of the ladder: an admin ties\\nany number of students to a parent account (`POST /users/{id}/students`), and\\nthe tie is the parent's whole power β€” they list their students\\n(`GET /users/me/students`) and read each one's mark, attendance, pomodoro,\\nand homework reports in full. Student-only checks are exact (`role == student`), so a\\nparent can never enroll, sit an exam, be graded, or land on a roll call; and\\nsitting below every staff bar, they can't touch anything else either β€” except\\nmessages, which any role sends and receives (that's how a parent reaches a\\nteacher). A role\\nchange off either end of a tie (the parent stops being a `parent`, the\\nstudent stops being a `student`) drops the tie, exactly like promotion drops\\ncourse enrollments.\\n\\n| Action | Minimum role | Notes |\\n|------------------------------------------|--------------|-----------------------------------------------|\\n| Register / login / view own account | (any) | Registration always creates a `student` |\\n| View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves |\\n| Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included β€” the role's one write); each party only ever touches their own copy |\\n| Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark β€” a teacher+ may mark anyone expected, themselves included |\\n| Create events | teacher | The audience (school / role / course / registration) is set at creation and editable later |\\n| Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** β€” never for another staff member. Unregistering mirrors the same rule |\\n| List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report |\\n| Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |\\n| View a course's sessions | student | Only inside **visible** courses: enrolled, creator, assigned teacher, or `manager`+ |\\n| List a session's roll call | teacher | The **session's teacher**, or anyone with course-management rights |\\n| Create / edit / delete a course session | teacher | Course-management rights (course creator, an assigned teacher, or `manager`+) |\\n| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights; only students sit on a roster |\\n| Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call β€” the teacher can't self-mark |\\n| Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied |\\n| View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries |\\n| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session |\\n| View **any** user's pomodoro log | teacher | Study oversight β€” same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' |\\n| Ask into the school question pool | student | **Students only** (exact); born `pending` β€” visible to the asker + teacher+ only; the asker may attach/replace/remove one photo while pending |\\n| Read the pool; offer / edit / withdraw own solutions | student | Every `approved` question is school-wide (parents stay out); a solution's author edits its body and photo anytime (solutions never freeze) and deletes it, teacher+ delete any |\\n| Approve a pending pool question; delete any question or solution | teacher | Approval publishes school-wide and **freezes** the content; rejection = deletion β€” moderation never edits, so teacher+ cannot rewrite a solution |\\n| Read the school **question bank**; save / instantiate bank questions | teacher | Every bank row is school-wide (reads + copy into an exam); saving one makes the caller its owner |\\n| Edit / delete a bank question (and its images) | teacher | **Owner only** (admin bypass); bank rows carry no exam link, so they never freeze |\\n| Read **own** attendance report | student | |\\n| Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created + assigned; `manager`+: all); exam **drafts** show only to the course's managers |\\n| Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** β€” staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |\\n| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |\\n| Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |\\n| Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights β€” one teacher can't read another's answer key |\\n| Watch an exam's live monitor (poll the snapshot) | teacher | Course-management rights |\\n| Create courses | teacher | The creator manages the course, and owns it for good |\\n| Assign / unassign a course's teachers | manager | Staffing is the office's call β€” a course's own creator cannot hand rights to peers; the assignee must be `teacher`+ |\\n| Delete a course | teacher | Only the **creator**, or a `manager`+ β€” an assigned teacher runs the course but doesn't own it |\\n| Manage inside a course: edit it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | The **course creator**, a teacher **assigned** to it, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions or homework won't delete (`409`) |\\n| View a course's roster, an exam's result list / statistics | teacher | Course-management rights |\\n| Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself |\\n| Assign / edit / delete homework; grade it; read its roster | teacher | Course-management rights; an `assigned` subset (≀ 200 enrolled students) can't be narrowed over existing work (`409`); a grade (`done`/`incomplete`/`missing` + optional mark) freezes the submission until removed |\\n| Submit **own** homework (text + files); read own submission and grade | student | **Students only** β€” staff never submit; enrolled + in the audience; editable until graded; ≀ 10 files of any type, each ≀ `max_file_bytes`, always downloaded as attachments |\\n| Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full β€” statuses/marks/flags, never files |\\n| Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields |\\n| Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen β€” the client then follows the device preference |\\n| List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports β€” a parent changes nothing, anywhere |\\n| Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |\\n| Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call |\\n| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role |\\n\\n### Bootstrapping the first admin\\n\\nThere is no self-service path to `admin` β€” registration always creates a\\n`student`. The first admin comes from the startup seed: set both\\n\\n```sh\\nADMIN_USERNAME=admin\\nADMIN_PASSWORD=admin123 # local-dev default used by compose.yaml; change it\\n```\\n\\nand on boot the account is created with the `admin` role **if the username\\ndoesn't exist yet**. The seed is idempotent and deliberately conservative: it\\nnever promotes or rewrites an existing account (if the name is taken by a\\nnon-admin it logs a warning and leaves it alone β€” promoting someone else's\\naccount would be an escalation). Setting only one of the two variables aborts\\nstartup. `compose.yaml` ships with the credentials above for local dev.\\n\\nThat admin can then promote everyone else through `PATCH /users/{id}/role`.\\n\\nManual fallback (also the recovery path if the seeded name was squatted or the\\nsole admin locked themselves out): run\\n\\n```surql\\nUPDATE user SET role = 'admin' WHERE username = 'ada';\\n```\\n\\nagainst the SurrealDB server β€” e.g.\\n`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db hezarfen`\\n(in the container setup, `podman exec -it hezarfen-surrealdb /surreal sql ...`).", "source": "README.md"}, {"id": "endpoints", "title": "Endpoints", "body": "`Auth` is the minimum role; `no` means no session required, `student` means any\\nlogged-in user.\\n\\nA course is a regular class (kind `course`, the default), an *etΓΌt* (kind\\n`study` β€” a supervised study session), or a *kulΓΌp* (kind `club` β€” a student\\nclub). The three kinds behave identically everywhere β€” enrollment, exams,\\nsessions, marks β€” the kind is a label the UI renders differently, settable at\\ncreation and editable later. A course may also carry a `capacity`: once the\\nroster reaches it, new enrolls are refused with `409` (members already on the\\nroster are unaffected, even if the cap is later lowered below them; `null`\\nlifts the cap).\\n\\n**Who runs a course.** Its **creator** owns it for good β€” only they (or a\\nmanager+) may delete it. On top of that, a manager can **assign** any\\n`teacher`+ to the course with `POST /courses/{id}/teachers` (`{user_id}`,\\nidempotent) and drop them again with `DELETE /courses/{id}/teachers/{user}`.\\nAn assigned teacher gets full **course-management rights** β€” edit the course,\\nenroll and unenroll students, add exams, sessions and subjects, grade, take\\nroll call β€” but *not* the two owner powers: they cannot delete the course, and\\nthey cannot change who else teaches it. Staffing is deliberately the office's\\ncall, so a course's own creator cannot hand rights to their peers; only\\nmanager+ may touch the list. Every course response carries its `teachers`\\narray alongside `creator`, and a user demoted below `teacher` is swept off\\nevery course they were assigned to (the mirror of promotion dropping\\nenrollments).\\n\\nCourse data is walled per course. A course, its exams, its sessions, and its\\nsubjects are\\n**visible** only to its enrolled users, its creator, its assigned teachers,\\nand manager+ β€” a student\\nsees just the classes they were added to, and the `/courses` / `/exams`\\ncatalogs are filtered accordingly. Teacher-level reads *inside* a course\\n(roster, results, statistics, the question list, answer sheets, the live\\nmonitor) additionally need **course-management rights** (creator, an assigned\\nteacher, or manager+):\\none teacher cannot look into another teacher's course, and the per-user\\nmarks/attendance reports narrow to the courses the caller manages.\\n\\n**Paging.** Every list endpoint below (the rows tagged **Β· paged**) accepts\\n`?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope\\nrather than a bare array. `total` is the full row count *before* the window, so\\na frontend can show \\"100 of 256\\" and page with `offset`. Paging is **opt-in**:\\nomit `limit` and you get every remaining row (the echoed `limit` is then\\n`null`), so a caller that sends no parameters still receives the whole list β€”\\nnothing silently truncates. `limit` must be `1`–`500`, `offset` defaults to `0`\\nand must be β‰₯ 0 (bad values are `400`), and an `offset` at or past the end\\nreturns an empty `items` (not an error). Deliberately **not** paged β€” these keep\\ntheir existing shapes: the student exam-room reads\\n`/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and\\n`/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`.\\n\\n**Schedule window (`GET /events`, `GET /exams`).** Both lists additionally\\naccept `?starts_after=` and `?ends_after=`, UTC unix-millis, both optional and\\nindependent (AND-ed when both are sent). `ends_after=T` keeps rows whose window\\nhas not finished β€” `ends_at > T`, falling back to `starts_at > T` when `ends_at`\\nis `null`; `starts_after=T` keeps rows with `starts_at > T`. A row with no\\nschedule at all (an event without times, an exam with no `mode` or in `open`\\nmode) is excluded by either parameter. Supplying either one flips the order to\\n**ascending by schedule** (`starts_at`, falling back to `ends_at`; ties by id),\\nso `?ends_after=<now>&limit=20` gives the twenty *soonest* rows instead of the\\ntwenty newest-created β€” with neither parameter the list is byte-for-byte the\\nnewest-first list it always was. `total` is the count after visibility *and*\\nwindow filtering, before paging; negative values are a `400` naming the field.\\n\\n| Method | Path | Auth | Description |\\n|--------|----------------------------------|---------|---------------------------------|\\n| GET | `/health` | no | Liveness check |\\n| GET | `/` | no | Same as `/health` |\\n| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |\\n| GET | `/limits` | no | Every fixed validation bound, grouped by resource β€” see Validation limits |\\n| GET | `/swagger` | no | Interactive API docs (Swagger UI) |\\n| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |\\n| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |\\n| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken β€” see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |\\n| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` β€” own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) Β· paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` β€” find users by username/name fragment (pickers); refs only, no contact info Β· paged |\\n| GET | `/users` | admin | List all users Β· paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` β€” set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` β€” tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students Β· paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |\\n| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes Β· paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) β€” ≀ the school's `max_file_bytes`, ≀ 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) Β· paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |\\n| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` β€” send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` β€” the caller's folder, newest first; `?folder=inbox&read=false&limit=1` β†’ `total` is the unread badge Β· paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` β€” read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** β€” only from the trash (`409` elsewhere); the row vanishes once both sides deleted |\\n| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` β€” `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` β€” mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) Β· paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` Β· paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` β€” seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |\\n| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` β€” publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, ≀ 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) β€” a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar β€” future slots only, demoted teachers' slots left out Β· paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` β€” book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests Β· paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` β€” call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included β€” they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` β€” counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal β€” this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |\\n| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` β€” `kind` is `course` (default), `study` (etΓΌt), or `club` (kulΓΌp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) Β· paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses Β· paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ β€” **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` β€” assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` β€” enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) Β· paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β€” add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β€” add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |\\n| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` β€” roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) Β· paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` β€” add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) Β· paged |\\n| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist β€” the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` β€” grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) Β· paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt β€” students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) Β· paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question β€” the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam β€” copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** β€” copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question β€” text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` β€” autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers ⋃ marks), ascending β€” the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first β€” the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** β€” the answer key the caller checks their own sheet against (same review gate) Β· paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers ⋃ marks), ascending β€” only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster Γ— latest attempts Γ— marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |\\n| GET | `/bank-questions` | teacher | The school-wide question bank β€” `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) Β· paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist β€” `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question β€” the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` β€” assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≀ 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) Β· paged |\\n| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) Β· paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade β€” the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades β€” file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` β€” hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part β€” **any** content type, ≀ `max_file_bytes`, ≀ 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) β€” the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student Γ— submission/files/grade + computed `late`/`missing`/`unenrolled` β€” a straggler's stale work stays visible (course manager) Β· paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` β€” grade `done`/`incomplete`/`missing` (+ optional 0–100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable β€” that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) β€” readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade β€” un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows β€” submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` β€” full, statuses and marks only, never files Β· paged |\\n| POST | `/questions` | student | `{title, body}` β€” ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` β€” the pool questions visible to the caller, each with its `solution_count` Β· paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question β€” publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` β€” offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first β€” a discussion thread Β· paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` β€” edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |\\n| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) Β· paged |\\n| GET | `/work/{user}` | manager | A staff member's work log Β· paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` β€” correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |\\n| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** β€” a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` Β· paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape Β· paged; *or a `parent` linked to `{user}` |\\n| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |\\n| POST | `/terms` | manager | `{name, starts_at, ends_at}` β€” past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first Β· paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course still links to it |\\n| POST | `/meals/menus` | manager | `{date, slot, capacity?}` β€” publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first Β· `?from=&to=` inclusive `YYYY-MM-DD` range Β· paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` β€” the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` β€” add a dish (≀ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` β€” record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` β€” take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first Β· paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included Β· paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent β€” cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` β€” mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu Β· paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history Β· `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day Β· paged Β· own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` β€” record money received; **admin only**, appends a `credit` line |\\n| POST | `/payments/plans` | manager | `{name, installments}` β€” write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it β€” its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (≀ 200) β€” place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first Β· paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` β€” record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` β€” hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` β€” undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines β€” charges, payments, refunds, reversals β€” newest first Β· paged Β· own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |\\n| POST | `/chatbot/threads` | student | `{title?}` β€” start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first Β· paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` β€” rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first β€” user and assistant rows alike Β· paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≀ `max_chatbot_message_len`) β€” send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` β€” nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β€” or one `error` β€” and close; an already-finished answer replays (see \\"Chatbot\\") |\\n| POST | `/boards` | student | `{title, participant_ids?}` β€” open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first Β· paged |\\n| GET | `/boards/{id}` | student | One board β€” a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |\\n\\n`status` must be one of the school's attendance statuses (`GET /settings`);\\nthe core four `present | absent | late | excused` always exist, plus whatever\\nthe school added.\\n`kind` must be one of the school's exam kinds (`GET /settings`; defaults:\\n`homework | quiz | midterm | final | project | oral`). The kind carries the\\nexam's weight in the course average β€” an integer `1`–`100` set per **kind** in\\nsettings (defaults all `1`), resolved when a report is read; an exam whose\\nkind was later removed from settings counts with weight `1`.\\nA course may carry a `term_id` (`null` = unassigned); on `PATCH\\n/courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`\\nclears it.\\n`role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are\\nULIDs. `parent` accounts are made by an admin (register as `student`, then\\n`PATCH /users/{id}/role`) and observe only the students an admin tied to them\\nβ€” see \\"Roles & access control\\".\\nAn exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row,\\nnever in a `note`. Students never grade anyone β€” grading is teacher+ with\\ncourse-management rights, and the target must be enrolled in the exam's course;\\na student reads just their own mark via `GET /exams/{id}/result`.\\nA course average is `Ξ£(markΓ—weight) / Ξ£(weight)` over the student's **graded**\\nexams in that course (`null` while nothing is graded β€” ungraded exams are\\nskipped, not zeroed). The overall average is the plain mean of the non-null\\ncourse averages. Unenrolling keeps result rows: the marks drop out of the\\nreport until re-enrollment, but stay visible on the exam itself. A course\\nwith anyone still on its roster refuses deletion (`409`) β€” empty the roster\\nfirst; once empty, deleting it cascades its exams, their results, its\\nsessions and roll call, and its subjects.\\nA **subject** is one topic of a course's curriculum (`name` ≀ 200 chars,\\noptional `description` ≀ 2000): every exam question carries a mandatory\\n`subject_id` naming one of *its own course's* subjects (an unknown or\\nforeign-course subject is a `400`), so exam content is always attributable to\\na topic. A subject's course link is fixed at creation, and a subject still\\nreferenced by questions refuses deletion with a `409` β€” re-tag (PATCH the\\nquestions' `subject_id`) or delete those questions first. Questions written\\nbefore subjects existed are **destroyed on boot** (answers first) β€” the clean\\nbreak instead of inventing a placeholder topic.\\nEvent `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both\\nare given, `ends_at` must not precede `starts_at`, and neither may be set in\\nthe past (else `400`). On `PATCH`, an omitted time keeps its value and an\\nexplicit `null` clears it.\\nAn event's `audience` is a tagged object β€” `{\\"kind\\": \\"school\\"}` (the default),\\n`{\\"kind\\": \\"role\\", \\"role\\": \\"student\\"}` (that exact role, no \\"and above\\"),\\n`{\\"kind\\": \\"course\\", \\"course\\": \\"<id>\\"}` (the course's current enrollment), or\\n`{\\"kind\\": \\"registration\\", \\"capacity\\": 30}` (a signup list; `capacity` optional,\\n`null` = unlimited) β€” and is the event's **expected-attendee roster**, resolved\\nlive at read time: role changes, (un)enrollments, and (un)registrations move\\npeople in and out by themselves. It never hides the event β€” everyone sees every\\nevent. Only audience members can be marked; `GET /events/{id}/roster` joins the\\nlive roster with the recorded marks (`status: null` = expected but never\\nmarked). Attendance rows for people a later audience edit (or unenrollment /\\nrole change) dropped stay stored and listed under `/events/{id}/attendance`,\\nbut leave the roster report.\\nA registration list fills through `POST /events/{id}/register`: teachers place\\nstudents (a student never registers, not even themselves) and take seats only\\nfor themselves β€” registering another staff member is refused. Re-registering\\nsomeone is a no-op, a full list is a `409`, and the list freezes the moment\\nthe event starts β€” or, when only `ends_at` is set (a pure signup deadline),\\nthe moment it passes (register and unregister both). Signup rows survive an\\naudience switch inertly and resurface if the event returns to the registration\\nkind; deleting the event deletes them. Pre-existing hand-picked (`users`)\\naudiences convert on boot: each listed user becomes a signup row credited to\\nthe event's creator, and the audience becomes an uncapped registration list.\\nReading a child collection of a missing parent (`/events/{id}/attendance`,\\n`/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`,\\n`/courses/{id}/sessions`, `/courses/{id}/subjects`, `/courses/{id}/homework`,\\n`/homework/{id}/submissions`, `/sessions/{id}/attendance`) is a `404`, not an\\nempty list.\\nPersonal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same\\noptional set on every account, whatever the role, and is `null` until filled\\nin. On `PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) each field\\nis independent: omitted (or `null`) keeps the current value, an empty string\\n`\\"\\"` clears it, anything else is validated β€” email must look like\\n`name@example.com`, phone is 7–15 digits with an optional `+` and cosmetic\\nseparators, `birth_date` is a real `YYYY-MM-DD` calendar date not in the\\nfuture. Names allow unicode; usernames are strict: lowercase letters and\\ndigits plus non-consecutive interior `.`, `_`, `-` separators, starting and\\nending with a letter or digit (3–32 chars). Staff-looking names (`admin`,\\n`administrator`, `root`, `support`, `system`, `moderator`, `staff`) are\\nrejected at `/auth/register` only β€” the `ADMIN_USERNAME` bootstrap may still\\nseed them.\\nUI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`,\\n`palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the\\nsame account row and come back on every user response (`/auth/me` included).\\n`PATCH /users/me/preferences` (or the admin `PATCH /users/{id}/preferences`)\\nuses the same field semantics as the profile patch: omitted keeps, `\\"\\"` clears\\nback to `null` (\\"never chose\\" β€” the client then follows the device\\npreference, or its own default accent), anything else must be valid or the\\nwhole patch is a `400`. `palette_color` is the one **open** set: any valid hex\\npasses (mixed case in, stored and returned lowercase), so a new frontend\\npalette needs no backend change β€” `/limits` publishes its pattern rather than a\\nlist of colors.", "source": "README.md"}, {"id": "appointments", "title": "Appointments", "body": "Office hours and parent-teacher conferences, booked instead of arranged by\\nmessage. A teacher+ **publishes availability**; a student or a parent\\n**books** one of those windows with a reason; the teacher **decides**. Two\\nrows carry it: an `appointment_slot` (the offer) and an `appointment` (the\\nbooking sitting on it) β€” a slot is never \\"half booked\\", and a refused request\\nstays readable instead of vanishing.\\n\\nA slot is a window on one teacher's calendar: `starts_at`/`ends_at` (unix\\nmilliseconds, `starts_at` strictly before `ends_at`, neither in the past β€” the\\nusual 60-second grace) plus an optional `note` (≀ 500 chars) shown to\\nrequesters (\\"office hours\\", \\"veli gΓΆrüşmesi\\"). Windows are **half-open**, so\\n10:00–10:30 and 10:30–11:00 are two slots, not a collision. A window that *does*\\noverlap one the same teacher has already published is refused with a `409` β€” the\\nguard is **per-teacher** (two teachers may hold office hours at the same hour)\\nand boundary-touching windows are legal by that same half-open rule, which is\\nhow an hour gets carved into back-to-back slots. `POST\\n/appointments/slots` publishes on the caller's *own* calendar (managers and\\nadmins included β€” the calendar always belongs to whoever posted) and **always\\nanswers an array**: one element for a one-off, one per occurrence for a\\nrecurring publish.\\n\\n`repeat_weekly: true` with an `until` expands the same window every seven days\\nup to and including `until`, server-side, into **concrete rows** sharing a\\n`series` id β€” no recurrence rule is stored, so one week can be cancelled\\nwithout touching the rest. At most 52 occurrences (a year); asking for more is\\na `400`, as is `repeat_weekly` without `until` β€” and so is a window sitting so\\nfar ahead that shifting it by a week would run off the end of representable\\ntime (the shift is checked, never wrapped: a wrapped end would land *before*\\nits start, and an inverted window can never overlap anything, which would\\nquietly disable the double-booking guard). A recurring publish is\\n**all-or-nothing**: every occurrence is checked β€” against the slots already\\nstored *and* against the earlier occurrences of the same batch, which a window\\nlonger than a week overlaps itself β€” before a single row is written, so a\\nmid-series collision answers `409` and leaves no stray weeks behind. Delete one\\noccurrence with\\n`DELETE /appointments/slots/{id}`, the whole publish with `DELETE\\n/appointments/slots/series/{series}`.\\n\\n```json\\nPOST /appointments/slots\\n{ \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"repeat_weekly\\": true, \\"until\\": 1901209600000 }\\n\\n201 [ { \\"id\\": \\"01J8…A\\", \\"teacher\\": {\\"id\\": \\"01J8…T\\", \\"username\\": \\"ayse\\",\\n \\"display_name\\": \\"Ayşe YΔ±lmaz\\"},\\n \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"series\\": \\"01J8…S\\", \\"created_at\\": 1899… },\\n { \\"id\\": \\"01J8…B\\", …, \\"starts_at\\": 1900604800000, \\"series\\": \\"01J8…S\\" } ]\\n```\\n\\n`GET /appointments/slots` is two lists behind one path: a teacher+ reads\\n**their own** calendar, past occurrences included; everyone else reads the\\n**bookable** calendar β€” future slots only, earliest first. A teacher demoted\\nafter publishing leaves **inert** slots: their live role is re-read, so those\\nslots drop out of the bookable list and booking one is refused with a `409`.\\nThe list does not say whether a slot is already taken β€” booking a taken one\\nanswers `409`.\\n\\n**Booking.** `POST /appointments` (`{slot, reason}` β€” the reason is required,\\n≀ 1000 chars) is for **students and parents only**; staff arrange between\\nthemselves off this API. A parent books for *themselves* β€” this is the\\nparent-teacher conference, not a booking on behalf of a child. The request\\nlands `pending`, always: publishing availability is not consent to a\\nparticular person and a particular topic, so approve/reject still applies.\\n\\nA booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two\\nare **live** and hold the slot; rejecting or cancelling frees it for someone\\nelse immediately (the slot carries an `occupied` counter, taken by a booking\\nand handed back in the same transaction as the reject or cancel that settles\\nit, so the seat is decided by the database rather than by a count two\\nconcurrent bookings can both read as free). The decisions:\\n\\n- `PATCH /{id}/approve` β€” the slot's teacher (or manager+) confirms. Refused\\n (`409`) when the effective window has already started.\\n- `PATCH /{id}/reject` β€” turns it down; the slot frees up.\\n- `PATCH /{id}/cancel` β€” **the requester only**, from either live state.\\n Anyone else is a `403`, the slot's teacher and a manager/admin included (the\\n guard compares ids, not roles). A teacher ends a booking by **rejecting** it\\n while it is `pending`, and an approved one by counter-proposing another time\\n (`/reschedule`, which sends it back to `pending`) and then rejecting it β€” or\\n simply by rescheduling to a time that works. Refused (`409`) once the\\n meeting's window has started: a\\n meeting that already began is history, not a plan. The guard sits in the\\n domain's `cancel` itself, on a fresh read compared-and-set into the row, so\\n every way of cancelling β€” the decline below included β€” inherits it.\\n- `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) β€” the teacher\\n **counter-proposes**. The times land on the *same* row as\\n `proposed_starts_at`/`proposed_ends_at`, the status goes back to `pending`\\n and `decided_by` clears, because leaving it `approved` would silently move a\\n confirmed appointment. The slot stays held meanwhile. A window that has\\n already opened is refused (`409`): the 60-second grace on the times is for\\n clock skew, not for proposing into a meeting already underway β€” one nobody\\n could then cancel.\\n- `PATCH /{id}/reschedule/accept` β€” the **requester** only: this *is* approval\\n at the new time, so the overlap guard runs again β€” and so does the\\n already-started guard (`409`). Agreeing to a window that has begun does not\\n help: the meeting could never be cancelled. The booking stays `pending`, so\\n the teacher just proposes a time that can still happen.\\n- `PATCH /{id}/reschedule/decline` β€” the requester only, and it **cancels the\\n booking**: the proposal replaced the time that was asked for, so there is\\n nothing to fall back to. The row stays readable as `cancelled` with the\\n refused proposal still on it β€” book another slot instead. Declining *is* a\\n cancel, so it answers to the cancel deadline too (`409` once the effective\\n window has started).\\n\\n**Who settled it, and why.** Every settled booking carries its own audit trail\\non the row: `decided_by` (who approved or rejected β€” cleared again by a\\ncounter-proposal), `cancelled_by` (who called it off, stamped by `cancel` and by\\na declined counter-proposal), plus the optional free text that came with the\\ndecision β€” `reject_reason` on `PATCH /{id}/reject` and `cancel_reason` on\\n`PATCH /{id}/cancel` and `/reschedule/decline`. Both reasons are optional: the\\nwhole body may be omitted, a blank one records nothing (`null`), and a present\\none is validated like the booking's own reason (≀ 1000 chars, `400` past that)\\nbefore it reaches the row. They are **not public**: bookings are only ever\\nrendered to the person who requested them and to the slot's teacher (a\\nmanager/admin acting on one by id sees the response to their own call), so\\n\\"couldn't make it, sorry\\" goes no further than the two people it concerns. Rows\\nwritten before these fields existed simply read back `null`.\\n\\nA booking's effective window is the accepted counter-proposal when there is\\none and the slot's own window otherwise; that is what `starts_at`/`ends_at` on\\nan `AppointmentResponse` report, and what the cancel deadline is judged on.\\n\\n**No double-booking.** Two `approved` meetings may never overlap for the same\\nteacher *or* the same requester (`409`). The guard runs at approval β€” the\\nmoment anyone is actually committed β€” and again on accepting a counter-proposal,\\nbecause the time moved. Approval also refuses (`409`) an **effective window\\nthat has already started** (the proposal's when one stands, the slot's\\notherwise), for the same reason booking one is refused. Requesting is checked more loosely: a booking is\\nrefused up front only when the slot's window has already started (booking it\\nwould create a meeting `cancel` refuses to undo β€” the 60-second publish grace\\nis for clock skew, not for booking into the past), when the slot is already\\ntaken, or when the *requester* is already committed at that hour; a clash on the teacher's side is theirs to\\nresolve when they decide, since refusing a request against a window they\\nthemselves published would only confuse. Touching windows never conflict.\\n\\nDeletion follows the same rule as the rest of the codebase: a slot carrying a\\nlive (pending or approved) booking refuses to go (`409`) β€” reject or cancel\\nthat booking first β€” and a series delete is all-or-nothing, `409` if *any*\\noccurrence still carries one, so the person waiting is dealt with rather than\\nleft stranded on a stray week. Settled (rejected/cancelled) bookings cascade\\naway with their slot.\\n\\n`GET /appointments` is likewise two lists: a teacher+ sees the bookings aimed\\nat their own slots (their request inbox), everyone else the ones they\\nrequested, newest first, paged. Managers and admins read their own inbox here\\ntoo β€” they may still decide any booking by id.", "source": "README.md"}, {"id": "messaging", "title": "Messaging", "body": "One-to-one, mail-style (subject + body + an optional free-text `label` the UI\\nrenders as a badge β€” \\"EtΓΌt\\", \\"SΔ±nav\\"; no threads): any user writes to any\\nuser β€” student to teacher, parent to teacher, teacher to student; only\\nmessaging yourself is refused. A single stored message serves both parties,\\nbut each **owns their copy independently**: the recipient's moves through\\n`inbox` β†’ `archive`/`trash` and carries the `read` flag (the sender sees it\\nas a read receipt); the sender's moves through `sent` β†’ `archive`/`trash`. Filing or\\ndeleting your copy never changes the other side's view.\\n\\nEvery copy remembers where it was filed from, so it can go back there. Moving\\ninto `archive`/`trash` stamps the folder you left onto the copy's\\n`previous_folder`, and restoring is a `PATCH` of `folder` back to that value:\\nan inbox message you archive and then trash returns to `archive`, and from\\nthere to `inbox`. Two folders are never stamped β€” the trash itself (pulling a\\ncopy out of the trash must not leave it pointing back at the discard pile) and\\nthe folder you are already in β€” and moving back to `inbox`/`sent` clears the\\nstamp. `previous_folder` is therefore `null` for any copy sitting in its home\\nfolder, and for copies filed before the field existed; both mean \\"restore to\\n`inbox`\\" (`sent` for the sender's copy).\\n\\nListing is per folder β€” `GET /messages?folder=` with `inbox` (default),\\n`sent`, `archive`, or `trash` (trash shows both received and sent copies you\\ntrashed) β€” newest first, paged, with sender/recipient rendered as person refs\\nplus their role. `?read=false` narrows to unread (`true` to read), and since\\n`total` counts the filtered view, `?folder=inbox&read=false&limit=1` is the\\none-row unread-badge query. `PATCH /messages/{id}` flips `read` (recipient only) or\\nmoves your copy (`folder`), restoring included. `DELETE` is\\npermanent, allowed only while your copy sits in the trash (`409` otherwise),\\nand physically removes the row once both sides have deleted theirs. Replying\\nis just sending a new message back β€” the frontend prefixes the subject if it\\nwants an `Re:`.", "source": "README.md"}, {"id": "question-pool", "title": "Question pool", "body": "Students get stuck; the pool is where the school unsticks them β€” with a\\nmoderation gate so nothing unreviewed goes school-wide. `POST /questions`\\n(students only, exact role) creates the question `pending`: only the asker\\nand teacher+ can see it (anyone else gets a `404`, not a `403` β€” a pending\\nquestion's existence is nobody else's business), and `GET\\n/questions?status=pending` is a teacher's approval queue. The asker may\\nattach **one photo** of the problem (`POST /questions/{id}/image`,\\n`multipart/form-data` with a `file` part β€” raster types only, no SVG, ≀ the\\nschool's `max_file_bytes`), replace it, or remove it β€” while pending only.\\n\\n`POST /questions/{id}/approve` (teacher+) publishes it: the question becomes\\nreadable by every signed-in user above `parent`, and its content β€” title,\\nbody, photo β€” **freezes**, because an edit after approval would bypass the\\nmoderation that just happened. There is no rejected state and no edit\\nendpoint: to fix a typo the asker deletes and re-asks; to reject, a teacher+\\ndeletes. Approving twice is a `409`; the response records `approved_by`.\\n\\nAnyone in the school (student through admin β€” not parents) may then offer a\\n**solution**: `POST /questions/{id}/solutions` with a text body, listed\\noldest-first like a discussion thread (`GET`, paged). Solutions are the\\nunmoderated half of the pool, so nothing about them ever freezes: the author\\nβ€” and only the author, teacher+ included out β€” may edit the body (`PATCH\\n/questions/{id}/solutions/{sid}`) and attach one **photo** of the worked\\nsteps (`POST /questions/{id}/solutions/{sid}/image`, same raster-only rules\\nand `max_file_bytes` cap as the question's photo), replace it, or remove it,\\nat any time; moderation stays delete-only β€” a teacher+ removes a bad\\nsolution, never rewrites someone else's words. A solution is deleted by its\\nauthor or by teacher+, its photo blob going with it; deleting a question β€”\\nasker withdrawing, or teacher+ moderating β€” takes its solutions and every\\nphoto blob (its own and its solutions') with it. Each question row reports\\nits `solution_count`, and questions and solutions embed their people as\\nperson refs (`{id, username, display_name}`), so the UI never shows a raw\\nULID.", "source": "README.md"}, {"id": "per-school-policy-settings-terms", "title": "Per-school policy (settings & terms)", "body": "Every school runs differently; the parts that vary are data, not code. One\\neditable `settings` singleton (`GET /settings` for any signed-in user,\\n`PATCH /settings` for manager+) carries seven knobs:\\n\\n- **`exam_kinds`** β€” the accepted `kind` values for new exams, each an\\n object `{name, weight}`. The weight (`1`–`100`) is how many times an exam\\n of that kind counts into its course average β€” weighting is school policy,\\n set once per kind, never per exam. Defaults to `homework, quiz, midterm,\\n final, project, oral`, all weighing `1` (a plain average); replace the\\n list with whatever the school grades and weighs (`{\\"name\\": \\"final\\",\\n \\"weight\\": 3}`, …). Reports resolve weights live: editing a weight\\n re-weights every exam of that kind at once. For the same reason a kind\\n whose exams already carry marks cannot be removed from the list (`409`):\\n those marks would silently re-weight. An unmarked kind leaves freely, and\\n an exam keeping a since-removed kind counts with weight `1` β€” but it can no\\n longer be graded (`409`) until the school offers that kind again, which is\\n what keeps \\"a marked kind cannot be removed\\" true from both ends. The same\\n rule pointed at one exam: an exam that already carries marks keeps its\\n `kind` (`PATCH /exams/{id}` answers `409`), because re-pointing it would\\n re-weight those marks just as silently.\\n- **`attendance_statuses`** β€” what attendance marking accepts. The core four\\n (`present`, `absent`, `late`, `excused`) are mandatory because the\\n attendance rate is defined over them (`(present+late) /\\n (present+absent+late)`); school extras (say `online`) are **rate-neutral**\\n and tally under `custom` in the attendance reports.\\n- **`grade_bands`** β€” how numeric marks display: a list of `{min, label}`\\n bands (`85 β†’ \\"AA\\"`, `50 β†’ \\"CC\\"`, …). One band must start at `0` so every\\n mark maps; an empty list (the default) means numeric-only. Storage and\\n averaging stay `0`–`100` forever β€” bands only add `grade`,\\n `average_grade`, and `overall_grade` labels to the mark report, so a school\\n can switch display scales without touching a single stored mark.\\n- **`max_file_bytes`** β€” the per-file size cap for uploads (note files and\\n exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;\\n a server hard cap β€” uploads buffer in memory), default `5242880` (5 MiB).\\n Checked at upload time only: lowering it never touches already-stored files.\\n- **`chatbot_history_turns`** β€” how many prior **messages** of a thread the\\n chatbot is given as context, `1`–`50` (default `10`). The unit is messages,\\n not exchanges: a question and its answer are two, so the default remembers\\n five question/answer pairs. Every one of them is re-sent on every reply, so\\n the number is both what the bot remembers and what each answer costs.\\n- **`max_chatbot_threads`** β€” how many chatbot threads one user may\\n keep, `1`–`500` (default `50`); at the cap the user deletes an old one\\n first. Storage protection, not a usage quota β€” that is the per-minute\\n message limit.\\n- **`max_chatbot_message_len`** β€” character limit on one chat message,\\n `100`–`8000` (default `4000`); the ceiling is a server hard cap, because\\n the message and its history must fit one bridge frame.\\n\\nA `PATCH` replaces only the fields it carries, each wholesale, and validation\\nis all-or-nothing. Concurrent edits are safe: each save applies only if the\\npolicy still matches the snapshot it merged from (retrying over the fresh row\\notherwise), so two managers patching different fields both land instead of\\nthe later write silently reverting the earlier one. Editing a list never\\nrewrites history: an exam keeps its retired kind, a roll-call row keeps its\\nretired status β€” only **new writes** are held to the current lists (which is\\nwhy grading an exam whose kind has left the list is refused).\\n\\nThe kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see \\"Food program: menus, dishes, bookings & the ledger\\").\\n\\nAcademic structure is data too. **Terms** (`/terms`) model whatever calendar\\nthe school runs β€” semester, trimester, quarter systems are just rows with a\\nname and a date range. Courses may link to one via `term_id` (nullable), and\\ndeleting a term is refused with a `409` while any course still links to it β€”\\nunlink those courses (`PATCH /courses/{id}` with `\\"term_id\\": null`) or delete\\nthem first, so the calendar never disappears under them. Term dates may lie in the past,\\ndeliberately: a school adopting the app mid-year backfills its calendar β€”\\nunlike exam/lesson/event times, which reject backdating.\\n\\nWhat stays fixed is deliberate too: the four roles, the `0`–`100` mark scale,\\nvalidation bounds, and the UTC time policy are invariants, not preferences\\n(rename role labels in the frontend if a school says \\"principal\\" instead of\\n\\"manager\\"). Deployment knobs (ports, rate limits, admin seed, CORS) remain\\nenvironment variables β€” the model is **one school per deployment**, which\\nkeeps every school's data physically isolated.", "source": "README.md"}, {"id": "food-program-menus-dishes-bookings-attendance-the-ledger", "title": "Food program: menus, dishes, bookings, attendance & the ledger", "body": "The school publishes **one menu per calendar day and meal slot** (`POST\\n/meals/menus`). Two shapes there are deliberate:\\n\\n- **`date` is text**, `YYYY-MM-DD`, not a timestamp. \\"One menu per day and\\n slot\\" is an equality test on the school's own day, and a midnight-in-millis\\n day is only unique for one timezone. Fixed-width and zero-padded, so the\\n text sorts chronologically β€” which is what the inclusive `?from=&to=` range\\n filter and the newest-day-first ordering are built on.\\n- **`slot` is a snapshot**, not a link into settings. It must be one of the\\n school's `meal_slots` (`GET /settings`) *when the menu is written*, and it\\n is stored as text β€” so retiring a slot later never rewrites a menu already\\n published under it. The slot's `serving_minute` is *not* snapshotted: the\\n booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any\\n menu was published for cannot be removed from the list (`409`), same\\n contract exam kinds have with graded exams.\\n\\nThe day+slot pair is unique: a second publish for the same meal answers `409`\\nβ€” edit the first one instead. Only `capacity` is patchable (`null` = uncapped)\\nβ€” `date` and `slot` are immutable, because a menu on another day is another\\nmenu.\\n\\n**Dishes** hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, then\\n`PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional\\ndescription (blank or `null` clears it), dietary `tags` drawn from the\\nschool's `dietary_tags` list β€” an unknown tag is a `400`, never a stored\\nstring β€” and a `price_minor`.\\n\\n### Dietary profiles and conflicts\\n\\nA student carries a **dietary profile**: a list of tags plus a free-text note\\nfor the kitchen, one row per student (the record key *is* the student's id).\\nThe tags come from the *same* `dietary_tags` list a dish is tagged from β€”\\nthere is deliberately no second vocabulary, because one shared list is exactly\\nwhat makes \\"is this dish a problem for this student\\" answerable as a set\\nintersection, without the backend knowing any nutrition.\\n\\nWriting it is **manager+** (`PATCH /meals/profiles/{user}`, first write\\ncreates the row). A student does *not* edit their own allergen list: it is a\\nsafety record the school keeps on their behalf, and a mistyped β€” or quietly\\nremoved β€” allergy would otherwise reach the kitchen with the school's\\nauthority behind it. Reading is `GET /meals/profiles/me`, or\\n`GET /meals/profiles/{user}` under the usual per-student gate (own id always,\\notherwise teacher+ or a parent link). A student who was never recorded reads\\nback as an *empty* profile rather than a `404` β€” \\"nothing known\\" is an answer.\\n\\nEvery dish a menu read returns therefore carries a **`conflicts`** list: the\\nintersection of that dish's `tags` with the **calling user's** profile tags.\\nIt is empty when the two do not overlap, and empty for every reader without a\\nprofile β€” a manager reading a menu sees `conflicts: []`, which is correct and\\nnot a bug (the field answers \\"may *I* eat this\\", and there is no \\"conflicts\\nfor student X\\" parameter). The caller's profile is loaded **once per request**,\\nnot per dish, so the menu list stays at its fixed query count no matter how\\nmany menus or dishes the page holds.\\n\\n**Money is minor units** (kuruş) as an integer, at every layer: `4550` is\\n45,50 β‚Ί. This API never speaks decimals or floats about money, so no rounding\\nis ever introduced by transport or by a client's JSON number parser.\\n\\nReads are open to every authenticated user β€” a student has to see what is\\nbeing served β€” and every write is manager+. Deleting a menu takes its dishes\\nwith it: a dish has no meaning apart from the menu it was published on.\\n\\n**Bookings** are seats on a published menu (`POST\\n/meals/menus/{id}/bookings`). One row per (menu, student), keyed by a\\ndeterministic composite id, so booking twice is the same seat and never a\\nsecond one. A **student books only for themselves**; a **parent books for a\\nstudent they hold a link to** β€” the one write a `parent_link` authorises, since\\npaying for lunch is a parent's job. Nobody else books through this route: a\\nteacher or manager ordering a child's lunch is a `403`.\\n\\n- **Cancelling is a status flip, not a delete** (`DELETE\\n /meals/bookings/{bid}` answers `200` with the flipped row): the row survives\\n as `cancelled` with a `cancelled_at` stamp, so a freed seat stays auditable\\n against the money it moved. Only `booked` rows count against `capacity`,\\n which is what genuinely frees the seat β€” and re-booking is the same row\\n flipped back. The call is **idempotent**: cancelling an already-cancelled\\n seat answers `200` with the row as it stands *and replays the refund*, so a\\n cancel cut short between the flip and the reversal (the tab closed, a proxy\\n timed out) is recovered by sending it again. Refusing it as a `409` β€” as it\\n once did β€” made that state permanent: no route could append the missing\\n reversal, and the student stayed billed for a seat they no longer held.\\n- **The capacity check is serialized in-process.** Counting rows and then\\n writing one is write-skew: SurrealDB does not conflict-check a cross-record\\n count against a concurrent insert, so 24 students racing for 3 seats would\\n otherwise all pass the count. The whole check-then-write runs under the same\\n lock a menu publish takes, and the cap is re-read inside it.\\n- **One cutoff closes both ends.** Within the school's\\n `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new\\n booking nor a cancellation lands (`409`) β€” the kitchen's headcount has to\\n settle at some point. `null` (the default) means no cutoff at all. The\\n cutoff is measured back from the menu's `date` **plus the slot's\\n `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served\\n at `720` closes at 10:00 UTC that morning, not at 22:00 the night before.\\n **That minute is UTC**: `date` carries no timezone and the backend stores no\\n school timezone β€” deliberately, it is a rejected feature β€” so a UTC+3 school\\n enters `540` (09:00 UTC) for a meal served at noon locally. A slot with no\\n `serving_minute` falls back to **midnight UTC starting the meal's day**, the\\n behaviour every booking had before the field existed; the booking is never\\n refused for want of a serving time.\\n- **The serving time is read live, not snapshotted onto the menu.** The cutoff\\n minutes are already read live, so freezing the other half of the same\\n deadline would make one policy edit apply and its twin not; a kitchen that\\n moves lunch an hour later wants today's menus to move with it. The menu\\n still snapshots the slot *name* (that is what keeps a retired slot's history\\n readable), so a menu whose slot has since left the list simply has no\\n serving time and falls back to midnight UTC.\\n- A menu somebody still holds a seat on **cannot be unpublished** (`409`) β€”\\n cancel the bookings first, so nothing is left pointing at a deleted meal.\\n\\n`GET /meals/bookings/me` is the caller's own list: the seats held *for* them\\nplus, for a parent, the seats held for every student they **currently** hold a\\nlink to β€” so a parent's list is their children's meals. The links are re-read\\non every call rather than trusted from the booking's `booked_by` stamp: an\\nunlinked parent stops seeing the child's seats at once, including the ones\\nthey booked and paid for themselves, exactly like every other parent read. `GET /meals/menus/{id}/bookings` is the kitchen's list for\\none menu (manager+), cancelled rows included so the changes are visible.\\n\\n### Meal attendance\\n\\nWhoever stands at the canteen door records who actually ate:\\n`POST /meals/menus/{id}/attendance` with `{student_id, status}`, teacher+ (a\\nstudent never marks, not even themselves). The status is the fixed pair\\n`served` / `missed` β€” deliberately **not** the school's editable\\n`attendance_statuses`, since a canteen line has no \\"late\\" or \\"excused\\", and one\\nlist meaning two things would let a school change one by editing the other.\\nOne row per (menu, student) keyed by a composite id, so a correction re-marks\\nthe same row instead of stacking a second one.\\n\\n**Attendance has zero billing effect.** Booking is the sole charge trigger, so\\na student who booked and did not eat still pays β€” the kitchen bought the food.\\nThere is no no-show penalty, no refund-on-missed, and no auto-reversal:\\nnothing under `meal_attendance` writes to the ledger. A walk-in with no live\\nbooking *can* be marked `served` (the record is operationally true) and is\\nlikewise not charged for it β€” charging there would be a ledger write. The\\ntarget only has to *exist*: a canteen also feeds staff, so any user may be\\nmarked, not only a student. A mark is a record of what happened, not a check\\nof who was entitled, and since it moves no money it costs nobody anything.\\n\\n`GET /meals/menus/{id}/attendance` is the per-menu list (teacher+), and\\n`GET /meals/attendance/{user}` is one student's history, narrowable with\\n`?from=&to=` β€” inclusive `YYYY-MM-DD` bounds compared against the *menu's*\\nday, a lexical compare that is chronological for that format. Same gate as the\\nbalance and the ledger: the caller's own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`meal_ledger`): one line per `charge`,\\n`credit`, or `reversal`, every field `READONLY`, and **no code path anywhere\\nthat updates or deletes one**. A ledger line that can be edited or dropped\\nsilently rewrites a student's financial history with no trace of the rewrite β€”\\nthis is the one genuinely irreversible part of the food program, so a mistake\\nis corrected by appending the opposing line, which leaves both the mistake and\\nthe correction visible.\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer.\\nA *negative* balance means the student owes the school; a positive one is\\nmoney on account. Amounts are stored positive; the sign lives in the `kind`.\\n\\n- **Booking is what charges, at a price snapshot.** The menu's dishes are\\n summed the moment the seat is taken and that number is frozen onto the\\n charge. Editing a dish's price afterwards moves no existing charge β€” what a\\n student owes is what the menu cost the day they booked. The price is\\n snapshotted *before* the seat is given, so a menu that cannot be charged\\n refuses the booking rather than leaving a booked-but-unbilled row (`400`,\\n when the dishes sum past 10 000 000). A free menu writes no line at all β€”\\n but the booking row records that it *was* free, so \\"free when taken\\" is\\n never confused with \\"not billed yet\\": pricing the menu afterwards leaves\\n every seat already taken on it free.\\n- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its\\n money move together under one in-process lock, and the ledger id is derived\\n from the seat plus how many times it has been taken β€” so eight simultaneous\\n `POST`s of one seat write one charge, a retried cancel refunds once, and a\\n write that failed halfway heals when the request is repeated. Booking the\\n same seat twice bills once because the *identity* is the same, never\\n because a scan happened to see the first charge in time.\\n- **Cancelling appends a `reversal`** for the charge's exact amount, with\\n `source` pointing at the charge it undoes. The charge row itself stays. A\\n cancel past the cutoff is already a `409`, so a reversal only ever follows a\\n legal cancel β€” and repeating a cancel replays the reversal, which is what\\n makes the refund recoverable rather than a one-shot the network can lose.\\n Re-booking afterwards is a **fresh** charge at the then-current price.\\n- **The price snapshot is taken under the booking lock**, and dish\\n create/edit/delete take that same lock. Taken outside it, a dish added\\n between the sum and the seat would be frozen onto the row as \\"the menu was\\n free then\\" β€” and nothing heals it, since a seat already held is returned\\n as-is, never re-priced.\\n- **A no-show still pays.** Meal attendance has zero billing effect β€” nothing\\n in the ledger reads or writes it. The seat was reserved and the food was\\n cooked; there is no no-show penalty and no no-show refund.\\n- **`POST /meals/credits` is admin-only**, not manager: writing down cash\\n received is the highest-trust action in the app. It appends a `credit` for a\\n student with a positive `amount_minor` (≀ 10 000 000), an optional `method`\\n (\\"cash\\", \\"havale\\", …) and `note`, and records the admin as `recorded_by`.\\n There is no payment gateway and no card data, ever. An over-credit is\\n corrected with a compensating line, never a fix-up.\\n\\n`GET /meals/balance/me` is the caller's own balance. `GET\\n/meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line\\nfirst) read a student's: your own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student. A charge's `source` is the\\nbooking id it came from, a reversal's is the charge line it reverses, and a\\ncredit has none.", "source": "README.md"}, {"id": "payments-fee-plans-assignment-the-fee-ledger", "title": "Payments: fee plans, assignment & the fee ledger", "body": "School fees live in their own tables (`fee_plan`, `fee_plan_assignment`,\\n`payment_ledger`) and their own balance. **Meal money is separate** β€” two\\nledgers, two balances, and no route folds one into the other: what a family\\nowes the canteen and what it owes the school are different debts, and mixing\\nthem would make either statement unreadable.\\n\\nEvery write here is **manager+**. Reads are narrower than the other\\nper-student reports: the student themselves, a parent holding a live link to\\nthem, or manager+ β€” **a teacher gets a `403` on every `/payments` route**,\\nbecause what a family owes the school is not classroom information.\\n\\n### Fee plans and what turns them into money\\n\\nA **fee plan** (`POST /payments/plans`) is a name and 1 to 60 **installments**,\\neach `{amount_minor, due_at}` β€” minor units (kuruş) as an integer, and unix\\nmilliseconds. `due_at` **may be in the past**: a school adopting the app\\nmid-year assigns plans whose first installments were already due, so there is\\nno future-date rule here.\\n\\nWriting a plan bills nobody. **Assigning it does** (`POST\\n/payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call):\\nthat appends *every* installment as a `charge` line right away, each carrying\\nits own due date. There is no scheduler, no nightly sweep, and nothing that\\nwakes up when a date passes β€” the whole schedule is written once, and lateness\\nis read off it.\\n\\nAssignment is **replay-safe by identity**: the assignment row is keyed\\n(plan, student) and every charge it raises is keyed (plan, student,\\ninstallment), so re-assigning bills nothing a second time (that student comes\\nback `already_assigned`), and an assignment cut short after three of twelve\\ncharges landed completes itself when the call is simply repeated. Only\\nstudents carry a fee record, so any other target comes back `rejected` β€” one\\nbad id never loses the rest of the batch.\\n\\nA plan that has been assigned to anyone can no longer be edited or deleted\\n(`409`). Its charges are frozen copies of the installments as they stood, so\\nan edit would only make the plan and the money tell different stories β€” write\\na new plan instead.\\n\\nThat freeze is a **counter on the plan row** (`assignment_count`), incremented\\nin the *same transaction* as the assignment row it counts, and the edit and the\\ndelete are single-record conditional writes against it β€” the same shape as a\\nterm's `course_count`. It used to be a `SELECT` taken before the write, which a\\nconcurrent assign could land behind, leaving a plan edited *and* assigned, or\\ndeleted with a live assignment naming it. Now the two contend on one record: an\\nassign either freezes the plan first (and the edit or delete is a `409`) or\\narrives after it (and bills the edited plan β€” the installments a first\\nassignment charges are re-read from the *stored* plan at the instant it\\nfreezes, never from the copy the request first looked at). A plan deleted out\\nfrom under a running batch is `rejected` for that student on, in the same\\nper-student report as every other outcome β€” the students it already billed are\\nnever dropped from the answer. A `PATCH`\\ncarrying no field at all writes nothing, so it is not refused.\\n\\nBecause an assignment is never removed, the counter is only ever claimed and\\nnever released: once assigned, a plan stays frozen for good. Plans written\\nbefore the counter existed are seeded from their assignment rows at boot,\\nbefore the server accepts a request β€” an absent counter reads as zero, and a\\nzero would have re-opened every already-assigned plan on an existing volume.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`payment_ledger`), exactly like the\\nmeal one: every field `READONLY`, and **no code path anywhere that updates or\\ndeletes a line**. A ledger line that can be edited or dropped silently\\nrewrites a family's financial history with no trace of the rewrite, so a\\nmistake is corrected by appending the **opposing line**, which leaves both the\\nmistake and the correction visible.\\n\\nFour kinds, and the sign lives in the `kind` β€” amounts are always stored\\npositive:\\n\\n| Kind | Sign | What it records | `source` points at |\\n| ---------- | ---- | ------------------------------------------------ | ------------------ |\\n| `charge` | βˆ’1 | An installment billed by a plan assignment | the assignment |\\n| `credit` | +1 | Money received, against one named charge | the charge paid |\\n| `reversal` | +1 | A `charge` or `refund` entered in error, undone | the undone line |\\n| `refund` | βˆ’1 | Money handed back, against one named payment | the credit returned |\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge) - SUM(refund)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer. A\\n*negative* balance means the family owes the school; a positive one is money on\\naccount.\\n\\n- **A payment names the charge it settles.** `POST /payments/credits` takes\\n `{charge_id, amount_minor, method?, note?}`: allocation is *recorded*, never\\n inferred from a balance, so a statement can say which installment is still\\n open rather than only how much is outstanding. **Partial payments are the\\n norm** β€” several credits accumulate against one charge.\\n- **A refund names the payment it returns.** `POST /payments/refunds` takes\\n `{credit_id, …}`, partials allowed, capped by what that credit was worth.\\n This is also the **only** way a mistaken credit is corrected: a credit is\\n never reversed, so money leaving the school is always spelled the one way.\\n- **A retry is not a second payment β€” when the client says so.** Both routes\\n take an optional `request_key` (`[A-Za-z0-9-]`, 1 to 64 characters β€” `_` is\\n the separator inside a ledger id, so a key may not carry one). With\\n one, the line is keyed `<charge>_k_<key>` (a refund: `<credit>_kr_<key>`), so\\n a client retrying after a network timeout gets **the line the first attempt\\n wrote**, not a second charge on the family β€” idempotence by identity, the\\n same rule that keeps a replayed assignment from billing twice, never a \\"has\\n this been recorded yet?\\" scan two concurrent requests can both walk past. The\\n replay is answered **before** the over-payment cap is consulted, so a payment\\n that filled its charge to the penny still replays as itself instead of coming\\n back \\"already paid in full\\". Sending that key again with a **different**\\n `amount_minor` or a different target is a `409`, never the stored line: that\\n is a client bug, and a `201` would bury it. Omit the key and nothing changes\\n from before β€” two identical posts are two payments, which is exactly what a\\n desk taking the same amount twice means.\\n- **A reversal only undoes a `charge` or a `refund`**, for its exact amount and\\n nothing else (`400` on any other kind). It is keyed `<line>_r`, so a line has\\n at most one reversal however often the call is retried, and the reversed line\\n itself stays on the record beside it.\\n- **A refund frees the charge's room.** The cap on a payment is folded over the\\n target's whole source subtree, so refunding a payment gives that charge its\\n room back and the charge **can be paid again** β€” and reversing that refund\\n takes the room back with it. Money that came back out is not money the school\\n still holds.\\n- **The over-payment cap is not the database's.** The `409` past a charge's or\\n a credit's worth is a cross-record fold, which SurrealDB cannot enforce on\\n its own; it holds because the backend is one process and the fold, and the\\n append it authorizes, are taken under one lock. Should an over-payment ever\\n be recorded anyway it is not a crisis: this is human data entry at an office\\n desk, the outcome is an over-paid charge that is plainly visible in the\\n statement, and it is undone by appending a refund. Both lines are true\\n records of money that really arrived β€” refusing them would be the worse lie.\\n- **There is no payment gateway and no card data, ever**, and none is planned:\\n nothing here talks to a bank, a PSP, or a card network. `method` is free text\\n (\\"cash\\", \\"havale\\", …) describing how money that already arrived was handed\\n over, and `note` is whatever the office needs to remember (a receipt number,\\n say).\\n\\n### Statements, balances and `overdue`\\n\\n`GET /payments/ledger/{user}` is the raw lines, newest first, paged.\\n`GET /payments/statement/me` and `/payments/statement/{user}` are the\\n**per-charge rollup** (its rows paged by the usual opt-in `?limit=&offset=`,\\nin an `entries: {items, total, limit, offset}` envelope): one row per charge with its plan, the installment's\\namount and due date, what it collected, what went back out, what is still\\noutstanding, whether the charge itself was reversed (such a charge owes\\nnothing), and whether it is **`overdue`** β€” still owed, and its `due_at` has\\npassed.\\n\\nAll of that is folded from the raw lines **on every request and stored\\nnowhere**, `overdue` included. Paging windows the *returned rows* only, after\\nthat fold: `balance_minor` β€” and every row's own arithmetic β€” is identical on\\nevery page, because it is read from all of the student's lines either way. There is no overdue flag, no sweep that sets\\none, and no stored rollup: a stored rollup is a second version of the truth,\\nand the ledger is the first. `GET /payments/balance/me` and\\n`/payments/balance/{user}` are the same fold reduced to one number.", "source": "README.md"}, {"id": "exam-modes-attempts-retakes-rejoin-live-monitoring", "title": "Exam modes, attempts, retakes, rejoin & live monitoring", "body": "Preparing an exam is slow work, so an exam can be created as a **draft**\\n(`draft: true`): only the course's managers see it (to students it's a `404`\\nthat might as well not exist β€” lists, direct reads, and attempts all hide\\nit), nobody can sit it, and grading it is a `409`. The teacher builds the\\nquestions in peace and publishes with `PATCH /exams/{id}` `{\\"draft\\": false}`.\\nAn exam can go back into hiding the same way β€” but only while it has **no\\nattempts and no results**; after that, re-drafting is a `409` (students never\\nlose sight of an exam they've sat or been graded on). Existing exams (and\\nthose created without the flag) are published from the start.\\n\\nSeparately from drafts, a published exam without a `mode` (all schedule\\nfields `null`) is **offline-graded** β€” a paper exam whose marks are entered\\nby hand; students see it and their marks, but attempts on it are a `409`\\n(\\"nothing to sit\\"). Making an exam sittable means giving it a `mode`, as one\\nconsistent unit (validated together on create and after every `PATCH` merge):\\n\\n- `mode: \\"sync\\"` + `starts_at` + `ends_at` β€” everyone sits inside one window;\\n every attempt's deadline is `ends_at`.\\n- `mode: \\"async\\"` + `starts_at` + `ends_at` + `duration_ms` β€” each student\\n starts anywhere inside the window and gets\\n `min(started_at + duration_ms, ends_at)` as their personal deadline.\\n- `mode: \\"open\\"` β€” no window at all: students sit anytime. `duration_ms` is\\n *optional* β€” set it for a per-attempt countdown (`started_at +\\n duration_ms`), omit it for unlimited time (the attempt only ends by\\n submission).\\n- `duration_ms` is 1 minute to 24 hours wherever it appears, and for `async`\\n cannot exceed the `starts_at`..`ends_at` window (equal to it is fine).\\n `ends_at` must be strictly after `starts_at`, and neither may be *set* in\\n the past β€” on create or `PATCH` (kept values are exempt, so a running exam\\n stays editable). All instants are the usual UTC unix-milliseconds, judged\\n only by the server clock (`GET /time` for sync).\\n\\nTwo per-exam policy knobs ride along, both **live-editable** at any point:\\n\\n- `max_attempts` (default `1`, `0` = unlimited) β€” how many sittings each\\n student gets. Raising it mid-exam grants retakes on the spot; lowering it\\n never kills a running attempt, it only blocks future starts.\\n- `allow_rejoin` (default `true`) β€” whether a student who *left the exam room*\\n may come back in and keep answering (see the exam-room section).\\n- `allow_review` (default `false`) β€” opt-in door to the student self-review\\n reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A\\n student may review only when this is on **and** the teacher has marked them\\n (an `ExamResult` row exists); own-scoped, so no student reads another's sheet.\\n\\nA student **sits** an exam through attempts (sitting 1, 2, … β€” each row id is\\nthe composite `exam_user[_seq]` key, so a sitting exists at most once by\\nconstruction):\\n\\n- `POST /exams/{id}/attempt` starts, resumes, or retakes (students only β€”\\n staff never sit; enrolled; window open where one exists β€” `open` exams start\\n anytime). While the latest\\n sitting runs, re-posting returns it unchanged (`200`, not `201`):\\n reconnecting never resets the clock. Once it is submitted or expired,\\n re-posting mints the next sitting (`201`) **from a blank answer sheet** β€”\\n the previous sitting's answers are wiped β€” until `max_attempts` is spent\\n (`409` after that). Starting is the live-attendance signal.\\n- `GET /exams/{id}/attempt` is the student's exam screen: the latest sitting's\\n `status` (`in_progress` | `submitted` | `expired`), `attempt` (its number),\\n `attempts_used`/`max_attempts`, `deadline`/`remaining_ms` (`null` for an\\n untimed open exam), `left_at`, own `mark` once graded, and the server `now`.\\n- `POST /exams/{id}/attempt/finish` submits. After the deadline the attempt is\\n `expired` β€” a valid terminal state (the student used their full time), and\\n finishing answers `409`. Grading stays per exam+user (one mark), whatever\\n the sitting count β€” the sheet a grader sees is always the latest sitting's.\\n\\nDeadlines are **recomputed from the exam's current schedule on every read**,\\nnever stored: a teacher who `PATCH`es `ends_at` (or a `duration_ms`)\\nwhile the exam runs moves every running deadline instantly. What's frozen once\\nanyone has started is only `mode` (including back to unscheduled) β€” swapping\\nthe deadline rules mid-sitting would be a different exam (`409`).\\n\\nThe course's manager (its creator, or manager+) watches it all live:\\n`GET /exams/{id}/live` returns one snapshot β€”\\nthe enrolled roster joined with attempts and marks (`not_started` | `absent` |\\n`in_progress` | `submitted` | `expired`, per-student `attempt` /\\n`attempts_used` / `left_at` / `deadline` / `remaining_ms` / `mark`, always the\\nlatest sitting) plus summary counts, all judged at a single `now`. Once the\\nwindow closes, `not_started` hardens into `absent` β€” the no-shows, flagged\\nright in the roster (open exams have no window, so never an `absent`). The\\nflag is informational: an absent student still has no mark until the teacher\\nrecords one through `POST /exams/{id}/results`. Poll `GET /exams/{id}/live` to\\nkeep a monitor current β€” attendance, ticking clocks, submissions, and marks all\\nride in each snapshot.\\n\\nDeleting an exam (or its course) cascades attempts, questions, answers, and\\nquestion + answer images (blobs included) along with results; unenrolling mid-exam\\nhides the student from the monitor roster but keeps the attempt and mark\\nrows, mirroring the marks report.\\n\\n> **Upgrading a pre-course database**: `exam` rows created before courses\\n> existed lack the now-required `course` field and will fail to deserialize.\\n> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data,\\n> backfill manually with the SurrealDB CLI (server stopped), e.g.\\n> `UPDATE exam SET course = course:<id> WHERE course = NONE;`\\n> after creating a course to attach them to.\\n>\\n> **Upgrading to the attempts/rejoin build needs nothing manual**: the boot\\n> migration backfills `max_attempts = 1`, `allow_rejoin = true`, and attempt\\n> `seq = 1` on existing rows, and swaps the single-attempt unique index for\\n> the per-sitting one. Pre-upgrade attempts keep their record ids and count\\n> as sitting #1.\\n>\\n> **Upgrading to the kind-weight build is a clean break**: weights moved off\\n> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with\\n> no data migration. A database from an older build has string kinds and a\\n> per-exam `weight` column the code no longer understands β€” delete\\n> `./data/hezarfen.db` and reboot.", "source": "README.md"}, {"id": "taking-an-exam-questions-answers-the-exam-room", "title": "Taking an exam: questions, answers & the exam room", "body": "Teachers author a question list per exam; students answer inside their\\nattempt, autosaved as they go; choice questions are machine-checked as a\\n**suggestion** β€” the final mark stays a human call through the existing\\n`POST /exams/{id}/results`.\\n\\n**Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`,\\ncourse-management rights): each has a mandatory `subject_id` (one of the\\ncourse's subjects, `GET /courses/{id}/subjects` β€” the topic the question\\nbelongs to), `text` (≀ 2000 chars), `points` `1`–`100`\\n(its share of the auto-score), and a `kind`:\\n\\n- `kind: \\"choice\\"` β€” carries `choices` (2–10 options, each ≀ 500 chars) and\\n `correct`, the zero-based index of the right option. Auto-scorable.\\n- `kind: \\"text\\"` β€” free text, judged by the grader; carries neither.\\n\\nThe kind bundle is validated as a unit (create and after every `PATCH` merge):\\nswitching a question to `text` needs explicit `\\"choices\\": null, \\"correct\\":\\nnull`, switching to `choice` must bring both along. Presentation order is\\ncreation order. The whole list **freezes once anyone has started an attempt**\\n(`409` on create/edit/delete) β€” editing questions under a sitting student\\nwould fork what \\"the exam\\" means. Deleting a question cascades its answers\\nand images.\\n\\n**Question images**: any question may carry one **illustration** (`POST\\n/exams/{id}/questions/{qid}/image` β€” the map the prompt asks about, on\\n`choice` and `text` questions alike), and each option of a `choice` question\\nmay carry a **picture** of its own (`POST .../choices/{choice_id}/image` β€” so\\nthe options themselves can be images: four map crops, pick the right one).\\nUploads are `multipart/form-data` with a single `file` part, capped by the\\nschool's `max_file_bytes`; the declared content type must be `image/png`,\\n`image/jpeg`, `image/webp`, or `image/gif` (rasters only β€” SVG can script,\\nand these bytes render inline for the whole class). One image per slot:\\nre-uploading replaces, `DELETE` on the same paths removes, and replacing a\\nquestion's `choices` list drops all its option pictures (the illustration\\nstays β€” re-upload against the new list). Image writes follow question\\nauthoring exactly: course-management rights, frozen once attempts exist.\\nBoth question views (`GET /exams/{id}/questions` and the sitting view)\\nembed the metadata as `image: {content_type, size} | null` and\\n`choice_images: [...|null]` aligned with `choices`; the bytes come from the\\n`GET` endpoints above β€” course managers anytime, students through the same\\nenrollment + started-attempt wall as the sitting view (no early peek at the\\npictures either), served with `Cache-Control: private, no-store`.\\n\\n**Answering** (student, attempt `in_progress`, deadline judged by the server\\nclock on every save):\\n\\n- `GET /exams/{id}/attempt/questions` β€” the sitting view. Requires\\n enrollment (`403` β€” the questions are course content, so leaving the course\\n closes them) and an attempt (`404` before `POST /exams/{id}/attempt`; also\\n the anti-peek gate), never contains `correct`, and embeds the caller's own\\n saved answer per question (`{selected, text, updated_at}` or `null`). Still\\n readable after submitting/expiry, for review.\\n- `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` β€” an\\n upsert: one row per question+user, re-answering overwrites. The payload must\\n match the question's kind (`selected` indexing a choice, or `text`\\n ≀ 10 000 chars β€” empty clears the draft); mismatches are `400`s. Requires\\n the student role and enrollment (`403`): a promotion out of `student` or an\\n unenrollment mid-exam closes the sheet (the exam room's door checks,\\n re-applied to every save β€” finishing stays open). Once the\\n attempt is submitted or past its deadline every save is a `409` β€” likewise\\n while the student has left the exam room with `allow_rejoin` off; answers\\n saved in time survive untouched for grading. Each sitting keeps its own\\n answers, drawings, and mark, keyed by the attempt's `seq` β€” a retake starts\\n from a blank sheet without erasing the prior one, so the full per-attempt\\n history stays readable (see the grading view).\\n\\n**Answer images**: the student side mirrors the teacher's question images. A\\nstudent may attach one **drawing** to any question in their attempt β€” a\\nsketched answer or worked steps β€” via `POST\\n/exams/{id}/attempt/answers/{qid}/image` (`multipart/form-data`, one `file`\\npart, the same raster allowlist and `max_file_bytes` cap as question images).\\nOne image per question: re-uploading replaces, `DELETE` on the same path\\nremoves. Writes ride the exact `POST /exams/{id}/attempt/answers` gate β€” the\\nstudent role, enrollment, an `in_progress` attempt, and the rejoin door β€” so a\\ndrawing is just another autosaved answer; a drawing-only answer (nothing\\ntyped) still surfaces, and clearing it grooms the empty row away. The bytes\\ncome from `GET` on the same path (the caller's own, behind the sitting-view\\nwall) and, for the grader, `GET /exams/{id}/attempts/{user}/answers/{qid}/image`\\n(course-management rights); both serve inline with `Cache-Control: private,\\nno-store`. The metadata rides the answer as `answer_image: {content_type,\\nsize} | null` on both the sitting view and the grading sheet. To the backend\\nit is a normal raster PNG; the frontend piggybacks its editable stroke data in\\na PNG `tEXt` chunk, opaque here β€” stored on disk under `Config::files_path`\\nby a ULID, metadata in the `answer_image` table, structurally identical to\\nquestion images.\\n\\n**Grading view** (course-management rights): `GET /exams/{id}/attempts/{user}/answers` returns\\nthe student's **latest** sitting's sheet β€” every saved answer with `is_correct`\\n(`true`/`false` for choice, `null` for text: that's the grader's call) plus\\n`auto_score: {earned, possible}` summing the choice questions' points. It is a\\nsuggestion to read while grading, never written anywhere.\\n\\n**Per-attempt history** (course-management rights): prior sittings stay\\nreadable. `GET /exams/{id}/students/{user}/attempts` lists the sitting numbers\\na student has (every `seq` carrying answers or a mark, ascending);\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers` is the grading sheet\\nfor one of them (drawing bytes at\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image`); and\\n`GET /exams/{id}/students/{user}/marks` is the full per-sitting mark history,\\noldest first. Grading (`POST /exams/{id}/results`) always lands on the current\\nsitting, and the latest seq is the grade-of-record β€” the roster, report, and\\nstatistics reads all show it. Every result payload carries its `seq`, so a mark\\nlinks straight to that sitting's answer sheet β€” without it a marked retake's\\nanswers would be unreachable from the mark.\\n\\n**The exam room (WebSocket)** β€” `GET /exams/{id}/attempt/ws`, cookie-authed\\nlike everything else; REST above remains the full fallback. Gates run before\\nthe upgrade: unknown or draft exam `404`, unscheduled (no mode) `409`, not a\\nstudent `403`, not enrolled `403`, no attempt yet `404` (start it first),\\nsubmitted/expired `409`, left while rejoin is closed `409`. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| server β†’ | `{\\"type\\":\\"state\\", status, attempt, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save |\\n| client β†’ | `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"selected\\":1}` or `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"text\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` |\\n| server β†’ | `{\\"type\\":\\"saved\\", question_id, updated_at, client_seq?}` β€” the autosave ack |\\n| client β†’ | `{\\"type\\":\\"finish\\"}` β€” submit the attempt |\\n| server β†’ | `{\\"type\\":\\"finished\\", finished_at}`, then Close |\\n| server β†’ | `{\\"type\\":\\"expired\\"}`, then Close β€” a tick noticed the deadline |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", message, question_id?, client_seq?}` β€” bad JSON, wrong kind, deadline, … |\\n\\nAn `answer` may carry a `client_seq`: any number the client picks, echoed verbatim on\\nthat message's `saved` or `error` and on nothing else. The server never reads\\nit β€” no uniqueness, no ordering, no dedupe, all the client's business β€” and\\nomits the key entirely when the request omitted it, so leaving it out keeps\\ntoday's frames byte for byte. It exists because `question_id` is not an\\nidentity: save a question, time out, save it again, and two sends are\\noutstanding for the same id β€” the first reply would settle the second and the\\nUI would claim \\"Saved\\" for an answer the server never took. `question_id` on\\nan `error` is the separate, orthogonal question: whether the failure belongs\\nto that one question (payload or question) or to the room, in which case every\\nsave in flight is equally refused. An error can carry `client_seq` without\\n`question_id`.\\n\\nEvery tick and every save re-read the exam, so a mid-exam `ends_at` extension\\nmoves the room's countdown on the next tick, and no stale socket can write\\npast its real deadline β€” the socket shares the exact REST write path. Each\\nroom acts only on the sitting it was opened for: once that sitting is over,\\nits `answer`/`finish` are `error` frames, so a lingering socket can never\\nscribble on (or instantly submit) a retake started elsewhere.\\n\\nThe room is also the presence signal behind the **rejoin door**: connecting\\nclears the attempt's `left_at`, and the *last* socket of the sitting to close\\nwhile it is still running stamps it (visible on the live monitor β€” \\"left the\\nroom three minutes ago\\" at a glance). Closing one of two tabs is not leaving,\\nand a lingering socket from an already-finished sitting never marks a later\\nretake as left β€” each room is bound to the sitting it was opened for. With the exam's `allow_rejoin` off, a stamped\\n`left_at` refuses re-entry *and* any further saves, over the socket or REST,\\nuntil the teacher flips the door back open (`PATCH /exams/{id}\\n{\\"allow_rejoin\\": true}` β€” live, like the times). Finishing stays allowed: a\\nlocked-out student can always submit what they saved. The timer never pauses\\neither way. Students who only ever use REST never trip the door β€” the room is\\nwhat marks leaving.\\nExample client:\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/exams/${id}/attempt/ws`);\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"state\\") renderCountdown(m.remaining_ms, m.answered, m.question_count);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.question_id);\\n};\\nlet clientSeq = 0;\\nconst save = (question_id, selected) =>\\n ws.send(JSON.stringify({ type: \\"answer\\", question_id, selected, client_seq: ++clientSeq }));\\n```\\n\\nThe live monitor rides along: each roster row now carries `answered` and\\n`last_activity` (latest save instant), and the snapshot a top-level\\n`question_count`, so \\"stuck at 3/10 for five minutes\\" is visible at a glance.\\nThe student's own `GET /exams/{id}/attempt` echoes the same\\n`answered`/`question_count` pair.", "source": "README.md"}, {"id": "question-bank", "title": "Question bank", "body": "Writing good questions is slow, and the same one gets asked year after year, so\\nthe school keeps a reusable **question bank**. A bank question is an\\n`ExamQuestion` cut loose from any exam: it has the same shape (`subject_id`,\\n`text`, `kind`, `points`, and β€” for a `choice` β€” `choices` + `correct`), the\\nsame image slots (one illustration, plus a picture per option), and the same\\nnewtype validation, but it carries **no exam link**. Because nothing sits it,\\na bank row **never freezes** β€” its owner can edit or delete it forever.\\n\\n`POST /bank-questions` (teacher+) saves one, stamping the caller as its\\n**owner**. `subject_id` is origin metadata, but it must **exist** β€” an unknown\\nsubject is a `400` (create and PATCH alike). The reverse guard does **not**\\nhold here, unlike exam questions and homework: a template never blocks a\\nsubject delete, which simply clears `subject` off every template that carried\\nit (only a template's owner may re-tag it, so a `409` would be one a manager\\ncould never clear β€” and a private template raising it would leak its\\nexistence). Reads are school-wide: `GET /bank-questions` lists the\\nwhole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` β€” or\\n`?owner=me` β€” by owner) and `GET /bank-questions/{bid}` fetches one with\\n`correct` included β€” any teacher+ can browse and reuse what any colleague\\nbanked. Each response carries its **image metadata** β€” an `image` meta for the\\nillustration and a `choice_images` array aligned with `choices` (per-slot\\n`{content_type, size}`, `null` where a slot has no picture) β€” the same shape an\\nexam question's response uses; the bytes still come from the image endpoints.\\nMutation is **owner-only** (an `admin` bypasses): `PATCH /bank-questions/{bid}`\\nrevalidates the kind bundle as a unit, `DELETE /bank-questions/{bid}` drops the\\nrow and its image blobs. The illustration and option pictures work exactly like\\nan exam question's β€” `POST|GET|DELETE /bank-questions/{bid}/image` and\\n`…/choices/{choice_id}/image`, `multipart/form-data` with one `file` part, raster\\nonly (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` β€” reads school-wide,\\nwrites owner-only.\\n\\nThe bank feeds exams by **copying**, never linking. `POST\\n/exams/{id}/questions/from-bank/{bid}` instantiates a bank question into the\\nexam: it mints a **fresh** exam-scoped question (new id, its own answer rows,\\nits image blobs copied to new files), so later edits on either side never\\ntouch the other. The subject on the bank row is origin metadata only β€” the\\ncall takes its own `{subject_id}`, re-checked against the target course's\\nsubjects (`400` on a cross-course subject), and instantiating into an exam\\nthat already has attempts is a `409`, the same freeze that guards hand-authored\\nquestions. The instantiated question records the template it came from in\\n`source_bank`. The reverse, `POST /exams/{id}/questions/{qid}/to-bank`, copies\\nan existing exam question **into** the bank (new detached row, images copied to\\nnew files, owner = caller); the source question is left untouched, and the new\\ntemplate records the origin exam in `source_exam`. Both provenance fields are\\nnullable β€” a hand-authored question or template carries `null` β€” and one-way\\nmetadata (the copies stay fully detached). All bank routes are course-agnostic\\nand require teacher+.\\n\\nCopying means a template edit never reaches the copies, so there is one escape\\nhatch for that divergence: `POST /exams/{id}/questions/{qid}/refresh-from-bank`\\nre-copies the template's *current* content over one exam question β€” text,\\npoints, kind, choices (adopting the **template's** choice ids, so the option\\npictures re-land on the right options), `correct`, the illustration and the\\noption pictures. The question keeps its own id, its exam, its `subject` (the\\ntemplate's is unrelated origin metadata) and its provenance links; anything\\nedited on the copy is overwritten, deliberately. A question with no\\n`source_bank` β€” hand-authored, or its template deleted β€” is a `400`, a template\\nthe caller may not see is a `404` (never a 403), and the usual freeze applies:\\nonce any attempt exists, `409`. Every source blob is read before anything is\\nwritten, so a missing blob is a `500` with the question untouched rather than a\\nhalf-applied refresh.", "source": "README.md"}, {"id": "homework", "title": "Homework", "body": "A course hands out **homework**: `POST /courses/{id}/homework` with a title,\\nan optional description, a **required subject** (one of the course's own β€” and\\nthe same delete guard questions have: a subject with homework refuses deletion\\nwith a `409` until the homework is re-tagged via `PATCH /homework/{id}` or\\ndeleted), and a **required `due_at`** that must not lie in the past (same 60s\\ngrace as every schedule field; late *submissions* are fine β€” a late\\n*assignment* is not).\\n\\n**Audience.** By default the whole course, resolved live: whoever is enrolled\\n*when they act* β€” a student enrolled after the assignment sees and submits it\\nlike everyone else. `assigned` (at create or PATCH) instead pins a named\\nsubset of currently enrolled students (at most 200). The unnamed must not even\\nlearn a subset exists: lists omit it, and direct reads and submits answer\\n`404` β€” the same no-leak a hidden exam draft gets. Narrowing the subset later\\nis refused with a `409` that names the blockers while any submission or grade\\nbelongs to a student the new list would strand.\\n\\n**Submitting.** Students only β€” staff and parents never submit β€” enrolled and\\nin the audience, re-checked on every write. A submission is optional text plus\\nup to **10 files of any content type** (each ≀ the school's\\n`max_file_bytes`): text is replaced whole on each `POST` (omit to clear),\\nfiles are added and removed one by one, and a file upload with no prior\\nsubmission auto-creates an empty one, so a photo-only homework is a single\\nrequest. Two stamps tell the lateness story: `submitted_at` pins the **first**\\nhand-in forever, `updated_at` moves on every text edit and file add/remove,\\nand `late` is **computed on read** (`updated_at > due_at`), never stored β€” so\\ntouching work after the deadline flips it late, and a `due_at` edit re-grades\\nlateness for free. Late submissions are always accepted, only flagged. File\\nbytes always come back as a forced download (`Content-Disposition:\\nattachment`): homework accepts any content type, so rendering an uploaded\\nHTML/SVG inline would run it in the viewer's session.\\n\\n**Grading.** A course manager records a status β€” `done`, `incomplete`, or\\n`missing` β€” plus an optional 0–100 `mark` per student\\n(`POST /homework/{id}/results`, one upsert row per homework+student; the\\nexam walls apply: live students only, enrolled, in the audience, never the\\ngrader themselves). A stored grade **freezes** that submission β€” text edits,\\nfile changes, withdrawal all `409` β€” until\\n`DELETE /homework/{id}/results/{user}` removes it and reopens editing.\\nGrading before the due date, or before anything was submitted, is allowed β€”\\nthe latter is how never-handed-in work gets its `missing` verdict, and\\n`GET /homework/{id}/result` is where its student reads it (their submission\\nendpoints have nothing to show). The teacher-set `missing` **status** is a\\ndeliberate verdict; the roster and the report *also* compute a `missing`\\n**flag** for anyone unsubmitted past due β€” the two are independent. Homework\\nmarks stay out of `/marks`: the weighted course average remains exam-only\\n(the exam *kind* named `homework` still lives there), so nothing\\ndouble-counts.\\n\\n**Roster & report.** `GET /homework/{id}/submissions` (course manager) is the\\ngrading table: one row per audience student β€” plus any straggler outside the\\naudience who still owns a submission or grade (an unenrollment, a promotion,\\nor an audience change leaves work behind; it stays visible, flagged\\n`unenrolled`, though a stale student can neither submit nor be graded).\\n`GET /homework/report/{user}` is the fourth observer read beside marks,\\nattendance, and pomodoro: teacher+ (an exactly-teacher caller narrowed to the\\ncourses they manage), or a **parent linked** to the student β€” per-homework\\nrows of submitted/late/missing plus the grade; statuses and marks only,\\n**never the files**.\\n\\nEvery delete collects its garbage: withdrawing a submission, deleting a\\nhomework, and deleting the whole course each cascade the rows (submissions,\\nfiles, grades) and unlink the file blobs from disk. Role changes never sweep\\nhomework rows: a promoted student's work stays readable on the roster behind\\nthe `unenrolled` flag, while the live-role gates refuse fresh edits and\\ngrades.", "source": "README.md"}, {"id": "lesson-sessions-roll-call-the-work-log-pomodoro-attendance-reports", "title": "Lesson sessions, roll call, the work log, pomodoro & attendance reports", "body": "Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session\\nbelongs to a course and carries a `teacher` (defaults to whoever creates it;\\nany explicit `teacher_id` must hold teacher+ β€” a student cannot teach), an\\noptional `topic`, a required `starts_at`, and an optional `ends_at` (when both\\nare set, `ends_at` must not precede `starts_at`; neither may be set in the\\npast). Sessions are created, edited,\\nand deleted under course-management rights, exactly like exams; session lists\\nare ordered by `starts_at` (a timetable, not a creation log).\\n\\n**Roll call** (`/sessions/{id}/attendance`) deliberately differs from event\\nattendance: students never mark themselves. The session's teacher or a course\\nmanager marks **enrolled** students β€” only students attend classes, so a\\nnon-student or unenrolled target is a `400` β€” and the\\n**session teacher's own** presence row can only be written or removed by\\nmanager+ β€” staff presence is management's call, so a teacher can't declare\\nthemselves present. Listing the roll call follows the same rights as taking\\nit; a student reads their own tallies through the attendance report instead.\\nRe-marking overwrites: one row per session+user, by construction. Deleting a\\nsession (or its course) cascades its roll-call rows.\\n\\nThe **work log** (`/work`) is the staff timesheet, for teachers and above.\\n`POST /work/check-in` opens a stint and `POST /work/check-out` closes it, both\\nstamped by the **server clock** β€” a request never carries an instant, so a\\nwrong device clock (or a crafted request) can't forge presence. At most one\\nopen stint per user holds atomically: double check-ins and check-outs without\\nan open stint answer `409`, and a reconnecting double-click can't reset a\\nrunning clock. `GET /work/me` lists your stints newest-first (the open one has\\n`check_out: null`, closed ones a convenience `duration_ms`); manager+ reads\\nanyone's log (`GET /work/{user}`), corrects a **closed** stint's instants\\n(`PATCH /work/entries/{id}`, `409` while open β€” check out or delete instead),\\nand deletes entries.\\n\\nThe **pomodoro log** (`/pomodoro`) is the students' study-time twin of the\\nwork log. The frontend owns the timer β€” the visible countdown, the work/break\\nrhythm, the durations; the backend stores no timing policy and records only\\n**focus stints**, stamped by the server clock exactly like work stints.\\n`POST /pomodoro/start` opens a session and β€” unlike a work check-in β€” always\\nsucceeds for a student: a dangling unfinished session (a laptop closed\\nmid-timer) is **discarded and replaced**, because it recorded no focus and\\nmust not lock the student out of the next one. `POST /pomodoro/finish` closes\\nthe running session (`409` when nothing runs); breaks are never reported.\\nLogs return the usual page envelope plus `total_focus_ms`, the unpaged sum of\\nevery finished session's duration: `GET /pomodoro/me` for your own,\\n`GET /pomodoro/{user}` for teacher+ (study oversight). Only students start\\nsessions β€” pomodoro is the study tool, the work log is the staff timesheet.\\n\\n**Attendance reports** mirror the marks report: `GET /attendance/me` for any\\nlogged-in user, `GET /attendance/{user}` for teacher+ β€” narrowed to the\\ncourses the caller manages (manager+ sees every course; event tallies are\\nschool-wide either way). The report tallies event attendance and lesson roll\\ncall separately, plus a per-course breakdown:\\n\\n```json\\n{\\n \\"user\\": \\"01J…\\",\\n \\"events\\": { \\"present\\": 4, \\"absent\\": 1, \\"late\\": 0, \\"excused\\": 1, \\"total\\": 6, \\"rate\\": 0.8 },\\n \\"sessions\\": { \\"present\\": 9, \\"absent\\": 2, \\"late\\": 1, \\"excused\\": 0, \\"total\\": 12, \\"rate\\": 0.8333 },\\n \\"courses\\": [ { \\"course\\": { \\"id\\": \\"01J…\\", \\"title\\": \\"algebra\\", … }, \\"counts\\": { … } } ]\\n}\\n```\\n\\n`rate = (present + late) / (present + absent + late)`: arriving late still\\ncounts as attending, and an excused absence counts against no one (`rate` is\\n`null` when every row is excused, or there are none). Per-course blocks appear\\nfor every course the user has roll-call rows in β€” attendance is a historical\\nrecord, so unenrolling hides marks from the marks report but never hides an\\nabsence.", "source": "README.md"}, {"id": "quick-tour-curl", "title": "Quick tour (curl)", "body": "```sh\\nBASE=http://127.0.0.1:8080\\nJAR=/tmp/hz.cookies\\n\\ncurl -s $BASE/auth/register -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\ncurl -s -c $JAR $BASE/auth/login -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\n# notes\\ncurl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"first\\",\\"content\\":\\"hello\\"}'\\ncurl -s -b $JAR $BASE/notes\\n\\n# note files (multipart; -F sets filename + content type from the file)\\nNO=$(curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"with file\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nFI=$(curl -s -b $JAR $BASE/notes/$NO/files -F 'file=@plan.pdf' \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/notes/$NO/files # list metadata\\ncurl -s -b $JAR -OJ $BASE/notes/$NO/files/$FI # download, original filename\\n\\n# events + attendance\\n# Creating events needs teacher+; grant it first (see \\"Bootstrapping\\" above β€”\\n# e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403.\\nEV=$(curl -s -b $JAR $BASE/events -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"standup\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json' \\\\\\n -d '{\\"status\\":\\"present\\"}'\\ncurl -s -b $JAR $BASE/events/$EV/attendance\\n\\n# courses + weighted marks (as a teacher)\\n# optional, manager+: weigh midterms triple β€” school policy, per kind\\ncurl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \\\\\\n -d '{\\"exam_kinds\\":[{\\"name\\":\\"midterm\\",\\"weight\\":3},{\\"name\\":\\"quiz\\",\\"weight\\":1}]}'\\n# find the student to enroll (here: a registered user \\"veli\\"): fragment\\n# search over username/name, role-narrowed (teacher+)\\nSID=$(curl -s -b $JAR \\"$BASE/users/search?q=vel&role=student\\" \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nCO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"algebra\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\nEX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"midterm\\",\\"kind\\":\\"midterm\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"mark\\\\\\":90,\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\ncurl -s -b $JAR $BASE/exams/$EX/statistics\\n\\n# lesson sessions + roll call (course manager creates; the session's teacher\\n# or a course manager marks enrolled students)\\nSE=$(curl -s -b $JAR $BASE/courses/$CO/sessions -H 'content-type: application/json' \\\\\\n -d '{\\"topic\\":\\"limits\\",\\"starts_at\\":1900000000000}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/sessions/$SE/attendance -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"status\\\\\\":\\\\\\"present\\\\\\",\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\n\\n# staff work log (instants are server-stamped)\\ncurl -s -b $JAR -X POST $BASE/work/check-in\\ncurl -s -b $JAR -X POST $BASE/work/check-out\\ncurl -s -b $JAR $BASE/work/me\\n\\n# ...and as the student:\\ncurl -s -b $STUDENT_JAR $BASE/marks/me\\ncurl -s -b $STUDENT_JAR $BASE/attendance/me\\n# pomodoro: start when the timer starts, finish when it rings\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/finish\\ncurl -s -b $STUDENT_JAR $BASE/pomodoro/me\\n```", "source": "README.md"}, {"id": "ai-bridge-quic", "title": "AI bridge (QUIC)", "body": "The AI features are separate projects β€” separate repos, separate processes,\\nprobably not Rust. They talk to this backend over a QUIC bridge rather than\\nHTTP.\\n\\nWhy QUIC: stream multiplexing lives in the transport. Each request rides its\\nown **bidirectional stream** on the service's single long-lived connection, so\\nconcurrent requests need no correlation-id bookkeeping and never head-of-line\\nblock each other β€” a 30-second inference on one stream does not delay the\\nanswer on another. Connection setup (and the TLS handshake) happens once, not\\nper request.\\n\\n**The backend listens; the services dial in.** A service can therefore sit\\nbehind NAT, restart without the backend knowing its address, and scale out by\\nopening a second connection β€” each connection is an independent worker.\\n\\nOff by default: with `AI_QUIC_ADDR` unset the bridge never starts and the rest\\nof the API is unaffected.\\n\\n### Handshake\\n\\nThe service connects with ALPN `hab/1`, then opens the **control stream** (the\\nfirst client-initiated bidi stream) and writes one `Hello`:\\n\\n```json\\n{ \\"protocol\\": \\"hab/1\\", \\"service\\": \\"ocr\\", \\"capabilities\\": [\\"ocr.extract\\"],\\n \\"token\\": \\"<AI_SHARED_TOKEN>\\", \\"max_concurrent\\": 8 }\\n```\\n\\nThe backend answers one `Greeting` and leaves the stream open:\\n\\n```json\\n{ \\"type\\": \\"welcome\\", \\"worker_id\\": \\"01J...\\", \\"protocol\\": \\"hab/1\\" }\\n{ \\"type\\": \\"rejected\\", \\"code\\": \\"unauthorized\\", \\"message\\": \\"invalid token\\" }\\n```\\n\\nReject codes: `unsupported_protocol`, `unauthorized`, `no_capabilities`,\\n`malformed`. The token is compared in constant time; the handshake must\\ncomplete within 10s.\\n\\nThe control stream carries no further frames. **Its closure is the goodbye** β€”\\nthere is no heartbeat. A service that dies silently is dropped by the QUIC idle\\ntimeout (30s, with a 10s keepalive) and deregistered then.\\n\\n`max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests\\nbeyond it are refused with \\"busy\\" rather than queued.\\n\\n### Requests\\n\\nFor each request the **backend** opens a bidi stream, writes one `Request`,\\nfinishes its send side, and reads one `Response`:\\n\\n```json\\n{ \\"id\\": \\"01J...\\", \\"capability\\": \\"ocr.extract\\", \\"deadline_ms\\": 30000,\\n \\"payload\\": { \\"image\\": \\"<base64>\\" } }\\n```\\n\\n```json\\n{ \\"status\\": \\"ok\\", \\"id\\": \\"01J...\\", \\"payload\\": { \\"text\\": \\"...\\" } }\\n{ \\"status\\": \\"err\\", \\"id\\": \\"01J...\\", \\"code\\": \\"unsupported_image\\",\\n \\"message\\": \\"only png and jpeg\\" }\\n```\\n\\n`id` is a trace id for logs on both sides β€” correlation is the stream, not the\\nid. It must still be echoed: an answer carrying a different id means the\\nservice lost track of whose work it is, and the payload is refused. `payload`\\nis opaque to the transport; its shape belongs to the capability.\\n\\n`deadline_ms` is when the backend gives up. A service should abandon the work\\nrather than answer late. A handled failure is an `err` frame; a crash is just a\\ndropped stream.\\n\\n### Framing\\n\\n`u32` big-endian byte length, then that many bytes of JSON. One frame per\\nmessage. The length is validated against the 8 MiB cap **before** any buffer is\\nallocated. JSON rather than a binary codec so a service in any language can\\nspeak it in ~20 lines.\\n\\n### Routing\\n\\nRequests route by exact capability string to the **least-loaded** worker\\noffering it (ties broken by worker id). Least-inflight rather than\\nround-robin because AI request costs are wildly uneven β€” round-robin would\\npile a second long inference onto a busy worker while an idle one sits next\\nto it. Selection and the in-flight increment happen under one lock, so\\nconcurrent dispatches cannot overshoot `max_concurrent`.\\n\\nFailure modes the caller sees: `NoWorker` (nothing registered β€” retryable),\\n`Busy` (all at capacity β€” retryable), `Timeout` (may still be running on the\\nfar side, so it promises nothing), `Remote` (the service's considered no β€”\\nnot retryable), `Protocol` / `IdMismatch` (broken peer), `Transport`.\\n\\n### Conformance suite\\n\\n`tests/ai_protocol.rs` is the wire contract, enforced on every `cargo test`. It\\nspeaks `hab/1` with a client that imports none of the crate's protocol types β€”\\nframes built as byte literals, answers parsed as untyped JSON β€” so it fails on\\nexactly the changes a service in another language would notice: a renamed\\nfield, a re-tagged enum, a flipped length-prefix endianness, a newly-required\\n`Hello` field. (`tests/ai_bridge.rs` drives real QUIC clients too, but shares\\nthe Rust structs with the backend, so it cannot see those.)\\n\\nIt is also the reference implementation: its `raw` module is the whole client\\nside of the protocol in about a hundred lines β€” handshake, framing, request\\nloop β€” and is the shortest thing to port when writing a new service.\\n\\nGuarantees it pins beyond the frame shapes: unknown fields in `Hello` and in a\\nresponse are accepted (a newer service may run against an older backend);\\npayloads pass through byte-for-byte whatever their JSON shape; request ids are\\nunique; answers may come back in any order; a service that drops one request\\nstream fails only that request; a service that ignores `deadline_ms` finds its\\nstream torn down rather than delivering a late answer.\\n\\n### TLS, auth & finding the certificate\\n\\nQUIC has no plaintext mode. With `AI_TLS_CERT`/`AI_TLS_KEY` unset, a\\nself-signed certificate is generated at boot and its sha256 fingerprint logged\\nβ€” services pin that instead of installing a CA. The certificate authenticates\\n*the backend*; the shared token in `Hello` authenticates *the service*.\\n\\nSo a service does not have to be handed a file out of band, the certificate is\\npublished over HTTP:\\n\\n```\\nGET /ai/certificate # no auth; 404 when the bridge is disabled\\n{ \\"protocol\\": \\"hab/1\\",\\n \\"certificate_pem\\": \\"-----BEGIN CERTIFICATE-----\\\\n...\\",\\n \\"fingerprint_sha256\\": \\"6745e8...\\" }\\n```\\n\\nUnauthenticated on purpose: a server certificate is handed to every peer during\\nthe TLS handshake anyway, so publishing it discloses nothing. The private key\\nnever leaves the process, and the shared token β€” the thing that actually\\nauthenticates a service β€” is *not* served here.\\n\\n**A service must re-fetch this on every reconnect, not once at startup.** With\\nno PEM pair configured the bridge re-selfsigns at each boot, so a certificate\\npinned once goes stale the moment the backend restarts; a reconnect loop that\\nonly redials would then fail forever. The service startup sequence is: `GET\\n/ai/certificate` β†’ trust that PEM β†’ dial QUIC β†’ `Hello` β†’ serve; on any\\nconnection loss, start again from the fetch.\\n\\nNote what this is not: fetch-then-pin over plain HTTP is trust-on-first-use,\\nonly as trustworthy as that HTTP hop. On an untrusted network set\\n`AI_TLS_CERT`/`AI_TLS_KEY` to a real certificate and distribute it out of band\\nβ€” the endpoint then simply serves that, stable across restarts.", "source": "README.md"}, {"id": "chatbot", "title": "Chatbot", "body": "Every signed-in user β€” `parent` included β€” keeps private threads with an\\nAI service. The backend is a **relay**: it owns auth, the limits, the thread,\\nthe payload format, and the last look at the answer before anyone sees it; the\\nwords are the service's. There are deliberately **no rule, intent or\\ncanned-answer tables** β€” the thread is free-form, and a school that wants\\ndifferent behaviour changes its AI service, not this backend. A thread is\\nprivate to its owner: no teacher, no admin, nobody reads someone else's, and\\nanother user's thread is a `404`, never a `403`.\\n\\n### Sending is two-phase, and that is the point\\n\\n`POST /chatbot/threads/{id}/messages` answers `202 {message_id, status:\\n\\"pending\\"}` instead of the answer, because an inference outlives a normal\\nrequest (and the request-timeout layer that guards every handler). Before the\\nAI is even called, two rows are written: the user's turn, and an **empty\\n`pending` assistant row** β€” `message_id` is that row. That order is the whole\\ndesign: a reload, a dropped connection, a closed laptop can no longer lose an\\nanswer, because the place it will land already exists and the answering task\\noutlives the HTTP request.\\n\\nThe client then reads that row either way it likes:\\n\\n- **poll** `GET /chatbot/threads/{id}/messages/{mid}` β€” `pending` until it\\n settles, then `complete` with `content` or `failed` with `error_code`;\\n- **stream** `GET /chatbot/threads/{id}/messages/{mid}/stream` β€” the same\\n row over Server-Sent Events.\\n\\nBoth read the same row, so they can never disagree, in any state.\\n\\n### The SSE stream\\n\\n```\\nevent: delta\\ndata: {\\"text\\":\\"Newton'un ikinci yasasΔ± \\"}\\n\\nevent: delta\\ndata: {\\"text\\":\\"kuvvet ile ivme arasΔ±ndaki …\\"}\\n\\nevent: done\\ndata: {\\"message\\":{ …the message DTO… }}\\n```\\n\\nOne to eight `delta` events, then exactly one `done` carrying the finished\\nmessage; or, if the turn failed, a single `error` event\\n(`{\\"code\\":\\"timed_out\\",\\"message\\":\\"…\\"}`) and nothing else. Then the stream\\ncloses. A stream opened *after* the answer already landed still emits\\n`delta`s and a `done` β€” the replay is deliberate, so a client that connects\\nlate (or reconnects) never hangs waiting for events that already happened.\\n\\n**The deltas are sliced by the backend from the finished answer.** `hab/1` is\\nunary β€” the service returns the whole reply text, not tokens β€” so today the\\nchunking is cosmetic pacing, not real streaming. The event shape exists now so\\nthat the day a service streams, it becomes a drop-in change behind an\\nunchanged frontend.\\n\\n### The message DTO\\n\\n```json\\n{ \\"id\\": \\"01J8…\\", \\"thread_id\\": \\"01J8…\\", \\"role\\": \\"assistant\\",\\n \\"status\\": \\"complete\\", \\"content\\": \\"…\\", \\"truncated\\": false, \\"error_code\\": null,\\n \\"created_at\\": 1761820800000, \\"completed_at\\": 1761820803120 }\\n```\\n\\n`role` is `user` or `assistant`; `status` is `pending`, `complete`, or\\n`failed` (a user turn is always `complete`). `content` is empty while pending,\\n`error_code` is set only when failed, `completed_at` is `null` until the turn\\nsettles. `truncated` is `true` when `content` is only the first part of what\\nthe assistant answered β€” the rest was over `max_chatbot_message_len` and was cut;\\nit is always `false` for a user turn and for a failed one. Show it: a clipped\\nanswer that looks whole is worse than one the reader knows is clipped. The same\\nDTO is what the SSE `done` event carries, so the streaming and polling reads\\nagree about `truncated` exactly as they do about every other field.\\n\\n### Status codes\\n\\n| code | when |\\n| --- | --- |\\n| `202` | the turn was accepted; the answer is on its way |\\n| `400` | empty message, or longer than the school's `max_chatbot_message_len` |\\n| `404` | no such thread or message β€” or not the caller's |\\n| `409` | already at `max_chatbot_threads`; delete a thread first |\\n| `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |\\n| `503` | no connected service offers `chat.reply` β€” **nothing was written**, retry later |\\n\\nThe `503` ordering matters: availability is checked before the rows exist, so\\nan unavailable service leaves no dead `pending` row behind, and the rate limit\\nis charged before that, so a refused turn leaves no trace at all. The check is\\nthe backend's own worker registry, which owns the QUIC sockets and is therefore\\nthe whole truth about what can be answered.\\n\\n### A turn always settles\\n\\nOnce the two rows exist the answer never stays `pending` forever, through\\nthree independent mechanisms:\\n\\n- the task that owns the bridge round trip stamps `complete` or `failed` β€”\\n the normal path;\\n- a reader **projects** a `pending` row older than 300 seconds as\\n `failed`/`timed_out` (a read-time projection, not a write β€” the row is left\\n for the task that may still own it);\\n- a **boot sweep** flips every leftover `pending` past the 300-second horizon\\n to `failed`/`interrupted`, which is what a process death mid-inference looks\\n like. Younger rows are left alone, since one may still be in flight.\\n\\nA restart therefore loses a turn that was in flight: it settles\\n`failed`/`interrupted` rather than being answered. Accepted β€” the backend is a\\nsingle process with stop-the-world deploys, so there is no peer that could have\\ntaken it over.\\n\\nTwo more verdicts come from inspecting the answer: an **empty** reply is\\nreported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a\\nbug), and an **over-long** one is truncated to `max_chatbot_message_len` β€” a\\nclipped answer still helps, a discarded one does not β€” with `truncated: true`\\non the stored turn, so the clip is never passed off as the whole answer.\\n\\n`error_code` values a client may see: `unavailable` (no worker, or the bridge\\nis off), `busy`, `timed_out`, `transport`, `protocol`, `bad_reply` (the\\nservice's payload did not parse), `empty_reply`, `service_error`,\\n`interrupted`, `not_found`, `internal` β€” **or a code the AI service itself\\nreturned**, verbatim. Treat it as an open set: branch on the ones you handle,\\nfall back to the human-readable text for the rest.\\n\\n### The `chat.reply` capability (for AI-service authors)\\n\\nA chat service declares `chat.reply` in its `Hello` (see \\"AI bridge (QUIC)\\").\\nRequests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:\\n\\n```json\\n{ \\"message\\": \\"and the second law?\\",\\n \\"history\\": [ {\\"role\\":\\"user\\",\\"content\\":\\"what is the first law?\\"},\\n {\\"role\\":\\"assistant\\",\\"content\\":\\"an object at rest …\\"} ] }\\n```\\n\\n`history` is **oldest first** (index 0 is furthest back), optional (absent or\\n`[]` = a fresh thread), and **excludes** the new message β€” that one is\\n`message`. It carries the last `chatbot_history_turns` **settled messages** β€”\\nentries, not exchanges: the default `10` is five question/answer pairs, and\\n`history` is exactly that many entries long whenever the thread holds enough\\nof them. Only settled turns count: a failed answer is skipped and the window\\nreaches further back for a usable one, rather than coming up short. All of it\\nis re-sent on every request, which is why the service may be stateless: it can\\nrestart, scale out, or be replaced mid-thread without losing context.\\n\\nThe answer is a `Response::Ok` whose payload is:\\n\\n```json\\n{ \\"text\\": \\"the complete reply, not chunked, not partial\\" }\\n```\\n\\nFailures reuse the existing `Response::Err {code, message}` β€” one failure\\nshape on the bridge for every capability β€” and that `code` reaches the client\\nas the message's `error_code`.\\n\\n**Unknown extra keys are ignored on both sides, on purpose.** A service may\\nadd fields (a model name, token counts) and a future backend may send more\\ncontext without either end having to be redeployed in lockstep.", "source": "README.md"}, {"id": "collaborative-whiteboard", "title": "Collaborative whiteboard", "body": "A board is a shared canvas whose membership is an **ad-hoc invite list**: the\\ncreator names participant user ids at `POST /boards` and that is the whole\\nmodel β€” no course, no lesson session, no appointment. Any account from\\n`student` upwards may open one. **Every participant draws; the creator\\nalone clears, locks, closes or deletes.**\\n\\n**No parents, anywhere.** The `parent` role is the school's read-only observer,\\nand it has no whiteboard access at all β€” not a view-only tier, none. It is\\nrefused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named*\\nin an invite list either: `resolve_participants` rejects a parent id with a\\n`400`, so a parent is never on a roster in the first place. That one cut is\\nwhat closes the rest β€” never on a roster means the id-scoped routes and the\\nroom's door already answer the outsider's `404` (never a `403`, which would\\nconfirm the board is there), and no socket opens, so no `stroke` frame can be\\nsent. The role bar is re-checked on the read path and at the door as well, so a\\nboard row written before this rule that still lists a parent is inert: that\\nparent sees a `404` for it like any stranger.\\n\\n**Two doors, two statuses.** A caller who is not on a board gets a `404` on\\nevery route, its existence included β€” an outsider must never learn a board is\\nthere. A participant who is not the creator has already been told it exists, so\\nthe four creator-only commands answer them a `403`: hiding it at that point\\nwould be a lie their client cannot act on. Over the socket the same refusal is\\n`error{code:\\"forbidden\\"}` and the socket **stays open** β€” someone clicking a\\nbutton they don't own must not lose the canvas they were drawing on.\\n\\n**A clear deletes nothing.** Strokes are append-only. `POST /boards/{id}/clear`\\nbumps the board's `epoch` and appends a `clear` **marker** carrying the epoch\\nit closed, that epoch's final stroke count, who cleared and when β€” so the live\\ncanvas empties while every mark ever drawn stays stored and replayable. Those\\nmarkers *are* the epoch index, which is why there is no epochs table and why\\nthe open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.\\n`DELETE /boards/{id}` is the one operation here that really destroys marks.\\n\\n**Three caps, and only one of them is terminal** (all three published at `GET\\n/limits` under `board`):\\n\\n- `max_epoch_strokes` bounds the **live** canvas β€” `epoch_stroke_count`, which\\n every clear resets. Hitting it is **recoverable**: the creator clears, the\\n history is kept, drawing resumes.\\n- `max_board_strokes` bounds the board's **lifetime** storage β€”\\n `total_stroke_count`, which never resets, because a clear keeps its history.\\n Hitting it stamps `closed_at` and the board becomes **permanently\\n read-only**: still fully readable and replayable, never deleted, and there is\\n no reopen β€” open a new board. `POST /boards/{id}/close` is the manual form of\\n the same thing, and idempotent.\\n- `max_boards_per_creator` bounds how many boards one creator holds\\n (`board_count` on the user row). Deleting a board frees a seat; closing one\\n does not β€” a closed board is still stored.\\n\\n**Two ways to read the marks, and the difference matters most to a client\\nauthor.** A socket `join` replays the **current epoch only**; history never\\nrides the socket. History is an explicit paged REST read:\\n`GET /boards/{id}/history` (the board's whole life, oldest first, `clear`\\nmarkers included, `?epoch=` for a single one) and `GET /boards/{id}/epochs`\\n(the marker index β€” enough to offer \\"replay session 3\\" without scanning the\\nlog). `GET /boards/{id}/strokes` is the current epoch over REST, the catch-up\\nand fallback path for the same canvas the socket replays β€” with one deliberate\\ndifference: the REST read is *not* filtered by kind, while the socket serves\\n`kind: \\"stroke\\"` rows only. In the steady state that is a distinction without a\\ndifference, since a marker is written with the epoch it *closed* and the open\\nepoch has none; the case where it shows is a clear landing between the board\\nread and the row read, which surfaces that epoch's closing marker in the page.\\nFor a live canvas the socket is the authority.\\n\\n**The board room (WebSocket)** β€” `GET /boards/{id}/ws`, cookie-authed like\\neverything else and, like the exam room, outside the OpenAPI spec (an upgrade\\nis not describable there); REST remains the full fallback. The gate before the\\nupgrade is the same `404` door: not a participant, no room. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| client β†’ | `{\\"type\\":\\"join\\", \\"after\\":\\"<last stroke id>\\", \\"epoch\\":3}` β€” both optional; replay the current epoch |\\n| server β†’ | `{\\"type\\":\\"state\\", board, epoch, locked, closed_at, creator, participants, now}` on connect and every `ws_tick_secs` |\\n| server β†’ | `{\\"type\\":\\"strokes\\", epoch, strokes:[{id, author, payload}]}` β€” one replay chunk, repeated until the epoch is served |\\n| server β†’ | `{\\"type\\":\\"synced\\", epoch, cursor}` β€” the replay is complete; `cursor` is what to resume from |\\n| client β†’ | `{\\"type\\":\\"stroke\\", \\"payload\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` β€” any participant |\\n| server β†’ | `{\\"type\\":\\"saved\\", id, client_seq?}` β€” your stroke landed |\\n| server β†’ | `{\\"type\\":\\"stroke\\", id, author, payload, epoch}` β€” someone *else* drew |\\n| client β†’ | `{\\"type\\":\\"clear\\"}` / `{\\"type\\":\\"lock\\", \\"locked\\":true}` β€” **creator only** |\\n| server β†’ | `{\\"type\\":\\"cleared\\", …}` / `{\\"type\\":\\"locked\\", locked, by}` β€” the canvas was emptied / drawing was paused |\\n| server β†’ | `{\\"type\\":\\"closed\\", …}` / `{\\"type\\":\\"deleted\\"}` β€” the board is finished; both end the room |\\n| server β†’ | `{\\"type\\":\\"participants\\", creator, participants}` β€” the roster changed; a socket no longer on it is dropped |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", code, message, client_seq?}` |\\n\\nA `stroke` may carry a `client_seq` exactly as an exam-room `answer` does: any\\nvalue the client picks, echoed **verbatim** on that message's `saved` or\\n`error` and on nothing else, omitted entirely when the request omitted it. The\\nserver never reads it.\\n\\n`error` codes are a closed set: `epoch_full` (the live canvas is full β€” clear\\nit and keep drawing), `board_closed` (permanently read-only), `locked`,\\n`forbidden` (a creator-only command from a participant), `resync` (below),\\n`invalid` (bad JSON, an unknown frame, an over-long payload), `not_found`,\\n`unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\n**Persist, then publish.** A stroke is fanned out only after its row has\\nlanded, so the channel can never carry a mark the database refused (a locked\\nboard, a full epoch, a closed board). The database is the canvas; the channel\\nis a notification *about* it β€” which is why a client dedupes by stroke `id`,\\nwhy a resync deliberately re-serves marks it already drew, and why a frame is\\nnever the authority: every stroke, clear and lock re-reads the board and\\nre-checks the roster, so a socket that missed a `participants` or `locked`\\nframe is refused all the same. One consequence of the same read-then-write\\nshape: a stroke carries the epoch the server read for it, so a clear landing in\\nthat instant can file one stroke under the epoch it just closed β€” the stroke is\\nkept and stays replayable in `/history`, it simply is not on the new canvas.\\n\\n**Reconnecting.** `join` carries a cursor: `after`, the last stroke id already\\ndrawn, plus the `epoch` it belongs to. Same epoch and only what is newer is\\nreplayed; an older epoch β€” or no cursor at all β€” gets a `cleared` frame first\\nand then the whole current epoch, because a cursor into a closed epoch no\\nlonger means anything. If the room falls behind a slow socket the server sends\\n`error{code:\\"resync\\"}` and immediately replays the current epoch **out of the\\ndatabase**: the client does not re-join, it throws its canvas away and takes\\nwhat follows. The database is always the source of truth, never the channel.\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/boards/${id}/ws`);\\nlet epoch = null, cursor = null, seq = 0;\\nws.onopen = () => ws.send(JSON.stringify({ type: \\"join\\", after: cursor, epoch }));\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"cleared\\") wipeCanvas();\\n if (m.type === \\"strokes\\") m.strokes.forEach(draw); // dedupe by m.id\\n if (m.type === \\"synced\\") ({ epoch, cursor } = m);\\n if (m.type === \\"stroke\\") draw(m);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.id);\\n if (m.type === \\"error\\" && m.code === \\"resync\\") wipeCanvas();\\n};\\nconst send = (payload) =>\\n ws.send(JSON.stringify({ type: \\"stroke\\", payload, client_seq: ++seq }));\\n```", "source": "README.md"}, {"id": "concurrency-model", "title": "Concurrency model", "body": "The backend runs as **one process against one database**, and that buys less\\nthan it sounds like: every request is an async task, dozens are in flight at\\nonce, and each of them awaits the database in the middle of its work. So\\n\\"read, decide, write\\" is never safe on its own β€” SurrealDB does not\\nconflict-check a cross-record `count()` against a concurrent insert\\n(write-skew), and that fires between two tasks in one process exactly as it\\nwould between two machines. The mutex-only design this replaced was already\\nlosing races at one process. Every invariant is therefore guarded where the\\ndatabase itself decides the winner. Three tiers:\\n\\n1. **Single-row conditional writes** β€” compare-and-set (`save_if_unchanged`),\\n `UPDATE … WHERE`, stored counters (`domain::cap`). A single-record write is\\n atomic, so of N concurrent tasks exactly the allowed number get a non-empty\\n result: the database decides the winner, the loser retries\\n (`CAS_UPDATE_RETRIES`) or gets a 409.\\n2. **In-transaction `IF … THROW` gates** β€” the check runs inside the same\\n statement as the write it authorizes, so it is atomic with it. Used where\\n the rule reads the row being written (state machines, delete guards).\\n \\"Is anything still attached?\\" is answered the same way, by a counter on the\\n row being deleted rather than a `SELECT` over the children: a course is\\n deletable while its `enrollment_count` is zero, a term while its\\n `course_count` is (courses claim that reference *before* they write the\\n link, and give it back when the link moves or the course is deleted). A fee\\n plan reads the same way β€” editable *and* deletable while its\\n `assignment_count` is zero, and frozen for good once it is not, since an\\n assignment is never taken back.\\n Where the child also carries a deterministic id β€” one enrollment per\\n (course, user), one registration per (event, user), one fee-plan assignment\\n per (plan, student) β€” the seat and the row\\n are claimed in one transaction (`cap::claim_and_create`), so a duplicate\\n `CREATE` rolls its own seat back instead of costing a stranger their place.\\n3. **Two accepted races**, reviewed and deliberately left open:\\n - *Attempt-seq late save* β€” an exam-room socket writes into the sitting it\\n joined with, a choice made before any lock is taken, so a save racing a\\n retake can stamp an answer onto the just-terminal previous sitting.\\n Damage: one history row; the grade of record (latest `seq`) is never\\n touched.\\n - *Approved-overlap* β€” two approvals landing in the same instant can\\n double-book a teacher. Damage: one overlapping half-hour, visible to both\\n parties, fixable by cancelling either side.\\n\\nIn-process locks remain, and they are a *second* line, never the guarantee:\\n`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional\\n-write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is\\nthe cap β€” the lock only tames the retry loop, and keeps the tests' in-memory\\nengine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in\\nfront of a rule no single-record write can express. Removing one of them costs\\nthroughput or an accepted race; removing the conditional write behind it costs\\nthe invariant.\\n\\nBoot is unconditional: the schema batches, the backfills and the admin seed all\\nrun on every start, because exactly one process ever starts. Deployment is\\nstop-the-world β€” `podman compose down` then `up`, never overlapping β€” and a\\nrelease that adds or renames a stored counter *requires* it. An old binary\\nwrites rows without touching the new counter, the `= NONE` backfill guard\\n(correctly) refuses to re-seed, and the resulting permanent under-count lets a\\nguard approve exactly what it exists to refuse. In-flight work does not survive\\na restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.", "source": "README.md"}, {"id": "layout", "title": "Layout", "body": "```\\nsrc/\\n main.rs bootstrap: config, db, router, serve\\n lib.rs build_router: routes + OpenAPI/Swagger + CORS + /health\\n config.rs env-sourced Config\\n constant.rs validation limits\\n validate.rs field validators (used by every newtype's try_new)\\n error.rs ValidationError + AppError -> HTTP responses\\n database.rs SurrealDB server connect (ws) + SCHEMAFULL migration\\n migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,\\n MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them\\n rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier\\n state.rs AppState { db, files_path, cookie_secure, rate_limit,\\n chatbot_limit, exam_presence, board_hub, db_up, ai }\\n ai/ QUIC bridge to the out-of-process AI services\\n (see \\"AI bridge (QUIC)\\"; the HTTP half is web/ai.rs)\\n protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing\\n server.rs AiBridge: listener, handshake, dispatch over per-request streams\\n registry.rs connected workers, capability routing, least-inflight leases\\n tls.rs listener certificate (PEM or self-signed) + fingerprint\\n error.rs AiError\\n chat.rs the `chat.reply` payload contract (ChatRequestPayload/ChatReplyPayload)\\n domain/ validated newtypes + entities (derive SurrealValue),\\n each owning its persistence\\n user.rs UserId Β· Username Β· Password Β· PasswordHash Β· User (has role)\\n role.rs Role enum (student < teacher < manager < admin), at_least()\\n field_update.rs FieldUpdate: one UPDATE ... SET built from only the fields a\\n PATCH actually carried (an omitted field is never written)\\n monotonic_id.rs next_ulid: ids that sort in write order β€” one process-wide\\n Generator, so same-millisecond rows never scramble\\n key.rs sitting(): the deterministic per-sitting record key shared by\\n attempts, answers, answer images and results (seq 1 stays bare)\\n cap.rs claim()/release(): the count caps the database enforces β€” an\\n atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter\\n column of the parent row, replacing count-then-write mutexes\\n that could not see a concurrent insert;\\n claim_and_create() commits that seat and the child row in\\n one transaction, for children with a deterministic id\\n text_fold.rs case- and diacritic-insensitive folding for search, shared by\\n the Rust needle and the SurrealQL column (Turkish Δ°/Δ±, ΓΌ, â…)\\n session.rs SessionId Β· SessionToken Β· Session (7-day expiry)\\n timestamp.rs Timestamp (unix-millisecond instant)\\n note.rs NoteId Β· NoteTitle Β· NoteContent Β· Note\\n note_file.rs NoteFileId Β· FileName Β· FileContentType Β· NoteFile (metadata row;\\n blob on disk under FILES_PATH, named by the row's ULID)\\n event.rs EventId Β· EventTitle Β· EventDescription Β· Event\\n attendance.rs AttendanceId Β· AttendanceStatus Β· Attendance\\n course.rs CourseId Β· CourseTitle Β· CourseDescription Β· Course\\n course_session.rs CourseSessionId Β· SessionTopic Β· CourseSession (a course's lesson)\\n session_attendance.rs SessionAttendanceId Β· SessionAttendance (roll call; one row per session+user)\\n work_entry.rs WorkEntryId Β· WorkEntry (staff stint; one open per user by construction)\\n enrollment.rs EnrollmentId Β· Enrollment (one row per course+user)\\n exam.rs ExamId Β· ExamTitle Β· ExamDescription Β· ExamKind Β· ExamWeight Β·\\n ExamMode Β· ExamDuration Β· ExamSchedule Β· Exam (belongs to a course)\\n exam_attempt.rs ExamAttemptId Β· AttemptStatus Β· ExamAttempt (numbered sittings per exam+user, metered by max_attempts)\\n exam_question.rs ExamQuestionId Β· QuestionText Β· QuestionKind Β· QuestionPoints Β·\\n ChoiceText Β· QuestionSpec Β· ExamQuestion (choice|text, per exam)\\n exam_answer.rs ExamAnswerId Β· AnswerText Β· ExamAnswer (one row per question+user) Β·\\n auto_score (choice-question suggestion)\\n exam_result.rs ExamResultId Β· Mark Β· ExamResult (one row per exam+user)\\n question_image.rs QuestionImageId Β· QuestionImage (question/choice picture\\n metadata; bytes on disk under FILES_PATH)\\n answer_image.rs AnswerImageId Β· AnswerImage (student answer-drawing\\n metadata; bytes on disk under FILES_PATH)\\n bank_question.rs BankQuestionId Β· BankQuestion (school-wide reusable\\n question template, copied into exams; no exam FK)\\n bank_question_image.rs BankQuestionImageId Β· BankQuestionImage (bank\\n question/choice picture metadata; bytes on disk under FILES_PATH)\\n profile.rs PersonName Β· Email Β· Phone Β· BirthDate (personal-info newtypes)\\n preferences.rs Theme Β· Language Β· PaletteColor (own UI preferences)\\n message.rs MessageId Β· MessageSubject Β· MessageBody Β· MessageLabel Β·\\n Message (per-copy folders: inbox/sent/archive/trash)\\n parent_link.rs ParentLinkId Β· ParentLink (parent↔student tie = the parent's read grant)\\n registration.rs RegistrationId Β· Registration (a seat on a registration event's signup list)\\n subject.rs SubjectId Β· SubjectName Β· SubjectDescription Β· Subject (course curriculum)\\n term.rs TermId Β· TermName Β· Term (school term window)\\n menu.rs MenuId Β· MenuDate Β· MenuSlot Β· Menu (one published menu per\\n calendar day + meal slot; slot snapshotted as text)\\n menu_dish.rs MenuDishId Β· DishName Β· DishDescription Β· DishPrice Β·\\n DishTags Β· MenuDish (a dish on a menu; price in minor units)\\n dietary_profile.rs DietaryProfileId Β· DietaryTags Β· DietaryNote Β·\\n DietaryProfile (what one student may not eat; keyed by the\\n student, tagged from the same `dietary_tags` list a dish is)\\n meal_booking.rs MealBookingId Β· MealBookingStatus Β· MealBooking (one seat\\n per (menu, student); a cancel flips the status, never deletes)\\n meal_attendance.rs MealAttendanceId Β· MealAttendanceStatus Β· MealAttendance\\n (who actually ate; one row per (menu, student), reporting\\n only β€” it never touches the ledger)\\n meal_ledger.rs MealLedgerId Β· MealLedgerKind Β· LedgerAmount Β· LedgerMethod Β·\\n LedgerNote Β· MealLedger (append-only money; the balance is\\n always the fold, never a stored field)\\n fee_plan.rs FeePlanId Β· FeePlanName Β· Installment Β· FeePlan (a school fee\\n plan; installments embedded on the row, past due dates legal)\\n fee_plan_assignment.rs FeePlanAssignmentId Β· FeePlanAssignment (one plan on\\n one student, keyed `<plan>_<student>`; assigning appends\\n every installment charge, a replay appends nothing)\\n payment_ledger.rs PaymentLedgerId Β· PaymentLedgerKind Β· PaymentLedger\\n (append-only school fees: charge/credit/reversal/refund, a\\n credit names its charge and a refund its credit; the balance\\n is always the fold; over-payment cap is advisory)\\n settings.rs ExamKindDef Β· GradeBand Β· Settings (per-school policy)\\n chatbot_thread.rs ChatbotThreadId Β· ChatbotThreadTitle Β· ChatbotThread (one\\n chatbot thread, private to its owner)\\n chatbot_message.rs ChatbotMessageId Β· ChatContent Β· MessageRole Β· MessageStatus Β·\\n ChatbotMessage (one turn; the assistant row is written\\n `pending` before the AI call and settled after)\\n board.rs BoardId Β· BoardTitle Β· Board (a collaborative whiteboard:\\n creator + ad-hoc participant list, `epoch`, the two stroke\\n counters and `closed_at`)\\n board_stroke.rs BoardStrokeId Β· BoardStroke (the\\n append-only stroke log; a `clear` row is the marker that\\n closed an epoch, carrying its final count β€” nothing is\\n ever deleted)\\n appointment_slot.rs AppointmentSlotId Β· SlotSeries Β· SlotNote Β·\\n AppointmentSlot (a teacher's published availability; a\\n recurring publish is expanded into rows sharing a series id)\\n appointment.rs AppointmentId Β· AppointmentStatus Β· AppointmentReason Β·\\n Appointment (a booking on a slot; occupancy is the slot's\\n stored `occupied` cap-1 counter, overlap is derived under\\n APPOINTMENT_LOCK)\\n pomodoro.rs PomodoroSessionId Β· PomodoroSession (student focus log)\\n pool_question.rs PoolQuestionId Β· PoolQuestionTitle Β· PoolQuestionBody Β·\\n PoolQuestion (student-asked question; teacher-approved into\\n the school-wide pool; optional photo as metadata + disk blob)\\n solution.rs SolutionId Β· SolutionBody Β· Solution (discussion thread on an\\n approved pool question; dies with the question)\\n homework.rs HomeworkId Β· HomeworkTitle Β· HomeworkDescription Β· Homework\\n (per-course assignment; required subject; optional `assigned`\\n student subset β€” absent/empty = the whole enrolled course)\\n homework_submission.rs HomeworkSubmissionId Β· SubmissionText Β·\\n HomeworkSubmission (one row per homework+user; immutable\\n submitted_at + moving updated_at β€” `late` is computed)\\n homework_file.rs HomeworkFileId Β· HomeworkFile (submission attachment\\n metadata; any content type; bytes on disk under FILES_PATH)\\n homework_result.rs HomeworkResultId Β· HomeworkStatus Β· HomeworkResult\\n (teacher grade: done/incomplete/missing + optional Mark; one\\n row per homework+user β€” its existence freezes the submission)\\n web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +\\n auth extractors\\n extractor.rs CurrentUser Β· RequireTeacher Β· RequireManager Β· RequireAdmin\\n dto.rs shared UserResponse Β· CourseResponse Β· ExamResponse Β· SessionResponse schemas\\n exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)\\n board_ws.rs the collaborative board room WebSocket (join replay, strokes\\n fanned out to every participant, clear/lock)\\n room.rs the plumbing both rooms share: sending a frame, classifying\\n an incoming message, an AppError as a readable code, and a\\n client_seq echoed untouched\\n page.rs PageParams Β· Page<T> (shared pagination)\\n etag.rs conditional-GET middleware: ETag over a 200 JSON body,\\n If-None-Match β†’ 304 (GET only; SSE and blobs pass through)\\n auth.rs users.rs notes.rs messages.rs events.rs appointments.rs\\n courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs\\n bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs\\n settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs\\n boards.rs\\n limits.rs GET /limits: every constant.rs bound served as JSON\\n```\\n\\nTests: `cargo test` β€” unit (in-source), integration (`tower::oneshot` + in-memory\\ndb), rate-limit (both tiers, proxy-header and peer-address keying, shipped\\nlimits over every route, two limiters sharing one budget over one db), e2e\\n(real TCP + reqwest cookie jar), persistence\\n(tempfile file engine, including close + reopen), ai-bridge (real QUIC on\\nloopback against a fake AI service), ai-protocol (the `hab/1` wire contract,\\ndriven by a client that shares no code with the backend).", "source": "README.md"}];
49+INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "16d576ae0877dbc7b21a88f129316c5b7eb833c95a064763ad4d7557b1dab3f2"}];
50+DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii;
51+DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25;
52+DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25;
53+REMOVE TABLE IF EXISTS endpoint;
54+INSERT INTO endpoint [{"id": "health", "routes": "| GET | `/health` | no | Liveness check |"}, {"id": "root", "routes": "| GET | `/` | no | Same as `/health` |"}, {"id": "time", "routes": "| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |"}, {"id": "limits", "routes": "| GET | `/limits` | no | Every fixed validation bound, grouped by resource \\u2014 see Validation limits |"}, {"id": "swagger", "routes": "| GET | `/swagger` | no | Interactive API docs (Swagger UI) |"}, {"id": "api-docs", "routes": "| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |"}, {"id": "ai", "routes": "| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |"}, {"id": "auth", "routes": "| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken \\u2014 see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |"}, {"id": "users", "routes": "| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` \\u2014 own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) \\u00b7 paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` \\u2014 find users by username/name fragment (pickers); refs only, no contact info \\u00b7 paged |\\n| GET | `/users` | admin | List all users \\u00b7 paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` \\u2014 set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` \\u2014 tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students \\u00b7 paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |"}, {"id": "notes", "routes": "| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes \\u00b7 paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) \\u2014 \\u2264 the school's `max_file_bytes`, \\u2264 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) \\u00b7 paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |"}, {"id": "messages", "routes": "| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` \\u2014 send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` \\u2014 the caller's folder, newest first; `?folder=inbox&read=false&limit=1` \\u2192 `total` is the unread badge \\u00b7 paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` \\u2014 read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** \\u2014 only from the trash (`409` elsewhere); the row vanishes once both sides deleted |"}, {"id": "events", "routes": "| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` \\u2014 `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` \\u2014 mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) \\u00b7 paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` \\u00b7 paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` \\u2014 seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |"}, {"id": "appointments", "routes": "| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` \\u2014 publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, \\u2264 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) \\u2014 a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar \\u2014 future slots only, demoted teachers' slots left out \\u00b7 paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` \\u2014 book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests \\u00b7 paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` \\u2014 call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included \\u2014 they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` \\u2014 counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal \\u2014 this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |"}, {"id": "courses", "routes": "| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` \\u2014 `kind` is `course` (default), `study` (et\\u00fct), or `club` (kul\\u00fcp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) \\u00b7 paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses \\u00b7 paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ \\u2014 **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` \\u2014 assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` \\u2014 enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u00b7 paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` \\u2014 add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` \\u2014 add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` \\u2014 add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) \\u00b7 paged |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` \\u2014 assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, \\u2264 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) \\u00b7 paged |"}, {"id": "subjects", "routes": "| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |"}, {"id": "sessions", "routes": "| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` \\u2014 roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) \\u00b7 paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |"}, {"id": "exams", "routes": "| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist \\u2014 the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` \\u2014 grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) \\u00b7 paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt \\u2014 students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) \\u00b7 paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question \\u2014 the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam \\u2014 copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** \\u2014 copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question \\u2014 text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` \\u2014 autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers \\u22c3 marks), ascending \\u2014 the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first \\u2014 the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** \\u2014 the answer key the caller checks their own sheet against (same review gate) \\u00b7 paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers \\u22c3 marks), ascending \\u2014 only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster \\u00d7 latest attempts \\u00d7 marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |"}, {"id": "bank-questions", "routes": "| GET | `/bank-questions` | teacher | The school-wide question bank \\u2014 `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) \\u00b7 paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist \\u2014 `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question \\u2014 the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |"}, {"id": "homework", "routes": "| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) \\u00b7 paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade \\u2014 the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades \\u2014 file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` \\u2014 hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part \\u2014 **any** content type, \\u2264 `max_file_bytes`, \\u2264 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) \\u2014 the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student \\u00d7 submission/files/grade + computed `late`/`missing`/`unenrolled` \\u2014 a straggler's stale work stays visible (course manager) \\u00b7 paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` \\u2014 grade `done`/`incomplete`/`missing` (+ optional 0\\u2013100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable \\u2014 that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) \\u2014 readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade \\u2014 un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows \\u2014 submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` \\u2014 full, statuses and marks only, never files \\u00b7 paged |"}, {"id": "questions", "routes": "| POST | `/questions` | student | `{title, body}` \\u2014 ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` \\u2014 the pool questions visible to the caller, each with its `solution_count` \\u00b7 paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question \\u2014 publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` \\u2014 offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first \\u2014 a discussion thread \\u00b7 paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` \\u2014 edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |"}, {"id": "marks", "routes": "| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "work", "routes": "| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) \\u00b7 paged |\\n| GET | `/work/{user}` | manager | A staff member's work log \\u00b7 paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` \\u2014 correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |"}, {"id": "pomodoro", "routes": "| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** \\u2014 a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` \\u00b7 paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape \\u00b7 paged; *or a `parent` linked to `{user}` |"}, {"id": "attendance", "routes": "| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "settings", "routes": "| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |"}, {"id": "terms", "routes": "| POST | `/terms` | manager | `{name, starts_at, ends_at}` \\u2014 past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first \\u00b7 paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term \\u2014 `409` while any course still links to it |"}, {"id": "meals", "routes": "| POST | `/meals/menus` | manager | `{date, slot, capacity?}` \\u2014 publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range \\u00b7 paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` \\u2014 the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` \\u2014 add a dish (\\u2264 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` \\u2014 record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` \\u2014 take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first \\u00b7 paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included \\u00b7 paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` \\u2014 mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu \\u00b7 paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day \\u00b7 paged \\u00b7 own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line |"}, {"id": "payments", "routes": "| POST | `/payments/plans` | manager | `{name, installments}` \\u2014 write a fee plan (1\\u201360 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first \\u00b7 paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it \\u2014 its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (\\u2264 200) \\u2014 place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first \\u00b7 paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` \\u2014 record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` \\u2014 hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` \\u2014 undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines \\u2014 charges, payments, refunds, reversals \\u2014 newest first \\u00b7 paged \\u00b7 own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |"}, {"id": "chatbot", "routes": "| POST | `/chatbot/threads` | student | `{title?}` \\u2014 start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first \\u00b7 paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` \\u2014 rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first \\u2014 user and assistant rows alike \\u00b7 paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (\\u2264 `max_chatbot_message_len`) \\u2014 send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` \\u2014 nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` \\u2014 or one `error` \\u2014 and close; an already-finished answer replays (see \\"Chatbot\\") |"}, {"id": "boards", "routes": "| POST | `/boards` | student | `{title, participant_ids?}` \\u2014 open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first \\u00b7 paged |\\n| GET | `/boards/{id}` | student | One board \\u2014 a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first \\u00b7 paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included \\u00b7 `?epoch=` for one epoch \\u00b7 paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) \\u00b7 paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` \\u2014 re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap \\u2014 nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board \\u2014 permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |"}];
55+SELECT sha256 FROM meta:readme;
56+SELECT VALUE count() FROM user GROUP ALL;
57+INFO FOR DB;
58+SELECT * FROM user;
59+SELECT VALUE count() FROM answer_image GROUP ALL;;SELECT VALUE count() FROM appointment GROUP ALL;;SELECT VALUE count() FROM appointment_slot GROUP ALL;;SELECT VALUE count() FROM attendance GROUP ALL;;SELECT VALUE count() FROM bank_question GROUP ALL;;SELECT VALUE count() FROM bank_question_image GROUP ALL;;SELECT VALUE count() FROM chatbot_message GROUP ALL;;SELECT VALUE count() FROM chatbot_thread GROUP ALL;;SELECT VALUE count() FROM course GROUP ALL;;SELECT VALUE count() FROM course_session GROUP ALL;;SELECT VALUE count() FROM dietary_profile GROUP ALL;;SELECT VALUE count() FROM enrollment GROUP ALL;;SELECT VALUE count() FROM event GROUP ALL;;SELECT VALUE count() FROM exam GROUP ALL;;SELECT VALUE count() FROM exam_answer GROUP ALL;;SELECT VALUE count() FROM exam_attempt GROUP ALL;;SELECT VALUE count() FROM exam_question GROUP ALL;;SELECT VALUE count() FROM exam_result GROUP ALL;;SELECT VALUE count() FROM fee_plan GROUP ALL;;SELECT VALUE count() FROM fee_plan_assignment GROUP ALL;;SELECT VALUE count() FROM homework GROUP ALL;;SELECT VALUE count() FROM homework_file GROUP ALL;;SELECT VALUE count() FROM homework_result GROUP ALL;;SELECT VALUE count() FROM homework_submission GROUP ALL;;SELECT VALUE count() FROM kind_ref GROUP ALL;;SELECT VALUE count() FROM meal_attendance GROUP ALL;;SELECT VALUE count() FROM meal_booking GROUP ALL;;SELECT VALUE count() FROM meal_ledger GROUP ALL;;SELECT VALUE count() FROM menu GROUP ALL;;SELECT VALUE count() FROM menu_dish GROUP ALL;;SELECT VALUE count() FROM message GROUP ALL;;SELECT VALUE count() FROM note GROUP ALL;;SELECT VALUE count() FROM note_file GROUP ALL;;SELECT VALUE count() FROM parent_link GROUP ALL;;SELECT VALUE count() FROM payment_ledger GROUP ALL;;SELECT VALUE count() FROM pomodoro_session GROUP ALL;;SELECT VALUE count() FROM pool_question GROUP ALL;;SELECT VALUE count() FROM question_image GROUP ALL;;SELECT VALUE count() FROM rate_limit GROUP ALL;;SELECT VALUE count() FROM registration GROUP ALL;;SELECT VALUE count() FROM session GROUP ALL;;SELECT VALUE count() FROM session_attendance GROUP ALL;;SELECT VALUE count() FROM settings GROUP ALL;;SELECT VALUE count() FROM slot_ref GROUP ALL;;SELECT VALUE count() FROM solution GROUP ALL;;SELECT VALUE count() FROM subject GROUP ALL;;SELECT VALUE count() FROM term GROUP ALL;;SELECT VALUE count() FROM user GROUP ALL;;SELECT VALUE count() FROM work_entry GROUP ALL;
60+INFO FOR TABLE answer_image;;INFO FOR TABLE appointment;;INFO FOR TABLE appointment_slot;;INFO FOR TABLE attendance;;INFO FOR TABLE bank_question;;INFO FOR TABLE bank_question_image;;INFO FOR TABLE chatbot_message;;INFO FOR TABLE chatbot_thread;;INFO FOR TABLE course;;INFO FOR TABLE course_session;;INFO FOR TABLE dietary_profile;;INFO FOR TABLE enrollment;;INFO FOR TABLE event;;INFO FOR TABLE exam;;INFO FOR TABLE exam_answer;;INFO FOR TABLE exam_attempt;;INFO FOR TABLE exam_question;;INFO FOR TABLE exam_result;;INFO FOR TABLE fee_plan;;INFO FOR TABLE fee_plan_assignment;;INFO FOR TABLE homework;;INFO FOR TABLE homework_file;;INFO FOR TABLE homework_result;;INFO FOR TABLE homework_submission;;INFO FOR TABLE kind_ref;;INFO FOR TABLE meal_attendance;;INFO FOR TABLE meal_booking;;INFO FOR TABLE meal_ledger;;INFO FOR TABLE menu;;INFO FOR TABLE menu_dish;;INFO FOR TABLE message;;INFO FOR TABLE note;;INFO FOR TABLE note_file;;INFO FOR TABLE parent_link;;INFO FOR TABLE payment_ledger;;INFO FOR TABLE pomodoro_session;;INFO FOR TABLE pool_question;;INFO FOR TABLE question_image;;INFO FOR TABLE rate_limit;;INFO FOR TABLE registration;;INFO FOR TABLE session;;INFO FOR TABLE session_attendance;;INFO FOR TABLE settings;;INFO FOR TABLE slot_ref;;INFO FOR TABLE solution;;INFO FOR TABLE subject;;INFO FOR TABLE term;;INFO FOR TABLE user;;INFO FOR TABLE work_entry;
61+CREATE user:01KYTW2N7ZSG9RDTN47C0YEG01 CONTENT { username:'stalestudent', password_hash:'$argon2id$v=19$m=19456,t=2,p=1$wRqh5DvfiRfBF0oqwbGh/A$ybdhHrHs73ixid1sipo9n4Pw6eTOhcHDCqPArvK51G4', role:'student', name:'Stale', surname:'Student', email:'s@e.com', phone:'5551112233', birth_date:'2010-01-01', theme:'dark', language:'tr', palette_color:'#ff8800', chatbot_thread_count: 2 };
62+CREATE user:01KYTW2N7ZSG9RDTN47C0YEG02 CONTENT { username:'staleteacher', password_hash:'$argon2id$v=19$m=19456,t=2,p=1$wRqh5DvfiRfBF0oqwbGh/A$ybdhHrHs73ixid1sipo9n4Pw6eTOhcHDCqPArvK51G4', role:'teacher', name:'Stale', surname:'Teacher' };
63+CREATE user:01KYTW2N7ZSG9RDTN47C0YEG03 CONTENT { username:'staleparent', password_hash:'$argon2id$v=19$m=19456,t=2,p=1$wRqh5DvfiRfBF0oqwbGh/A$ybdhHrHs73ixid1sipo9n4Pw6eTOhcHDCqPArvK51G4', role:'parent' };
64+CREATE chatbot_thread:01KYTW2N7ZSG9RDTN47C0YEG11 CONTENT { user_id: user:01KYTW2N7ZSG9RDTN47C0YEG01, title:'old thread one', created_at: 1750000000000, updated_at: 1750000000000 };
65+CREATE chatbot_thread:01KYTW2N7ZSG9RDTN47C0YEG12 CONTENT { user_id: user:01KYTW2N7ZSG9RDTN47C0YEG01, title:'old thread two', created_at: 1750000001000, updated_at: 1750000001000 };
66+SELECT * FROM user ORDER BY id;
67+INFO FOR TABLE board; INFO FOR TABLE board_stroke; INFO FOR TABLE user;
68+INFO FOR TABLE answer_image;;INFO FOR TABLE appointment;;INFO FOR TABLE appointment_slot;;INFO FOR TABLE attendance;;INFO FOR TABLE bank_question;;INFO FOR TABLE bank_question_image;;INFO FOR TABLE chatbot_message;;INFO FOR TABLE chatbot_thread;;INFO FOR TABLE course;;INFO FOR TABLE course_session;;INFO FOR TABLE dietary_profile;;INFO FOR TABLE enrollment;;INFO FOR TABLE event;;INFO FOR TABLE exam;;INFO FOR TABLE exam_answer;;INFO FOR TABLE exam_attempt;;INFO FOR TABLE exam_question;;INFO FOR TABLE exam_result;;INFO FOR TABLE fee_plan;;INFO FOR TABLE fee_plan_assignment;;INFO FOR TABLE homework;;INFO FOR TABLE homework_file;;INFO FOR TABLE homework_result;;INFO FOR TABLE homework_submission;;INFO FOR TABLE kind_ref;;INFO FOR TABLE meal_attendance;;INFO FOR TABLE meal_booking;;INFO FOR TABLE meal_ledger;;INFO FOR TABLE menu;;INFO FOR TABLE menu_dish;;INFO FOR TABLE message;;INFO FOR TABLE note;;INFO FOR TABLE note_file;;INFO FOR TABLE parent_link;;INFO FOR TABLE payment_ledger;;INFO FOR TABLE pomodoro_session;;INFO FOR TABLE pool_question;;INFO FOR TABLE question_image;;INFO FOR TABLE rate_limit;;INFO FOR TABLE registration;;INFO FOR TABLE session;;INFO FOR TABLE session_attendance;;INFO FOR TABLE settings;;INFO FOR TABLE slot_ref;;INFO FOR TABLE solution;;INFO FOR TABLE subject;;INFO FOR TABLE term;;INFO FOR TABLE user;;INFO FOR TABLE work_entry;
69+INFO FOR DB;
70+SELECT * FROM user ORDER BY id;
71+SELECT * FROM user:01KYTW2N7ZSG9RDTN47C0YEG01;
72+SELECT VALUE count() FROM board GROUP ALL;
73+SELECT VALUE count() FROM board_stroke GROUP ALL;
74+SELECT id, creator, creator.role AS creator_role, creator.username AS creator_username FROM board;
75+SELECT VALUE count() FROM board WHERE creator.role = 'parent' GROUP ALL;
76+SELECT id, board_count FROM user WHERE board_count != NONE;
77+SELECT id, board_count FROM user ORDER BY id;
78+SELECT id, epoch, epoch_stroke_count, total_stroke_count, participants FROM board ORDER BY id;
79+SELECT VALUE count() FROM board_stroke GROUP ALL;
80+SELECT VALUE board_count FROM user:01KYTW2N7ZSG9RDTN47C0YEG01;
81+SELECT VALUE count() FROM board_stroke GROUP ALL; SELECT VALUE board_count FROM user:01KYTW2N7ZSG9RDTN47C0YEG01; SELECT VALUE count() FROM board GROUP ALL;
82+SELECT id, board_count FROM user ORDER BY id; SELECT id, epoch, total_stroke_count FROM board ORDER BY id;
83+SELECT id, board_count FROM user ORDER BY id; SELECT id, epoch, total_stroke_count FROM board ORDER BY id; SELECT VALUE count() FROM board_stroke GROUP ALL;
84+DELETE board_stroke;
85+DELETE board;
86+DELETE exam_answer; DELETE exam_attempt; DELETE exam_question; DELETE exam;
87+DELETE enrollment; DELETE subject; DELETE course;
88+DELETE chatbot_thread WHERE user_id IN [user:01KYTW2N7ZSG9RDTN47C0YEG01];
89+DELETE session WHERE user IN [user:01KYTW2N7ZSG9RDTN47C0YEG01, user:01KYTW2N7ZSG9RDTN47C0YEG02, user:01KYTW2N7ZSG9RDTN47C0YEG03];
90+DELETE user:01KYTW2N7ZSG9RDTN47C0YEG01, user:01KYTW2N7ZSG9RDTN47C0YEG02, user:01KYTW2N7ZSG9RDTN47C0YEG03;
91+SELECT * FROM user; SELECT VALUE count() FROM board GROUP ALL; SELECT VALUE count() FROM board_stroke GROUP ALL; SELECT VALUE count() FROM course GROUP ALL; SELECT VALUE count() FROM exam GROUP ALL;
92+SELECT VALUE sha256 FROM meta:readme;
93+REMOVE TABLE IF EXISTS doc;
94+REMOVE TABLE IF EXISTS meta;
95+INSERT INTO doc [{"id": "intro", "title": "intro", "body": "# hezarfen_backend\\n\\nNote, attendance, course + weighted exam mark backend. **Rust (edition 2024) Β· axum Β· SurrealDB 3 (server, WebSocket) Β· tokio.**\\n\\nSession-cookie auth with five hierarchical roles (`parent < student < teacher\\n< manager < admin`). A **`parent`** observes and changes nothing: admins tie\\nstudents to a parent account, and the parent reads those students' mark,\\nattendance, pomodoro, and homework reports β€” that's the whole role. Notes are per-user and carry **file attachments** (PDFs, documents,\\n…): blobs live on disk next to the database, metadata in the database, and the\\nper-file size cap is school policy in settings (`max_file_bytes`, default\\n5 MiB). Any two users can **message** each other, mail-style β€” subject +\\nbody into the recipient's inbox, each side filing its own copy through\\narchive/trash with a read flag the sender sees as a receipt (the only place a\\n`parent` writes). Attendance is event + attendees: create an event with an **audience**\\n(the whole school, one role, a course's enrollment, or a **registration**\\nsignup list β€” omit for school-wide), then teachers mark the expected attendees\\npresent / absent / late / excused (students never self-mark), and a **roster\\nreport** shows who was expected and who missed. Registration lists fill seat\\nby seat: teachers register students (never the other way round), staff\\nregister only themselves, an optional `capacity` caps the seats, and the list\\ncloses the moment the event starts (or, for an event with only an end time β€”\\na pure signup deadline β€” the moment that end passes). Every event stays visible to everyone β€”\\nthe audience is a roster, not a wall. Marks are course-shaped\\n(Google Classroom style): a teacher creates a course β€” kind **`course`** (a\\nregular class), **`study`** (a supervised study session β€” *etΓΌt*), or\\n**`club`** (a student club β€” *kulΓΌp*; same behavior, different label),\\noptionally capped by a `capacity` that refuses new enrolls once the roster is\\nfull β€” lays out its **subjects** (curriculum topics β€”\\nevery exam question must be tagged with one of its course's subjects, so\\nresults can later be read per topic), enrolls students, adds\\nexams inside it, and grades β€” enrolling, sitting exams, roll call, and marks are\\nall student-only, staff never take part. A course is run by whoever created it\\nplus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`):\\nan assigned teacher manages everything inside the course β€” exams, sessions,\\nsubjects, roster, grading β€” but can't delete it or change who else teaches it,\\nand a demotion below `teacher` sweeps their assignments away. Students read a per-course weighted average and\\nan overall average from their mark report β€” each exam weighted by its **kind**\\n(midterms can count double, orals once: weights are set per kind in settings,\\nnot per exam). Exams run **sync** (one\\nfixed window), **async** (start anytime inside the window, with a personal\\ntime budget), or **open** (sit anytime, optionally timed per attempt);\\nstudents *sit* them via attempts β€” retakes metered by a per-exam limit\\n(`0` = unlimited), each sitting keeping its own answers, drawings, and mark\\nso staff can read a student's full attempt history, leaving the exam room\\ngoverned by a teacher-controlled rejoin door. Writing an exam takes a while, so it can be saved as a\\n**draft** β€” invisible to students, unsittable, ungradable β€” and published\\nwhen it's ready. Questions can carry **images**: any question may hold one\\nillustration (a map above the prompt), and each option of a choice question\\nmay be a picture of its own (pick the right city off the map) β€” raster\\nuploads capped by the same `max_file_bytes` policy as note files. Good\\nquestions get reused, so a teacher+ can bank one in a school-wide **question\\nbank** β€” detached templates (with their own images) that any teacher copies\\ninto a fresh exam question across years, editable and deletable only by\\nwhoever saved them. Teachers\\nwatch attendance, per-student remaining time,\\nsittings, walk-outs, no-shows (`absent` once the window closes), submissions,\\nand marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out\\n**homework**: assigned to the whole class or a named subset (the unnamed never\\neven see it), tagged with a course subject, due by a required future `due_at`\\nβ€” students hand in text and/or **files of any type** (same size cap, 10 per\\nsubmission, served back only as forced downloads), editable until the teacher\\ngrades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark\\n(grading freezes the hand-in until the grade is removed); lateness is computed\\nfrom two stamps (first hand-in vs last touch), never stored, and homework\\nmarks stay out of the weighted `/marks` averages. Courses also carry **lesson\\nsessions** with teacher-taken roll call (students never self-mark a lesson),\\nstaff clock in/out on a server-stamped **work log**, students track study time\\nwith a server-stamped **pomodoro log** (the timer runs in the frontend; the\\nbackend records the focus stints, and teachers can read any student's log),\\nand every user has an\\n**attendance report** (event + per-course lesson tallies with rates).\\nA school-wide **question pool** runs on moderation: a student asks a question\\n(optionally attaching one photo of the problem β€” raster only, same\\n`max_file_bytes` cap), a teacher+ **approves** it into the pool (or deletes\\nit β€” rejection is deletion, there is no rejected state), and every approved\\nquestion is readable by the whole school with anyone free to offer\\n**solutions** under it (parents stay out) β€” text plus an optional photo of\\nthe worked steps, both editable by the solution's author anytime; pending\\nquestions show only to their asker and to teacher+, and approval freezes the\\ncontent so nothing unmoderated ever reaches the pool.\\nTeachers keep an **appointment calendar**: a teacher+ publishes availability\\nslots (one-off, or repeating weekly up to an `until` date as a series that\\ndeletes as one), and students and parents book a slot with a reason β€” the\\nbooking lands `pending` until the teacher approves it, rejects it, or\\ncounter-proposes another time (which sends it back to `pending` for the\\nrequester to accept or decline); the **requester** may cancel until the meeting\\nstarts β€” a teacher ends a booking by rejecting it, or by counter-proposing and\\nthen rejecting an approved one β€” one live booking holds a slot, a teacher's own\\npublished windows may not overlap each other, and no approved meeting may\\noverlap another for the teacher or the requester (see \\"Appointments\\").\\nSchool-varying policy is data, not code: exam kinds (each with its weight in\\ncourse averages), attendance statuses, grade-display bands, the note-file\\nsize limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms**\\nare plain rows courses can link to (see \\"Per-school policy\\"). Each account\\nalso carries its own **UI preferences** β€” theme (`light`/`dark`), language\\n(`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` β€”\\nany hex, deliberately not a fixed palette) β€” self-managed, admin-editable for\\nanyone, `null` until chosen so the client can fall back to the device\\npreference (or, for the accent, its own default).\\nThe **AI features live in separate projects**, so the backend also opens a\\nQUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in,\\nregister the capabilities they serve, and each request rides its own QUIC\\nstream on that one connection β€” no correlation ids, no head-of-line blocking.\\nThe bridge's certificate is published at `GET /ai/certificate` so a service can\\npin it before dialling (see \\"AI bridge (QUIC)\\").\\nThe first thing riding that bridge is the **chatbot**: every signed-in user\\n(`parent` included) keeps private threads with an AI service, free-form β€”\\nno rule tables, no canned answers, the backend only owns auth, limits,\\npersistence and the payload format. Sending is asynchronous because an\\ninference outlives a request: the turn plus an empty `pending` answer are\\nwritten *first*, the call goes out after, so a reload never loses an answer;\\nthe client then polls the message or reads it off an SSE stream (see\\n\\"Chatbot\\").\\nAny account from `student` upwards can also open a **collaborative\\nwhiteboard** (a `parent` gets no whiteboard access at all β€” it can neither open\\none nor be invited onto one): a titled board whose membership is an **ad-hoc\\ninvite list** β€”\\nthe creator names participant user ids, and no course, session or appointment\\nis involved. Every participant draws over a WebSocket, the creator alone\\nclears, locks, closes or deletes, and someone who is not on a board gets a\\n`404` for it on every route, existence included. Strokes are **append-only and\\na clear deletes nothing** β€” it bumps the board's epoch, so the live canvas\\nempties while every mark ever drawn stays stored and replayable through the\\nhistory reads (see \\"Collaborative whiteboard\\").\\nThe school's **food program** is published here too: a manager puts up one\\n**menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot`\\ndrawn from the school's `meal_slots`, unique per pair), lists its **dishes**\\nwith dietary tags from the school's own list, and prices them in **minor\\nunits** (kuruş) as integers β€” this API never speaks decimals or floats about\\nmoney. A student's own **dietary profile** is tagged from that same list\\n(manager-written β€” an allergen list is a school record, not a self-service\\npreference), so every dish a menu read returns names the tags it `conflicts`\\nwith for whoever is reading. Every authenticated user reads what is being\\nserved; students (or their parents) book a seat, and every seat writes a line into an\\n**append-only** meal ledger whose balance is derived and never stored (see\\n\\"Food program: menus, dishes, bookings & the ledger\\").\\nSchool **fees** are tracked the same way, in a ledger of their own: a manager\\nwrites a **fee plan** (a name and 1–60 installments, each an amount in minor\\nunits and a due date that may sit in the past) and **assigns** it to students,\\nwhich appends every installment as a `charge` at once β€” there is no scheduler,\\nand \\"overdue\\" is derived at read time. Payments are recorded against one named\\ncharge, refunds against one named payment, and nothing is ever edited or\\ndeleted: a mistake is corrected by appending the opposing line. **There is no\\nonline payment integration and none is planned** β€” no gateway, no card data,\\n`method` is free text. Teachers see no money at all (see \\"Payments\\").\\n\\nEvery field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)\\nconstructed only after its restrictions pass β€” invalid input can't be\\nrepresented. Those restrictions are published rather than left to be guessed:\\n**`GET /limits`** (no auth) serves every fixed bound and closed value set the\\nAPI enforces, read straight from the constants the newtypes use, so a frontend\\nvalidates against the server's own rules instead of a hand-kept copy (see\\n\\"Validation limits\\"). Those same types derive `surrealdb::types::SurrealValue`, so one\\ntyped value flows from HTTP request into the `SCHEMAFULL` database. Record ids\\nare ULIDs (time-sortable).", "source": "README.md"}, {"id": "run", "title": "Run", "body": "```sh\\nsurreal start --user root --pass root surrealkv:./data/hezarfen.db # the DB server\\ncp .env.example .env # optional\\ncargo run\\n```\\n\\nBoots on `http://127.0.0.1:8080`, talking to the SurrealDB server at\\n`DB_URL` (default `ws://127.0.0.1:8000`, root credentials via\\n`DB_USER`/`DB_PASS`) and storing uploaded note files in\\n`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs\\n(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at\\n`/api-docs/openapi.json`.", "source": "README.md"}, {"id": "run-in-a-container-podman", "title": "Run in a container (podman)", "body": "```sh\\npodman compose up -d --build # build + start, http://127.0.0.1:8080\\npodman compose logs -f backend\\npodman compose down # stop (data survives in the volume)\\n```\\n\\nThe `Containerfile` is a two-stage build (Rust builder with cargo cache\\nmounts, `debian:trixie-slim` runtime, non-root user). Two services: the\\n`surrealdb` server (official image, surrealkv storage) and the backend, which\\nwaits for the server's healthcheck and connects over `ws://surrealdb:8000`.\\nEach has its own named volume β€” `surreal-data` holds the database,\\n`hezarfen-data` the uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the\\ncontainer so the published port works. Production knobs (`COOKIE_SECURE`,\\n`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in\\n`compose.yaml` β€” uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset\\nmeans dev mirror mode without credentials; a cookie-using browser frontend\\nmust be allowlisted explicitly. Works with `docker compose` too.\\n\\nThe backend survives the database going away, at boot and at runtime.\\n\\nAt boot it retries the connection (1s doubling to 5s) until the server\\nanswers, rather than exiting. Exiting looks tidier but is worse: the container\\nruntime restarts the process, it fails again in milliseconds, and a few\\nseconds of startup skew burns the whole restart budget and leaves the backend\\ndown for good.\\n\\nAt runtime a keepalive query every 5s doubles as a liveness probe. This\\nmatters more than it sounds: a query issued while the socket is down does\\n*not* fail β€” the SDK's reconnect loop stops draining its request queue, so the\\nquery parks until the database returns and only *then* runs. Left alone, a\\nrequest waits out the entire outage and any write it carries lands long after\\nthe caller gave up.\\n\\nSo while the probe says the socket is down, requests are refused at the edge\\nwith `503` and `Retry-After: 1`, before they can reach the database. Nothing\\nis queued, which is what makes that retry safe. Requests that slip through in\\nthe window between the socket dying and the probe noticing are capped at 30s\\nand answer `503` *without* `Retry-After`, with a message saying the write may\\nor may not have applied β€” they were already queued, so retrying them could\\napply the same write twice. WebSocket and SSE routes are unaffected: both\\nreturn their response immediately and stream afterwards.\\n\\nWithout compose:\\n\\n```sh\\npodman build -t hezarfen-backend .\\npodman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backend\\n```", "source": "README.md"}, {"id": "auth-model", "title": "Auth model", "body": "Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, stored\\nserver-side). Send it back on later requests. Every endpoint below whose `Auth`\\ncolumn names a role requires a valid session; the ones marked `no` (`/health`,\\nthe docs pages, `register` / `login` / `logout`) don't (`logout` is idempotent β€”\\nit clears the session if one is present). Set `COOKIE_SECURE=true` when serving\\nbehind TLS to add the cookie's `Secure` attribute.\\n\\n**Register never reveals whether a username is taken.** `POST /auth/register`\\nanswers `201` either way with the *same* body β€” `{username, role}`, the echoed\\nname and the `student` role every fresh account gets. Both outcomes return one\\nvalue built before the insert is even attempted, so they are byte-identical by\\nconstruction. This is deliberate: the route is unauthenticated, so a `409` (or a\\nfaster reply) would let anyone enumerate the school's users. The password is\\nhashed *before* the availability check so both outcomes cost the same ~33ms.\\n\\nThe reply carries **no `id`**: on the taken path there is no row to name, and a\\nfabricated one would leave the client holding an id that matches nothing. Log\\nin and read `GET /auth/me` to learn who you are. The accepted cost: a caller who\\ncollides with an existing account gets no distinct error and simply cannot log\\nin with that password β€” they pick another name. Do not \\"fix\\" this back to a\\n`409`, and do not add an `id` back.", "source": "README.md"}, {"id": "time-policy", "title": "Time policy", "body": "Timezones and clock differences cannot corrupt data, by construction:\\n\\n- **Every instant is a UTC unix-millisecond `i64`** (`domain::timestamp::Timestamp`),\\n stored as an `int`, sent as a plain number. Nothing stores or parses a\\n timezone, so the server's `TZ`, the container's clock config, and the\\n client's locale are all irrelevant β€” clients convert millis to local time\\n for display only.\\n- **One clock choke point.** `Timestamp::now()` is the only wall-clock read.\\n `clippy.toml` bans every other source (`chrono::Local`/`Utc::now`,\\n `SystemTime::now`, `time::OffsetDateTime::now_*`, absolute cookie\\n `Expires`) and `[lints.clippy]` raises that to a hard `cargo clippy` error,\\n so local-time bugs can't be reintroduced.\\n- **Expiry is server-authoritative.** Sessions expire by comparing the stored\\n millis against the server clock; the cookie carries a relative `Max-Age`\\n (never an absolute `Expires`), so a wrong client clock changes nothing.\\n- **Pacing uses the monotonic clock.** The rate limiter runs on `Instant`,\\n immune to NTP steps and wall-clock jumps.\\n- **Calendar dates get a timezone grace.** A birth date is a calendar date on\\n the writer's wall, not an instant: validation accepts up to UTC-tomorrow,\\n since a client ahead of UTC (up to UTC+14) legitimately writes a date the\\n server's UTC calendar hasn't reached yet.\\n- **Times-of-day are UTC too, and staff enter them that way.** A meal slot's\\n `serving_minute` (minutes past midnight, `0`–`1439`) is the one clock-face\\n value a school types in, and it is read as UTC on the menu's `date` β€” there\\n is deliberately **no school-timezone setting** (a rejected feature), so a\\n UTC+3 school enters `540` (09:00 UTC) for a meal served at noon locally.\\n- **Nothing schedules in the past.** A request-supplied schedule instant β€” an\\n exam window, a lesson's `starts_at`/`ends_at`, an event time β€” must not lie\\n before the server's now, on create and on every `PATCH` that sets it: a\\n deadline that starts in the past is dead on arrival, so it's a `400`. A\\n 60-second grace absorbs request latency and client-clock skew (\\"starts now\\"\\n survives its own round trip). Values a `PATCH` merely keeps are exempt β€” a\\n running exam's `starts_at` is legitimately past, and a rename or deadline\\n extension must not trip over it. (Work-log corrections are records of past\\n work, not schedules, and stay free.)\\n- **Frontends can sync to the server clock.** `GET /time` (no auth) returns\\n `{\\"now\\": <UTC unix-millis>}`. Fetch once, keep\\n `offset = now - Date.now()`, and use `Date.now() + offset` for countdowns\\n and past/future checks instead of trusting the device clock.\\n\\nKeep the single server's clock NTP-synced; that's the only clock that matters.", "source": "README.md"}, {"id": "validation-limits", "title": "Validation limits", "body": "Every fixed bound the API enforces is published at `GET /limits` (no auth), so\\na client never has to hard-code a copy that drifts the day a constant moves.\\nThe handler reads `src/constant.rs` directly β€” a changed constant changes the\\nresponse in the same commit.\\n\\n```json\\n{\\n \\"user\\": { \\"min_username_len\\": 3, \\"max_username_len\\": 32,\\n \\"username_separators\\": [\\".\\", \\"_\\", \\"-\\"],\\n \\"reserved_usernames\\": [\\"admin\\", \\"…\\"],\\n \\"min_password_len\\": 6, \\"max_password_len\\": 128,\\n \\"max_name_len\\": 100, \\"max_email_len\\": 254,\\n \\"min_phone_digits\\": 7, \\"max_phone_digits\\": 15,\\n \\"roles\\": [\\"parent\\", \\"student\\", \\"teacher\\", \\"manager\\", \\"admin\\"],\\n \\"themes\\": [\\"light\\", \\"dark\\"], \\"languages\\": [\\"tr\\", \\"en\\"],\\n \\"palette_color_pattern\\": \\"^#[0-9a-fA-F]{6}$\\", \\"palette_color_len\\": 7,\\n \\"session_duration_days\\": 7 },\\n \\"note\\": { \\"max_title_len\\": 200, \\"max_content_len\\": 10000, \\"max_files\\": 10 },\\n \\"file\\": { \\"max_name_len\\": 255, \\"max_content_type_len\\": 100,\\n \\"min_max_file_bytes\\": 1024, \\"max_max_file_bytes\\": 26214400,\\n \\"default_max_file_bytes\\": 5242880,\\n \\"image_content_types\\": [\\"image/png\\", \\"image/jpeg\\", \\"image/webp\\", \\"image/gif\\"] },\\n \\"message\\": { \\"max_subject_len\\": 200, \\"max_body_len\\": 10000, \\"max_label_len\\": 50 },\\n \\"event\\": { \\"max_title_len\\": 200, \\"max_description_len\\": 2000 },\\n \\"course\\": { \\"kinds\\": [\\"course\\", \\"study\\", \\"club\\"], \\"max_title_len\\": 200, \\"…\\": 0 },\\n \\"exam\\": { \\"modes\\": [\\"sync\\", \\"async\\", \\"open\\"],\\n \\"question_kinds\\": [\\"choice\\", \\"text\\"],\\n \\"min_duration_ms\\": 60000, \\"max_duration_ms\\": 86400000,\\n \\"max_attempts\\": 100, \\"unlimited_attempts\\": 0,\\n \\"min_mark\\": 0, \\"max_mark\\": 100, \\"…\\": 0 },\\n \\"homework\\": { \\"statuses\\": [\\"done\\", \\"incomplete\\", \\"missing\\"],\\n \\"max_files_per_submission\\": 10, \\"max_assigned\\": 200, \\"…\\": 0 },\\n \\"question_pool\\": { \\"max_title_len\\": 200, \\"max_body_len\\": 10000, \\"max_solution_body_len\\": 10000 },\\n \\"appointment\\": { \\"max_note_len\\": 500, \\"max_reason_len\\": 1000, \\"max_slot_occurrences\\": 52 },\\n \\"chatbot\\": { \\"max_message_len\\": 8000, \\"max_thread_title_len\\": 200,\\n \\"min_max_message_len\\": 100, \\"…\\": 0 },\\n \\"board\\": { \\"max_title_len\\": 200, \\"max_participants\\": 50,\\n \\"max_stroke_payload_len\\": 4096,\\n \\"max_epoch_strokes\\": 5000, \\"max_board_strokes\\": 50000,\\n \\"max_boards_per_creator\\": 200,\\n \\"stroke_kinds\\": [\\"stroke\\", \\"clear\\"],\\n \\"ws_tick_secs\\": 15, \\"ws_max_board_id_len\\": 64 },\\n \\"settings\\": { \\"max_list_len\\": 20, \\"max_item_len\\": 50,\\n \\"min_exam_kind_weight\\": 1, \\"max_exam_kind_weight\\": 100,\\n \\"max_grade_bands\\": 20, \\"max_grade_label_len\\": 20,\\n \\"required_attendance_statuses\\": [\\"present\\", \\"absent\\", \\"late\\", \\"excused\\"] },\\n \\"request\\": { \\"max_page_limit\\": 500, \\"schedule_past_grace_ms\\": 60000,\\n \\"request_timeout_secs\\": 30 },\\n \\"rate\\": { \\"window_secs\\": 60, \\"auth_per_minute\\": 10,\\n \\"api_per_minute\\": 300, \\"chatbot_per_minute\\": 20 }\\n}\\n```\\n\\nThe `rate` group is the one part that is **not** compile-time: those tiers are\\nenvironment-tunable, so the endpoint serves *this* server's live values (read\\nfrom its running limiters), not the shipped defaults. `0` means the tier is\\noff. A client should read its budget here rather than discovering it by\\ncollecting a `429`.\\n\\n### Two surfaces, one source\\n\\nThe bounds are published twice, on purpose, because clients consume them two\\ndifferent ways:\\n\\n| Surface | Shape | Use it when |\\n|---------|-------|-------------|\\n| `GET /limits` | One JSON document, grouped by resource, closed value sets included | Runtime fetch. No codegen step, survives a deploy skew, and carries things OpenAPI holds awkwardly (`reserved_usernames`, `image_content_types`) |\\n| `/api-docs/openapi.json` | Per-field `maxLength` / `minLength` / `minimum` / `maximum` / `maxItems` on the request schemas | Build-time codegen β€” `openapi-typescript`, `orval`, and friends turn these into types *and* validators automatically |\\n\\nBoth are generated from the same `src/constant.rs`, and **neither is allowed to\\ndrift from it**, which is enforced rather than asked for:\\n\\n- `tests/limits_completeness.rs` parses every `pub const` out of `constant.rs`\\n and fails unless each one is either referenced by `src/web/limits.rs` or\\n listed as a deliberate exclusion *with a reason*. A new constant breaks the\\n suite until someone decides, consciously, whether clients need it.\\n- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 161 published\\n bounds back out of the emitted JSON, and asserts each equals its constant.\\n This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal\\n only** β€” a `const` there does not compile β€” so the annotations are\\n unavoidably a second copy of each number. The test is what makes that copy\\n safe. It also pins the `limit` query parameter's `maximum` to\\n `MAX_PAGE_LIMIT`, a duplication `constant.rs` previously only *asked* a human\\n to maintain.\\n- A third check in `limits_completeness.rs` refuses to let a validation bound\\n be declared **outside** `constant.rs` at all. Without it a limit can hide in\\n a domain module and reach neither surface β€” which is exactly where\\n `MAX_CHATBOT_THREAD_TITLE_LEN` was found sitting, private and unpublished.\\n\\nNotes:\\n\\n- **No auth.** The registration and login forms need the username and password\\n bounds before a session exists, and none of these are secrets β€” they are the\\n same rules a `400` already spells out in prose.\\n- **Answers during a database outage.** `/limits` touches no row, so it is\\n exempt from the guard that answers `503` while the database reconnects β€” a\\n frontend booting against a degraded backend is exactly when it needs the\\n contract. Every route that does read the database still refuses.\\n- **Fetch once.** The values are compile-time constants, so the response only\\n changes with a deploy. Cache it for the session; the `ETag`/`304` path makes\\n a revalidation cheap if you'd rather re-check.\\n- **`/limits` is not `/settings`.** School-adjustable policy β€” the exam kinds\\n and their weights, the attendance statuses, the grade bands, the live\\n `max_file_bytes` and chatbot knobs β€” is on `GET /settings` and changes when a\\n manager edits it. What `/limits` carries for those knobs is the fixed range a\\n manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the\\n attendance statuses no school may remove.\\n- **Open sets travel as a pattern.** `palette_color` accepts any hex accent\\n color, so `/limits` publishes `palette_color_pattern` (a regular expression)\\n and `palette_color_len` instead of a value list β€” validate the shape, not\\n membership in a palette. The pattern describes what the server *accepts*, so\\n it matches either case; the stored (and returned) value is lowercased, which\\n is the one place a response may differ in case from the request.\\n- **Closed value sets ride along.** `roles`, `themes`, `languages`, course\\n `kinds`, exam `modes`, `question_kinds`, homework `statuses`, board\\n `stroke_kinds`, and the\\n uploadable `image_content_types` are the exact accepted spellings β€” build\\n pickers from these rather than from a literal list.", "source": "README.md"}, {"id": "rate-limiting", "title": "Rate limiting", "body": "Requests are limited per client IP over a fixed 60-second window, in two tiers:\\n`/auth/login` + `/auth/register` get a strict budget\\n(`RATE_LIMIT_AUTH_PER_MINUTE`, default 10) against credential brute-force,\\nand every route β€” Swagger included β€” shares a generous catch-all\\n(`RATE_LIMIT_API_PER_MINUTE`, default 300). Exceeding either answers `429` with\\na `Retry-After` header (seconds). Set a limit to `0` to disable that tier β€”\\nuseful for load tests.\\n\\nSending a chatbot message adds a third tier, and it is keyed by **user id**,\\nnot by IP (`RATE_LIMIT_CHATBOT_PER_MINUTE`, default 20), because an inference\\ncosts the school real money and a shared-IP classroom must not spend one\\nstudent's budget on another's. `0` disables it like the other two. It is\\ncharged before anything is written, so a `429` leaves no trace (see\\n\\"Chatbot\\").\\n\\nAll three tiers admit from memory β€” no request ever waits on the database to be\\nlet in β€” but the window **outlives the process**. A background task folds each\\ntier's new admits into one shared `rate_limit` row per tier + client + minute\\nevery 2 seconds, then caps the in-memory bucket by the total that comes back,\\nso a restart mid-minute does not hand every client a fresh budget. One caveat:\\na just-started process can spend up to the tier's budget in the 2 seconds\\nbefore its first fold tightens it. If the database is down the tiers simply\\nfall back to their own local budgets β€” nobody is refused for it.\\n\\nBehind a reverse proxy every connection carries the proxy's address, so also\\nset `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry\\n(the one the proxy itself appends). Leave it off when clients reach the server\\ndirectly β€” the header is client-forged in that case.", "source": "README.md"}, {"id": "cors", "title": "CORS", "body": "Cookie-authenticated APIs can't use a wildcard `Access-Control-Allow-Origin`\\n(browsers refuse it on credentialed requests), so origins listed in the\\ncomma-separated `CORS_ALLOWED_ORIGINS` allowlist are echoed back with\\n`Access-Control-Allow-Credentials: true`. When the allowlist is unset the\\nserver reflects the request's `Origin` β€” dev-friendly β€” but **without**\\ncredentials: mirroring with credentials would let any website ride a\\nvisitor's session cookie. A browser frontend that needs the session cookie\\ncross-origin must therefore be allowlisted explicitly.", "source": "README.md"}, {"id": "roles-access-control", "title": "Roles & access control", "body": "Every user has one of five roles, ranked lowest to highest:\\n\\n```\\nparent < student < teacher < manager < admin\\n```\\n\\nThe check is **hierarchical** β€” a higher role satisfies any lower requirement\\n(an admin can do anything a teacher can). New accounts always register as\\n`student`; a role read is re-checked on every request, so a role change takes\\neffect on the user's very next call (no re-login).\\n\\n`parent` is the read-only observer at the bottom of the ladder: an admin ties\\nany number of students to a parent account (`POST /users/{id}/students`), and\\nthe tie is the parent's whole power β€” they list their students\\n(`GET /users/me/students`) and read each one's mark, attendance, pomodoro,\\nand homework reports in full. Student-only checks are exact (`role == student`), so a\\nparent can never enroll, sit an exam, be graded, or land on a roll call; and\\nsitting below every staff bar, they can't touch anything else either β€” except\\nmessages, which any role sends and receives (that's how a parent reaches a\\nteacher). A role\\nchange off either end of a tie (the parent stops being a `parent`, the\\nstudent stops being a `student`) drops the tie, exactly like promotion drops\\ncourse enrollments.\\n\\n| Action | Minimum role | Notes |\\n|------------------------------------------|--------------|-----------------------------------------------|\\n| Register / login / view own account | (any) | Registration always creates a `student` |\\n| View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves |\\n| Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included β€” the role's one write); each party only ever touches their own copy |\\n| Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark β€” a teacher+ may mark anyone expected, themselves included |\\n| Create events | teacher | The audience (school / role / course / registration) is set at creation and editable later |\\n| Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** β€” never for another staff member. Unregistering mirrors the same rule |\\n| List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report |\\n| Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |\\n| View a course's sessions | student | Only inside **visible** courses: enrolled, creator, assigned teacher, or `manager`+ |\\n| List a session's roll call | teacher | The **session's teacher**, or anyone with course-management rights |\\n| Create / edit / delete a course session | teacher | Course-management rights (course creator, an assigned teacher, or `manager`+) |\\n| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights; only students sit on a roster |\\n| Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call β€” the teacher can't self-mark |\\n| Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied |\\n| View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries |\\n| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session |\\n| View **any** user's pomodoro log | teacher | Study oversight β€” same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' |\\n| Ask into the school question pool | student | **Students only** (exact); born `pending` β€” visible to the asker + teacher+ only; the asker may attach/replace/remove one photo while pending |\\n| Read the pool; offer / edit / withdraw own solutions | student | Every `approved` question is school-wide (parents stay out); a solution's author edits its body and photo anytime (solutions never freeze) and deletes it, teacher+ delete any |\\n| Approve a pending pool question; delete any question or solution | teacher | Approval publishes school-wide and **freezes** the content; rejection = deletion β€” moderation never edits, so teacher+ cannot rewrite a solution |\\n| Read the school **question bank**; save / instantiate bank questions | teacher | Every bank row is school-wide (reads + copy into an exam); saving one makes the caller its owner |\\n| Edit / delete a bank question (and its images) | teacher | **Owner only** (admin bypass); bank rows carry no exam link, so they never freeze |\\n| Read **own** attendance report | student | |\\n| Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created + assigned; `manager`+: all); exam **drafts** show only to the course's managers |\\n| Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** β€” staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |\\n| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |\\n| Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |\\n| Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights β€” one teacher can't read another's answer key |\\n| Watch an exam's live monitor (poll the snapshot) | teacher | Course-management rights |\\n| Create courses | teacher | The creator manages the course, and owns it for good |\\n| Assign / unassign a course's teachers | manager | Staffing is the office's call β€” a course's own creator cannot hand rights to peers; the assignee must be `teacher`+ |\\n| Delete a course | teacher | Only the **creator**, or a `manager`+ β€” an assigned teacher runs the course but doesn't own it |\\n| Manage inside a course: edit it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | The **course creator**, a teacher **assigned** to it, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions or homework won't delete (`409`) |\\n| View a course's roster, an exam's result list / statistics | teacher | Course-management rights |\\n| Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |\\n| Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself |\\n| Assign / edit / delete homework; grade it; read its roster | teacher | Course-management rights; an `assigned` subset (≀ 200 enrolled students) can't be narrowed over existing work (`409`); a grade (`done`/`incomplete`/`missing` + optional mark) freezes the submission until removed |\\n| Submit **own** homework (text + files); read own submission and grade | student | **Students only** β€” staff never submit; enrolled + in the audience; editable until graded; ≀ 10 files of any type, each ≀ `max_file_bytes`, always downloaded as attachments |\\n| Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full β€” statuses/marks/flags, never files |\\n| Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields |\\n| Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen β€” the client then follows the device preference |\\n| List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports β€” a parent changes nothing, anywhere |\\n| Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |\\n| Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call |\\n| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role |\\n\\n### Bootstrapping the first admin\\n\\nThere is no self-service path to `admin` β€” registration always creates a\\n`student`. The first admin comes from the startup seed: set both\\n\\n```sh\\nADMIN_USERNAME=admin\\nADMIN_PASSWORD=admin123 # local-dev default used by compose.yaml; change it\\n```\\n\\nand on boot the account is created with the `admin` role **if the username\\ndoesn't exist yet**. The seed is idempotent and deliberately conservative: it\\nnever promotes or rewrites an existing account (if the name is taken by a\\nnon-admin it logs a warning and leaves it alone β€” promoting someone else's\\naccount would be an escalation). Setting only one of the two variables aborts\\nstartup. `compose.yaml` ships with the credentials above for local dev.\\n\\nThat admin can then promote everyone else through `PATCH /users/{id}/role`.\\n\\nManual fallback (also the recovery path if the seeded name was squatted or the\\nsole admin locked themselves out): run\\n\\n```surql\\nUPDATE user SET role = 'admin' WHERE username = 'ada';\\n```\\n\\nagainst the SurrealDB server β€” e.g.\\n`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db hezarfen`\\n(in the container setup, `podman exec -it hezarfen-surrealdb /surreal sql ...`).", "source": "README.md"}, {"id": "endpoints", "title": "Endpoints", "body": "`Auth` is the minimum role; `no` means no session required, `student` means any\\nlogged-in user.\\n\\nA course is a regular class (kind `course`, the default), an *etΓΌt* (kind\\n`study` β€” a supervised study session), or a *kulΓΌp* (kind `club` β€” a student\\nclub). The three kinds behave identically everywhere β€” enrollment, exams,\\nsessions, marks β€” the kind is a label the UI renders differently, settable at\\ncreation and editable later. A course may also carry a `capacity`: once the\\nroster reaches it, new enrolls are refused with `409` (members already on the\\nroster are unaffected, even if the cap is later lowered below them; `null`\\nlifts the cap).\\n\\n**Who runs a course.** Its **creator** owns it for good β€” only they (or a\\nmanager+) may delete it. On top of that, a manager can **assign** any\\n`teacher`+ to the course with `POST /courses/{id}/teachers` (`{user_id}`,\\nidempotent) and drop them again with `DELETE /courses/{id}/teachers/{user}`.\\nAn assigned teacher gets full **course-management rights** β€” edit the course,\\nenroll and unenroll students, add exams, sessions and subjects, grade, take\\nroll call β€” but *not* the two owner powers: they cannot delete the course, and\\nthey cannot change who else teaches it. Staffing is deliberately the office's\\ncall, so a course's own creator cannot hand rights to their peers; only\\nmanager+ may touch the list. Every course response carries its `teachers`\\narray alongside `creator`, and a user demoted below `teacher` is swept off\\nevery course they were assigned to (the mirror of promotion dropping\\nenrollments).\\n\\nCourse data is walled per course. A course, its exams, its sessions, and its\\nsubjects are\\n**visible** only to its enrolled users, its creator, its assigned teachers,\\nand manager+ β€” a student\\nsees just the classes they were added to, and the `/courses` / `/exams`\\ncatalogs are filtered accordingly. Teacher-level reads *inside* a course\\n(roster, results, statistics, the question list, answer sheets, the live\\nmonitor) additionally need **course-management rights** (creator, an assigned\\nteacher, or manager+):\\none teacher cannot look into another teacher's course, and the per-user\\nmarks/attendance reports narrow to the courses the caller manages.\\n\\n**Paging.** Every list endpoint below (the rows tagged **Β· paged**) accepts\\n`?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope\\nrather than a bare array. `total` is the full row count *before* the window, so\\na frontend can show \\"100 of 256\\" and page with `offset`. Paging is **opt-in**:\\nomit `limit` and you get every remaining row (the echoed `limit` is then\\n`null`), so a caller that sends no parameters still receives the whole list β€”\\nnothing silently truncates. `limit` must be `1`–`500`, `offset` defaults to `0`\\nand must be β‰₯ 0 (bad values are `400`), and an `offset` at or past the end\\nreturns an empty `items` (not an error). Deliberately **not** paged β€” these keep\\ntheir existing shapes: the student exam-room reads\\n`/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and\\n`/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`.\\n\\n**Schedule window (`GET /events`, `GET /exams`).** Both lists additionally\\naccept `?starts_after=` and `?ends_after=`, UTC unix-millis, both optional and\\nindependent (AND-ed when both are sent). `ends_after=T` keeps rows whose window\\nhas not finished β€” `ends_at > T`, falling back to `starts_at > T` when `ends_at`\\nis `null`; `starts_after=T` keeps rows with `starts_at > T`. A row with no\\nschedule at all (an event without times, an exam with no `mode` or in `open`\\nmode) is excluded by either parameter. Supplying either one flips the order to\\n**ascending by schedule** (`starts_at`, falling back to `ends_at`; ties by id),\\nso `?ends_after=<now>&limit=20` gives the twenty *soonest* rows instead of the\\ntwenty newest-created β€” with neither parameter the list is byte-for-byte the\\nnewest-first list it always was. `total` is the count after visibility *and*\\nwindow filtering, before paging; negative values are a `400` naming the field.\\n\\n| Method | Path | Auth | Description |\\n|--------|----------------------------------|---------|---------------------------------|\\n| GET | `/health` | no | Liveness check |\\n| GET | `/` | no | Same as `/health` |\\n| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |\\n| GET | `/limits` | no | Every fixed validation bound, grouped by resource β€” see Validation limits |\\n| GET | `/swagger` | no | Interactive API docs (Swagger UI) |\\n| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |\\n| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |\\n| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken β€” see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |\\n| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` β€” own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) Β· paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` β€” find users by username/name fragment (pickers); refs only, no contact info Β· paged |\\n| GET | `/users` | admin | List all users Β· paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` β€” set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` β€” tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students Β· paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |\\n| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes Β· paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) β€” ≀ the school's `max_file_bytes`, ≀ 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) Β· paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |\\n| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` β€” send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` β€” the caller's folder, newest first; `?folder=inbox&read=false&limit=1` β†’ `total` is the unread badge Β· paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` β€” read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** β€” only from the trash (`409` elsewhere); the row vanishes once both sides deleted |\\n| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` β€” `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` β€” mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) Β· paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` Β· paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` β€” seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |\\n| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` β€” publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, ≀ 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) β€” a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar β€” future slots only, demoted teachers' slots left out Β· paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` β€” book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests Β· paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` β€” call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included β€” they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` β€” counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal β€” this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |\\n| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` β€” `kind` is `course` (default), `study` (etΓΌt), or `club` (kulΓΌp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) Β· paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses Β· paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ β€” **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` β€” assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` β€” enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) Β· paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β€” add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β€” add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) Β· paged |\\n| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |\\n| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` β€” roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) Β· paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` β€” add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) Β· paged |\\n| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) Β· paged Β· `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist β€” the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` β€” grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) Β· paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt β€” students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) Β· paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question β€” the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam β€” copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** β€” copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question β€” text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` β€” autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers ⋃ marks), ascending β€” the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first β€” the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** β€” the answer key the caller checks their own sheet against (same review gate) Β· paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers ⋃ marks), ascending β€” only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster Γ— latest attempts Γ— marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |\\n| GET | `/bank-questions` | teacher | The school-wide question bank β€” `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) Β· paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` β€” save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist β€” `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question β€” the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part β€” raster images only (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` β€” assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≀ 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) Β· paged |\\n| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) Β· paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade β€” the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades β€” file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` β€” hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part β€” **any** content type, ≀ `max_file_bytes`, ≀ 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) β€” the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student Γ— submission/files/grade + computed `late`/`missing`/`unenrolled` β€” a straggler's stale work stays visible (course manager) Β· paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` β€” grade `done`/`incomplete`/`missing` (+ optional 0–100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable β€” that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) β€” readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade β€” un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows β€” submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` β€” full, statuses and marks only, never files Β· paged |\\n| POST | `/questions` | student | `{title, body}` β€” ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` β€” the pool questions visible to the caller, each with its `solution_count` Β· paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question β€” publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` β€” offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first β€” a discussion thread Β· paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` β€” edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, ≀ `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |\\n| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) Β· paged |\\n| GET | `/work/{user}` | manager | A staff member's work log Β· paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` β€” correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |\\n| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** β€” a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` Β· paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape Β· paged; *or a `parent` linked to `{user}` |\\n| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |\\n| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |\\n| POST | `/terms` | manager | `{name, starts_at, ends_at}` β€” past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first Β· paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course still links to it |\\n| POST | `/meals/menus` | manager | `{date, slot, capacity?}` β€” publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first Β· `?from=&to=` inclusive `YYYY-MM-DD` range Β· paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` β€” the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` β€” add a dish (≀ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` β€” record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` β€” take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first Β· paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included Β· paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent β€” cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` β€” mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu Β· paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history Β· `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day Β· paged Β· own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` β€” record money received; **admin only**, appends a `credit` line |\\n| POST | `/payments/plans` | manager | `{name, installments}` β€” write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it β€” its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (≀ 200) β€” place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first Β· paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` β€” record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` β€” hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` β€” undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines β€” charges, payments, refunds, reversals β€” newest first Β· paged Β· own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |\\n| POST | `/chatbot/threads` | student | `{title?}` β€” start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first Β· paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` β€” rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first β€” user and assistant rows alike Β· paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≀ `max_chatbot_message_len`) β€” send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` β€” nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` β€” or one `error` β€” and close; an already-finished answer replays (see \\"Chatbot\\") |\\n| POST | `/boards` | student | `{title, participants?}` β€” open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first Β· paged |\\n| GET | `/boards/{id}` | student | One board β€” a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first Β· paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |\\n\\n`status` must be one of the school's attendance statuses (`GET /settings`);\\nthe core four `present | absent | late | excused` always exist, plus whatever\\nthe school added.\\n`kind` must be one of the school's exam kinds (`GET /settings`; defaults:\\n`homework | quiz | midterm | final | project | oral`). The kind carries the\\nexam's weight in the course average β€” an integer `1`–`100` set per **kind** in\\nsettings (defaults all `1`), resolved when a report is read; an exam whose\\nkind was later removed from settings counts with weight `1`.\\nA course may carry a `term_id` (`null` = unassigned); on `PATCH\\n/courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`\\nclears it.\\n`role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are\\nULIDs. `parent` accounts are made by an admin (register as `student`, then\\n`PATCH /users/{id}/role`) and observe only the students an admin tied to them\\nβ€” see \\"Roles & access control\\".\\nAn exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row,\\nnever in a `note`. Students never grade anyone β€” grading is teacher+ with\\ncourse-management rights, and the target must be enrolled in the exam's course;\\na student reads just their own mark via `GET /exams/{id}/result`.\\nA course average is `Ξ£(markΓ—weight) / Ξ£(weight)` over the student's **graded**\\nexams in that course (`null` while nothing is graded β€” ungraded exams are\\nskipped, not zeroed). The overall average is the plain mean of the non-null\\ncourse averages. Unenrolling keeps result rows: the marks drop out of the\\nreport until re-enrollment, but stay visible on the exam itself. A course\\nwith anyone still on its roster refuses deletion (`409`) β€” empty the roster\\nfirst; once empty, deleting it cascades its exams, their results, its\\nsessions and roll call, and its subjects.\\nA **subject** is one topic of a course's curriculum (`name` ≀ 200 chars,\\noptional `description` ≀ 2000): every exam question carries a mandatory\\n`subject_id` naming one of *its own course's* subjects (an unknown or\\nforeign-course subject is a `400`), so exam content is always attributable to\\na topic. A subject's course link is fixed at creation, and a subject still\\nreferenced by questions refuses deletion with a `409` β€” re-tag (PATCH the\\nquestions' `subject_id`) or delete those questions first. Questions written\\nbefore subjects existed are **destroyed on boot** (answers first) β€” the clean\\nbreak instead of inventing a placeholder topic.\\nEvent `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both\\nare given, `ends_at` must not precede `starts_at`, and neither may be set in\\nthe past (else `400`). On `PATCH`, an omitted time keeps its value and an\\nexplicit `null` clears it.\\nAn event's `audience` is a tagged object β€” `{\\"kind\\": \\"school\\"}` (the default),\\n`{\\"kind\\": \\"role\\", \\"role\\": \\"student\\"}` (that exact role, no \\"and above\\"),\\n`{\\"kind\\": \\"course\\", \\"course\\": \\"<id>\\"}` (the course's current enrollment), or\\n`{\\"kind\\": \\"registration\\", \\"capacity\\": 30}` (a signup list; `capacity` optional,\\n`null` = unlimited) β€” and is the event's **expected-attendee roster**, resolved\\nlive at read time: role changes, (un)enrollments, and (un)registrations move\\npeople in and out by themselves. It never hides the event β€” everyone sees every\\nevent. Only audience members can be marked; `GET /events/{id}/roster` joins the\\nlive roster with the recorded marks (`status: null` = expected but never\\nmarked). Attendance rows for people a later audience edit (or unenrollment /\\nrole change) dropped stay stored and listed under `/events/{id}/attendance`,\\nbut leave the roster report.\\nA registration list fills through `POST /events/{id}/register`: teachers place\\nstudents (a student never registers, not even themselves) and take seats only\\nfor themselves β€” registering another staff member is refused. Re-registering\\nsomeone is a no-op, a full list is a `409`, and the list freezes the moment\\nthe event starts β€” or, when only `ends_at` is set (a pure signup deadline),\\nthe moment it passes (register and unregister both). Signup rows survive an\\naudience switch inertly and resurface if the event returns to the registration\\nkind; deleting the event deletes them. Pre-existing hand-picked (`users`)\\naudiences convert on boot: each listed user becomes a signup row credited to\\nthe event's creator, and the audience becomes an uncapped registration list.\\nReading a child collection of a missing parent (`/events/{id}/attendance`,\\n`/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`,\\n`/courses/{id}/sessions`, `/courses/{id}/subjects`, `/courses/{id}/homework`,\\n`/homework/{id}/submissions`, `/sessions/{id}/attendance`) is a `404`, not an\\nempty list.\\nPersonal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same\\noptional set on every account, whatever the role, and is `null` until filled\\nin. On `PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) each field\\nis independent: omitted (or `null`) keeps the current value, an empty string\\n`\\"\\"` clears it, anything else is validated β€” email must look like\\n`name@example.com`, phone is 7–15 digits with an optional `+` and cosmetic\\nseparators, `birth_date` is a real `YYYY-MM-DD` calendar date not in the\\nfuture. Names allow unicode; usernames are strict: lowercase letters and\\ndigits plus non-consecutive interior `.`, `_`, `-` separators, starting and\\nending with a letter or digit (3–32 chars). Staff-looking names (`admin`,\\n`administrator`, `root`, `support`, `system`, `moderator`, `staff`) are\\nrejected at `/auth/register` only β€” the `ADMIN_USERNAME` bootstrap may still\\nseed them.\\nUI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`,\\n`palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the\\nsame account row and come back on every user response (`/auth/me` included).\\n`PATCH /users/me/preferences` (or the admin `PATCH /users/{id}/preferences`)\\nuses the same field semantics as the profile patch: omitted keeps, `\\"\\"` clears\\nback to `null` (\\"never chose\\" β€” the client then follows the device\\npreference, or its own default accent), anything else must be valid or the\\nwhole patch is a `400`. `palette_color` is the one **open** set: any valid hex\\npasses (mixed case in, stored and returned lowercase), so a new frontend\\npalette needs no backend change β€” `/limits` publishes its pattern rather than a\\nlist of colors.", "source": "README.md"}, {"id": "appointments", "title": "Appointments", "body": "Office hours and parent-teacher conferences, booked instead of arranged by\\nmessage. A teacher+ **publishes availability**; a student or a parent\\n**books** one of those windows with a reason; the teacher **decides**. Two\\nrows carry it: an `appointment_slot` (the offer) and an `appointment` (the\\nbooking sitting on it) β€” a slot is never \\"half booked\\", and a refused request\\nstays readable instead of vanishing.\\n\\nA slot is a window on one teacher's calendar: `starts_at`/`ends_at` (unix\\nmilliseconds, `starts_at` strictly before `ends_at`, neither in the past β€” the\\nusual 60-second grace) plus an optional `note` (≀ 500 chars) shown to\\nrequesters (\\"office hours\\", \\"veli gΓΆrüşmesi\\"). Windows are **half-open**, so\\n10:00–10:30 and 10:30–11:00 are two slots, not a collision. A window that *does*\\noverlap one the same teacher has already published is refused with a `409` β€” the\\nguard is **per-teacher** (two teachers may hold office hours at the same hour)\\nand boundary-touching windows are legal by that same half-open rule, which is\\nhow an hour gets carved into back-to-back slots. `POST\\n/appointments/slots` publishes on the caller's *own* calendar (managers and\\nadmins included β€” the calendar always belongs to whoever posted) and **always\\nanswers an array**: one element for a one-off, one per occurrence for a\\nrecurring publish.\\n\\n`repeat_weekly: true` with an `until` expands the same window every seven days\\nup to and including `until`, server-side, into **concrete rows** sharing a\\n`series` id β€” no recurrence rule is stored, so one week can be cancelled\\nwithout touching the rest. At most 52 occurrences (a year); asking for more is\\na `400`, as is `repeat_weekly` without `until` β€” and so is a window sitting so\\nfar ahead that shifting it by a week would run off the end of representable\\ntime (the shift is checked, never wrapped: a wrapped end would land *before*\\nits start, and an inverted window can never overlap anything, which would\\nquietly disable the double-booking guard). A recurring publish is\\n**all-or-nothing**: every occurrence is checked β€” against the slots already\\nstored *and* against the earlier occurrences of the same batch, which a window\\nlonger than a week overlaps itself β€” before a single row is written, so a\\nmid-series collision answers `409` and leaves no stray weeks behind. Delete one\\noccurrence with\\n`DELETE /appointments/slots/{id}`, the whole publish with `DELETE\\n/appointments/slots/series/{series}`.\\n\\n```json\\nPOST /appointments/slots\\n{ \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"repeat_weekly\\": true, \\"until\\": 1901209600000 }\\n\\n201 [ { \\"id\\": \\"01J8…A\\", \\"teacher\\": {\\"id\\": \\"01J8…T\\", \\"username\\": \\"ayse\\",\\n \\"display_name\\": \\"Ayşe YΔ±lmaz\\"},\\n \\"starts_at\\": 1900000000000, \\"ends_at\\": 1900001800000,\\n \\"note\\": \\"office hours\\", \\"series\\": \\"01J8…S\\", \\"created_at\\": 1899… },\\n { \\"id\\": \\"01J8…B\\", …, \\"starts_at\\": 1900604800000, \\"series\\": \\"01J8…S\\" } ]\\n```\\n\\n`GET /appointments/slots` is two lists behind one path: a teacher+ reads\\n**their own** calendar, past occurrences included; everyone else reads the\\n**bookable** calendar β€” future slots only, earliest first. A teacher demoted\\nafter publishing leaves **inert** slots: their live role is re-read, so those\\nslots drop out of the bookable list and booking one is refused with a `409`.\\nThe list does not say whether a slot is already taken β€” booking a taken one\\nanswers `409`.\\n\\n**Booking.** `POST /appointments` (`{slot, reason}` β€” the reason is required,\\n≀ 1000 chars) is for **students and parents only**; staff arrange between\\nthemselves off this API. A parent books for *themselves* β€” this is the\\nparent-teacher conference, not a booking on behalf of a child. The request\\nlands `pending`, always: publishing availability is not consent to a\\nparticular person and a particular topic, so approve/reject still applies.\\n\\nA booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two\\nare **live** and hold the slot; rejecting or cancelling frees it for someone\\nelse immediately (the slot carries an `occupied` counter, taken by a booking\\nand handed back in the same transaction as the reject or cancel that settles\\nit, so the seat is decided by the database rather than by a count two\\nconcurrent bookings can both read as free). The decisions:\\n\\n- `PATCH /{id}/approve` β€” the slot's teacher (or manager+) confirms. Refused\\n (`409`) when the effective window has already started.\\n- `PATCH /{id}/reject` β€” turns it down; the slot frees up.\\n- `PATCH /{id}/cancel` β€” **the requester only**, from either live state.\\n Anyone else is a `403`, the slot's teacher and a manager/admin included (the\\n guard compares ids, not roles). A teacher ends a booking by **rejecting** it\\n while it is `pending`, and an approved one by counter-proposing another time\\n (`/reschedule`, which sends it back to `pending`) and then rejecting it β€” or\\n simply by rescheduling to a time that works. Refused (`409`) once the\\n meeting's window has started: a\\n meeting that already began is history, not a plan. The guard sits in the\\n domain's `cancel` itself, on a fresh read compared-and-set into the row, so\\n every way of cancelling β€” the decline below included β€” inherits it.\\n- `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) β€” the teacher\\n **counter-proposes**. The times land on the *same* row as\\n `proposed_starts_at`/`proposed_ends_at`, the status goes back to `pending`\\n and `decided_by` clears, because leaving it `approved` would silently move a\\n confirmed appointment. The slot stays held meanwhile. A window that has\\n already opened is refused (`409`): the 60-second grace on the times is for\\n clock skew, not for proposing into a meeting already underway β€” one nobody\\n could then cancel.\\n- `PATCH /{id}/reschedule/accept` β€” the **requester** only: this *is* approval\\n at the new time, so the overlap guard runs again β€” and so does the\\n already-started guard (`409`). Agreeing to a window that has begun does not\\n help: the meeting could never be cancelled. The booking stays `pending`, so\\n the teacher just proposes a time that can still happen.\\n- `PATCH /{id}/reschedule/decline` β€” the requester only, and it **cancels the\\n booking**: the proposal replaced the time that was asked for, so there is\\n nothing to fall back to. The row stays readable as `cancelled` with the\\n refused proposal still on it β€” book another slot instead. Declining *is* a\\n cancel, so it answers to the cancel deadline too (`409` once the effective\\n window has started).\\n\\n**Who settled it, and why.** Every settled booking carries its own audit trail\\non the row: `decided_by` (who approved or rejected β€” cleared again by a\\ncounter-proposal), `cancelled_by` (who called it off, stamped by `cancel` and by\\na declined counter-proposal), plus the optional free text that came with the\\ndecision β€” `reject_reason` on `PATCH /{id}/reject` and `cancel_reason` on\\n`PATCH /{id}/cancel` and `/reschedule/decline`. Both reasons are optional: the\\nwhole body may be omitted, a blank one records nothing (`null`), and a present\\none is validated like the booking's own reason (≀ 1000 chars, `400` past that)\\nbefore it reaches the row. They are **not public**: bookings are only ever\\nrendered to the person who requested them and to the slot's teacher (a\\nmanager/admin acting on one by id sees the response to their own call), so\\n\\"couldn't make it, sorry\\" goes no further than the two people it concerns. Rows\\nwritten before these fields existed simply read back `null`.\\n\\nA booking's effective window is the accepted counter-proposal when there is\\none and the slot's own window otherwise; that is what `starts_at`/`ends_at` on\\nan `AppointmentResponse` report, and what the cancel deadline is judged on.\\n\\n**No double-booking.** Two `approved` meetings may never overlap for the same\\nteacher *or* the same requester (`409`). The guard runs at approval β€” the\\nmoment anyone is actually committed β€” and again on accepting a counter-proposal,\\nbecause the time moved. Approval also refuses (`409`) an **effective window\\nthat has already started** (the proposal's when one stands, the slot's\\notherwise), for the same reason booking one is refused. Requesting is checked more loosely: a booking is\\nrefused up front only when the slot's window has already started (booking it\\nwould create a meeting `cancel` refuses to undo β€” the 60-second publish grace\\nis for clock skew, not for booking into the past), when the slot is already\\ntaken, or when the *requester* is already committed at that hour; a clash on the teacher's side is theirs to\\nresolve when they decide, since refusing a request against a window they\\nthemselves published would only confuse. Touching windows never conflict.\\n\\nDeletion follows the same rule as the rest of the codebase: a slot carrying a\\nlive (pending or approved) booking refuses to go (`409`) β€” reject or cancel\\nthat booking first β€” and a series delete is all-or-nothing, `409` if *any*\\noccurrence still carries one, so the person waiting is dealt with rather than\\nleft stranded on a stray week. Settled (rejected/cancelled) bookings cascade\\naway with their slot.\\n\\n`GET /appointments` is likewise two lists: a teacher+ sees the bookings aimed\\nat their own slots (their request inbox), everyone else the ones they\\nrequested, newest first, paged. Managers and admins read their own inbox here\\ntoo β€” they may still decide any booking by id.", "source": "README.md"}, {"id": "messaging", "title": "Messaging", "body": "One-to-one, mail-style (subject + body + an optional free-text `label` the UI\\nrenders as a badge β€” \\"EtΓΌt\\", \\"SΔ±nav\\"; no threads): any user writes to any\\nuser β€” student to teacher, parent to teacher, teacher to student; only\\nmessaging yourself is refused. A single stored message serves both parties,\\nbut each **owns their copy independently**: the recipient's moves through\\n`inbox` β†’ `archive`/`trash` and carries the `read` flag (the sender sees it\\nas a read receipt); the sender's moves through `sent` β†’ `archive`/`trash`. Filing or\\ndeleting your copy never changes the other side's view.\\n\\nEvery copy remembers where it was filed from, so it can go back there. Moving\\ninto `archive`/`trash` stamps the folder you left onto the copy's\\n`previous_folder`, and restoring is a `PATCH` of `folder` back to that value:\\nan inbox message you archive and then trash returns to `archive`, and from\\nthere to `inbox`. Two folders are never stamped β€” the trash itself (pulling a\\ncopy out of the trash must not leave it pointing back at the discard pile) and\\nthe folder you are already in β€” and moving back to `inbox`/`sent` clears the\\nstamp. `previous_folder` is therefore `null` for any copy sitting in its home\\nfolder, and for copies filed before the field existed; both mean \\"restore to\\n`inbox`\\" (`sent` for the sender's copy).\\n\\nListing is per folder β€” `GET /messages?folder=` with `inbox` (default),\\n`sent`, `archive`, or `trash` (trash shows both received and sent copies you\\ntrashed) β€” newest first, paged, with sender/recipient rendered as person refs\\nplus their role. `?read=false` narrows to unread (`true` to read), and since\\n`total` counts the filtered view, `?folder=inbox&read=false&limit=1` is the\\none-row unread-badge query. `PATCH /messages/{id}` flips `read` (recipient only) or\\nmoves your copy (`folder`), restoring included. `DELETE` is\\npermanent, allowed only while your copy sits in the trash (`409` otherwise),\\nand physically removes the row once both sides have deleted theirs. Replying\\nis just sending a new message back β€” the frontend prefixes the subject if it\\nwants an `Re:`.", "source": "README.md"}, {"id": "question-pool", "title": "Question pool", "body": "Students get stuck; the pool is where the school unsticks them β€” with a\\nmoderation gate so nothing unreviewed goes school-wide. `POST /questions`\\n(students only, exact role) creates the question `pending`: only the asker\\nand teacher+ can see it (anyone else gets a `404`, not a `403` β€” a pending\\nquestion's existence is nobody else's business), and `GET\\n/questions?status=pending` is a teacher's approval queue. The asker may\\nattach **one photo** of the problem (`POST /questions/{id}/image`,\\n`multipart/form-data` with a `file` part β€” raster types only, no SVG, ≀ the\\nschool's `max_file_bytes`), replace it, or remove it β€” while pending only.\\n\\n`POST /questions/{id}/approve` (teacher+) publishes it: the question becomes\\nreadable by every signed-in user above `parent`, and its content β€” title,\\nbody, photo β€” **freezes**, because an edit after approval would bypass the\\nmoderation that just happened. There is no rejected state and no edit\\nendpoint: to fix a typo the asker deletes and re-asks; to reject, a teacher+\\ndeletes. Approving twice is a `409`; the response records `approved_by`.\\n\\nAnyone in the school (student through admin β€” not parents) may then offer a\\n**solution**: `POST /questions/{id}/solutions` with a text body, listed\\noldest-first like a discussion thread (`GET`, paged). Solutions are the\\nunmoderated half of the pool, so nothing about them ever freezes: the author\\nβ€” and only the author, teacher+ included out β€” may edit the body (`PATCH\\n/questions/{id}/solutions/{sid}`) and attach one **photo** of the worked\\nsteps (`POST /questions/{id}/solutions/{sid}/image`, same raster-only rules\\nand `max_file_bytes` cap as the question's photo), replace it, or remove it,\\nat any time; moderation stays delete-only β€” a teacher+ removes a bad\\nsolution, never rewrites someone else's words. A solution is deleted by its\\nauthor or by teacher+, its photo blob going with it; deleting a question β€”\\nasker withdrawing, or teacher+ moderating β€” takes its solutions and every\\nphoto blob (its own and its solutions') with it. Each question row reports\\nits `solution_count`, and questions and solutions embed their people as\\nperson refs (`{id, username, display_name}`), so the UI never shows a raw\\nULID.", "source": "README.md"}, {"id": "per-school-policy-settings-terms", "title": "Per-school policy (settings & terms)", "body": "Every school runs differently; the parts that vary are data, not code. One\\neditable `settings` singleton (`GET /settings` for any signed-in user,\\n`PATCH /settings` for manager+) carries seven knobs:\\n\\n- **`exam_kinds`** β€” the accepted `kind` values for new exams, each an\\n object `{name, weight}`. The weight (`1`–`100`) is how many times an exam\\n of that kind counts into its course average β€” weighting is school policy,\\n set once per kind, never per exam. Defaults to `homework, quiz, midterm,\\n final, project, oral`, all weighing `1` (a plain average); replace the\\n list with whatever the school grades and weighs (`{\\"name\\": \\"final\\",\\n \\"weight\\": 3}`, …). Reports resolve weights live: editing a weight\\n re-weights every exam of that kind at once. For the same reason a kind\\n whose exams already carry marks cannot be removed from the list (`409`):\\n those marks would silently re-weight. An unmarked kind leaves freely, and\\n an exam keeping a since-removed kind counts with weight `1` β€” but it can no\\n longer be graded (`409`) until the school offers that kind again, which is\\n what keeps \\"a marked kind cannot be removed\\" true from both ends. The same\\n rule pointed at one exam: an exam that already carries marks keeps its\\n `kind` (`PATCH /exams/{id}` answers `409`), because re-pointing it would\\n re-weight those marks just as silently.\\n- **`attendance_statuses`** β€” what attendance marking accepts. The core four\\n (`present`, `absent`, `late`, `excused`) are mandatory because the\\n attendance rate is defined over them (`(present+late) /\\n (present+absent+late)`); school extras (say `online`) are **rate-neutral**\\n and tally under `custom` in the attendance reports.\\n- **`grade_bands`** β€” how numeric marks display: a list of `{min, label}`\\n bands (`85 β†’ \\"AA\\"`, `50 β†’ \\"CC\\"`, …). One band must start at `0` so every\\n mark maps; an empty list (the default) means numeric-only. Storage and\\n averaging stay `0`–`100` forever β€” bands only add `grade`,\\n `average_grade`, and `overall_grade` labels to the mark report, so a school\\n can switch display scales without touching a single stored mark.\\n- **`max_file_bytes`** β€” the per-file size cap for uploads (note files and\\n exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;\\n a server hard cap β€” uploads buffer in memory), default `5242880` (5 MiB).\\n Checked at upload time only: lowering it never touches already-stored files.\\n- **`chatbot_history_turns`** β€” how many prior **messages** of a thread the\\n chatbot is given as context, `1`–`50` (default `10`). The unit is messages,\\n not exchanges: a question and its answer are two, so the default remembers\\n five question/answer pairs. Every one of them is re-sent on every reply, so\\n the number is both what the bot remembers and what each answer costs.\\n- **`max_chatbot_threads`** β€” how many chatbot threads one user may\\n keep, `1`–`500` (default `50`); at the cap the user deletes an old one\\n first. Storage protection, not a usage quota β€” that is the per-minute\\n message limit.\\n- **`max_chatbot_message_len`** β€” character limit on one chat message,\\n `100`–`8000` (default `4000`); the ceiling is a server hard cap, because\\n the message and its history must fit one bridge frame.\\n\\nA `PATCH` replaces only the fields it carries, each wholesale, and validation\\nis all-or-nothing. Concurrent edits are safe: each save applies only if the\\npolicy still matches the snapshot it merged from (retrying over the fresh row\\notherwise), so two managers patching different fields both land instead of\\nthe later write silently reverting the earlier one. Editing a list never\\nrewrites history: an exam keeps its retired kind, a roll-call row keeps its\\nretired status β€” only **new writes** are held to the current lists (which is\\nwhy grading an exam whose kind has left the list is refused).\\n\\nThe kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see \\"Food program: menus, dishes, bookings & the ledger\\").\\n\\nAcademic structure is data too. **Terms** (`/terms`) model whatever calendar\\nthe school runs β€” semester, trimester, quarter systems are just rows with a\\nname and a date range. Courses may link to one via `term_id` (nullable), and\\ndeleting a term is refused with a `409` while any course still links to it β€”\\nunlink those courses (`PATCH /courses/{id}` with `\\"term_id\\": null`) or delete\\nthem first, so the calendar never disappears under them. Term dates may lie in the past,\\ndeliberately: a school adopting the app mid-year backfills its calendar β€”\\nunlike exam/lesson/event times, which reject backdating.\\n\\nWhat stays fixed is deliberate too: the four roles, the `0`–`100` mark scale,\\nvalidation bounds, and the UTC time policy are invariants, not preferences\\n(rename role labels in the frontend if a school says \\"principal\\" instead of\\n\\"manager\\"). Deployment knobs (ports, rate limits, admin seed, CORS) remain\\nenvironment variables β€” the model is **one school per deployment**, which\\nkeeps every school's data physically isolated.", "source": "README.md"}, {"id": "food-program-menus-dishes-bookings-attendance-the-ledger", "title": "Food program: menus, dishes, bookings, attendance & the ledger", "body": "The school publishes **one menu per calendar day and meal slot** (`POST\\n/meals/menus`). Two shapes there are deliberate:\\n\\n- **`date` is text**, `YYYY-MM-DD`, not a timestamp. \\"One menu per day and\\n slot\\" is an equality test on the school's own day, and a midnight-in-millis\\n day is only unique for one timezone. Fixed-width and zero-padded, so the\\n text sorts chronologically β€” which is what the inclusive `?from=&to=` range\\n filter and the newest-day-first ordering are built on.\\n- **`slot` is a snapshot**, not a link into settings. It must be one of the\\n school's `meal_slots` (`GET /settings`) *when the menu is written*, and it\\n is stored as text β€” so retiring a slot later never rewrites a menu already\\n published under it. The slot's `serving_minute` is *not* snapshotted: the\\n booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any\\n menu was published for cannot be removed from the list (`409`), same\\n contract exam kinds have with graded exams.\\n\\nThe day+slot pair is unique: a second publish for the same meal answers `409`\\nβ€” edit the first one instead. Only `capacity` is patchable (`null` = uncapped)\\nβ€” `date` and `slot` are immutable, because a menu on another day is another\\nmenu.\\n\\n**Dishes** hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, then\\n`PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional\\ndescription (blank or `null` clears it), dietary `tags` drawn from the\\nschool's `dietary_tags` list β€” an unknown tag is a `400`, never a stored\\nstring β€” and a `price_minor`.\\n\\n### Dietary profiles and conflicts\\n\\nA student carries a **dietary profile**: a list of tags plus a free-text note\\nfor the kitchen, one row per student (the record key *is* the student's id).\\nThe tags come from the *same* `dietary_tags` list a dish is tagged from β€”\\nthere is deliberately no second vocabulary, because one shared list is exactly\\nwhat makes \\"is this dish a problem for this student\\" answerable as a set\\nintersection, without the backend knowing any nutrition.\\n\\nWriting it is **manager+** (`PATCH /meals/profiles/{user}`, first write\\ncreates the row). A student does *not* edit their own allergen list: it is a\\nsafety record the school keeps on their behalf, and a mistyped β€” or quietly\\nremoved β€” allergy would otherwise reach the kitchen with the school's\\nauthority behind it. Reading is `GET /meals/profiles/me`, or\\n`GET /meals/profiles/{user}` under the usual per-student gate (own id always,\\notherwise teacher+ or a parent link). A student who was never recorded reads\\nback as an *empty* profile rather than a `404` β€” \\"nothing known\\" is an answer.\\n\\nEvery dish a menu read returns therefore carries a **`conflicts`** list: the\\nintersection of that dish's `tags` with the **calling user's** profile tags.\\nIt is empty when the two do not overlap, and empty for every reader without a\\nprofile β€” a manager reading a menu sees `conflicts: []`, which is correct and\\nnot a bug (the field answers \\"may *I* eat this\\", and there is no \\"conflicts\\nfor student X\\" parameter). The caller's profile is loaded **once per request**,\\nnot per dish, so the menu list stays at its fixed query count no matter how\\nmany menus or dishes the page holds.\\n\\n**Money is minor units** (kuruş) as an integer, at every layer: `4550` is\\n45,50 β‚Ί. This API never speaks decimals or floats about money, so no rounding\\nis ever introduced by transport or by a client's JSON number parser.\\n\\nReads are open to every authenticated user β€” a student has to see what is\\nbeing served β€” and every write is manager+. Deleting a menu takes its dishes\\nwith it: a dish has no meaning apart from the menu it was published on.\\n\\n**Bookings** are seats on a published menu (`POST\\n/meals/menus/{id}/bookings`). One row per (menu, student), keyed by a\\ndeterministic composite id, so booking twice is the same seat and never a\\nsecond one. A **student books only for themselves**; a **parent books for a\\nstudent they hold a link to** β€” the one write a `parent_link` authorises, since\\npaying for lunch is a parent's job. Nobody else books through this route: a\\nteacher or manager ordering a child's lunch is a `403`.\\n\\n- **Cancelling is a status flip, not a delete** (`DELETE\\n /meals/bookings/{bid}` answers `200` with the flipped row): the row survives\\n as `cancelled` with a `cancelled_at` stamp, so a freed seat stays auditable\\n against the money it moved. Only `booked` rows count against `capacity`,\\n which is what genuinely frees the seat β€” and re-booking is the same row\\n flipped back. The call is **idempotent**: cancelling an already-cancelled\\n seat answers `200` with the row as it stands *and replays the refund*, so a\\n cancel cut short between the flip and the reversal (the tab closed, a proxy\\n timed out) is recovered by sending it again. Refusing it as a `409` β€” as it\\n once did β€” made that state permanent: no route could append the missing\\n reversal, and the student stayed billed for a seat they no longer held.\\n- **The capacity check is serialized in-process.** Counting rows and then\\n writing one is write-skew: SurrealDB does not conflict-check a cross-record\\n count against a concurrent insert, so 24 students racing for 3 seats would\\n otherwise all pass the count. The whole check-then-write runs under the same\\n lock a menu publish takes, and the cap is re-read inside it.\\n- **One cutoff closes both ends.** Within the school's\\n `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new\\n booking nor a cancellation lands (`409`) β€” the kitchen's headcount has to\\n settle at some point. `null` (the default) means no cutoff at all. The\\n cutoff is measured back from the menu's `date` **plus the slot's\\n `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served\\n at `720` closes at 10:00 UTC that morning, not at 22:00 the night before.\\n **That minute is UTC**: `date` carries no timezone and the backend stores no\\n school timezone β€” deliberately, it is a rejected feature β€” so a UTC+3 school\\n enters `540` (09:00 UTC) for a meal served at noon locally. A slot with no\\n `serving_minute` falls back to **midnight UTC starting the meal's day**, the\\n behaviour every booking had before the field existed; the booking is never\\n refused for want of a serving time.\\n- **The serving time is read live, not snapshotted onto the menu.** The cutoff\\n minutes are already read live, so freezing the other half of the same\\n deadline would make one policy edit apply and its twin not; a kitchen that\\n moves lunch an hour later wants today's menus to move with it. The menu\\n still snapshots the slot *name* (that is what keeps a retired slot's history\\n readable), so a menu whose slot has since left the list simply has no\\n serving time and falls back to midnight UTC.\\n- A menu somebody still holds a seat on **cannot be unpublished** (`409`) β€”\\n cancel the bookings first, so nothing is left pointing at a deleted meal.\\n\\n`GET /meals/bookings/me` is the caller's own list: the seats held *for* them\\nplus, for a parent, the seats held for every student they **currently** hold a\\nlink to β€” so a parent's list is their children's meals. The links are re-read\\non every call rather than trusted from the booking's `booked_by` stamp: an\\nunlinked parent stops seeing the child's seats at once, including the ones\\nthey booked and paid for themselves, exactly like every other parent read. `GET /meals/menus/{id}/bookings` is the kitchen's list for\\none menu (manager+), cancelled rows included so the changes are visible.\\n\\n### Meal attendance\\n\\nWhoever stands at the canteen door records who actually ate:\\n`POST /meals/menus/{id}/attendance` with `{student_id, status}`, teacher+ (a\\nstudent never marks, not even themselves). The status is the fixed pair\\n`served` / `missed` β€” deliberately **not** the school's editable\\n`attendance_statuses`, since a canteen line has no \\"late\\" or \\"excused\\", and one\\nlist meaning two things would let a school change one by editing the other.\\nOne row per (menu, student) keyed by a composite id, so a correction re-marks\\nthe same row instead of stacking a second one.\\n\\n**Attendance has zero billing effect.** Booking is the sole charge trigger, so\\na student who booked and did not eat still pays β€” the kitchen bought the food.\\nThere is no no-show penalty, no refund-on-missed, and no auto-reversal:\\nnothing under `meal_attendance` writes to the ledger. A walk-in with no live\\nbooking *can* be marked `served` (the record is operationally true) and is\\nlikewise not charged for it β€” charging there would be a ledger write. The\\ntarget only has to *exist*: a canteen also feeds staff, so any user may be\\nmarked, not only a student. A mark is a record of what happened, not a check\\nof who was entitled, and since it moves no money it costs nobody anything.\\n\\n`GET /meals/menus/{id}/attendance` is the per-menu list (teacher+), and\\n`GET /meals/attendance/{user}` is one student's history, narrowable with\\n`?from=&to=` β€” inclusive `YYYY-MM-DD` bounds compared against the *menu's*\\nday, a lexical compare that is chronological for that format. Same gate as the\\nbalance and the ledger: the caller's own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`meal_ledger`): one line per `charge`,\\n`credit`, or `reversal`, every field `READONLY`, and **no code path anywhere\\nthat updates or deletes one**. A ledger line that can be edited or dropped\\nsilently rewrites a student's financial history with no trace of the rewrite β€”\\nthis is the one genuinely irreversible part of the food program, so a mistake\\nis corrected by appending the opposing line, which leaves both the mistake and\\nthe correction visible.\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer.\\nA *negative* balance means the student owes the school; a positive one is\\nmoney on account. Amounts are stored positive; the sign lives in the `kind`.\\n\\n- **Booking is what charges, at a price snapshot.** The menu's dishes are\\n summed the moment the seat is taken and that number is frozen onto the\\n charge. Editing a dish's price afterwards moves no existing charge β€” what a\\n student owes is what the menu cost the day they booked. The price is\\n snapshotted *before* the seat is given, so a menu that cannot be charged\\n refuses the booking rather than leaving a booked-but-unbilled row (`400`,\\n when the dishes sum past 10 000 000). A free menu writes no line at all β€”\\n but the booking row records that it *was* free, so \\"free when taken\\" is\\n never confused with \\"not billed yet\\": pricing the menu afterwards leaves\\n every seat already taken on it free.\\n- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its\\n money move together under one in-process lock, and the ledger id is derived\\n from the seat plus how many times it has been taken β€” so eight simultaneous\\n `POST`s of one seat write one charge, a retried cancel refunds once, and a\\n write that failed halfway heals when the request is repeated. Booking the\\n same seat twice bills once because the *identity* is the same, never\\n because a scan happened to see the first charge in time.\\n- **Cancelling appends a `reversal`** for the charge's exact amount, with\\n `source` pointing at the charge it undoes. The charge row itself stays. A\\n cancel past the cutoff is already a `409`, so a reversal only ever follows a\\n legal cancel β€” and repeating a cancel replays the reversal, which is what\\n makes the refund recoverable rather than a one-shot the network can lose.\\n Re-booking afterwards is a **fresh** charge at the then-current price.\\n- **The price snapshot is taken under the booking lock**, and dish\\n create/edit/delete take that same lock. Taken outside it, a dish added\\n between the sum and the seat would be frozen onto the row as \\"the menu was\\n free then\\" β€” and nothing heals it, since a seat already held is returned\\n as-is, never re-priced.\\n- **A no-show still pays.** Meal attendance has zero billing effect β€” nothing\\n in the ledger reads or writes it. The seat was reserved and the food was\\n cooked; there is no no-show penalty and no no-show refund.\\n- **`POST /meals/credits` is admin-only**, not manager: writing down cash\\n received is the highest-trust action in the app. It appends a `credit` for a\\n student with a positive `amount_minor` (≀ 10 000 000), an optional `method`\\n (\\"cash\\", \\"havale\\", …) and `note`, and records the admin as `recorded_by`.\\n There is no payment gateway and no card data, ever. An over-credit is\\n corrected with a compensating line, never a fix-up.\\n\\n`GET /meals/balance/me` is the caller's own balance. `GET\\n/meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line\\nfirst) read a student's: your own id always passes, anyone else's needs\\nteacher+ or a `parent_link` to that student. A charge's `source` is the\\nbooking id it came from, a reversal's is the charge line it reverses, and a\\ncredit has none.", "source": "README.md"}, {"id": "payments-fee-plans-assignment-the-fee-ledger", "title": "Payments: fee plans, assignment & the fee ledger", "body": "School fees live in their own tables (`fee_plan`, `fee_plan_assignment`,\\n`payment_ledger`) and their own balance. **Meal money is separate** β€” two\\nledgers, two balances, and no route folds one into the other: what a family\\nowes the canteen and what it owes the school are different debts, and mixing\\nthem would make either statement unreadable.\\n\\nEvery write here is **manager+**. Reads are narrower than the other\\nper-student reports: the student themselves, a parent holding a live link to\\nthem, or manager+ β€” **a teacher gets a `403` on every `/payments` route**,\\nbecause what a family owes the school is not classroom information.\\n\\n### Fee plans and what turns them into money\\n\\nA **fee plan** (`POST /payments/plans`) is a name and 1 to 60 **installments**,\\neach `{amount_minor, due_at}` β€” minor units (kuruş) as an integer, and unix\\nmilliseconds. `due_at` **may be in the past**: a school adopting the app\\nmid-year assigns plans whose first installments were already due, so there is\\nno future-date rule here.\\n\\nWriting a plan bills nobody. **Assigning it does** (`POST\\n/payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call):\\nthat appends *every* installment as a `charge` line right away, each carrying\\nits own due date. There is no scheduler, no nightly sweep, and nothing that\\nwakes up when a date passes β€” the whole schedule is written once, and lateness\\nis read off it.\\n\\nAssignment is **replay-safe by identity**: the assignment row is keyed\\n(plan, student) and every charge it raises is keyed (plan, student,\\ninstallment), so re-assigning bills nothing a second time (that student comes\\nback `already_assigned`), and an assignment cut short after three of twelve\\ncharges landed completes itself when the call is simply repeated. Only\\nstudents carry a fee record, so any other target comes back `rejected` β€” one\\nbad id never loses the rest of the batch.\\n\\nA plan that has been assigned to anyone can no longer be edited or deleted\\n(`409`). Its charges are frozen copies of the installments as they stood, so\\nan edit would only make the plan and the money tell different stories β€” write\\na new plan instead.\\n\\nThat freeze is a **counter on the plan row** (`assignment_count`), incremented\\nin the *same transaction* as the assignment row it counts, and the edit and the\\ndelete are single-record conditional writes against it β€” the same shape as a\\nterm's `course_count`. It used to be a `SELECT` taken before the write, which a\\nconcurrent assign could land behind, leaving a plan edited *and* assigned, or\\ndeleted with a live assignment naming it. Now the two contend on one record: an\\nassign either freezes the plan first (and the edit or delete is a `409`) or\\narrives after it (and bills the edited plan β€” the installments a first\\nassignment charges are re-read from the *stored* plan at the instant it\\nfreezes, never from the copy the request first looked at). A plan deleted out\\nfrom under a running batch is `rejected` for that student on, in the same\\nper-student report as every other outcome β€” the students it already billed are\\nnever dropped from the answer. A `PATCH`\\ncarrying no field at all writes nothing, so it is not refused.\\n\\nBecause an assignment is never removed, the counter is only ever claimed and\\nnever released: once assigned, a plan stays frozen for good. Plans written\\nbefore the counter existed are seeded from their assignment rows at boot,\\nbefore the server accepts a request β€” an absent counter reads as zero, and a\\nzero would have re-opened every already-assigned plan on an existing volume.\\n\\n### The ledger\\n\\nThe money is an **append-only ledger** (`payment_ledger`), exactly like the\\nmeal one: every field `READONLY`, and **no code path anywhere that updates or\\ndeletes a line**. A ledger line that can be edited or dropped silently\\nrewrites a family's financial history with no trace of the rewrite, so a\\nmistake is corrected by appending the **opposing line**, which leaves both the\\nmistake and the correction visible.\\n\\nFour kinds, and the sign lives in the `kind` β€” amounts are always stored\\npositive:\\n\\n| Kind | Sign | What it records | `source` points at |\\n| ---------- | ---- | ------------------------------------------------ | ------------------ |\\n| `charge` | βˆ’1 | An installment billed by a plan assignment | the assignment |\\n| `credit` | +1 | Money received, against one named charge | the charge paid |\\n| `reversal` | +1 | A `charge` or `refund` entered in error, undone | the undone line |\\n| `refund` | βˆ’1 | Money handed back, against one named payment | the credit returned |\\n\\n**No balance is stored, anywhere.** It is always derived:\\n\\n```text\\nbalance = SUM(credit) + SUM(reversal) - SUM(charge) - SUM(refund)\\n```\\n\\nin **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer. A\\n*negative* balance means the family owes the school; a positive one is money on\\naccount.\\n\\n- **A payment names the charge it settles.** `POST /payments/credits` takes\\n `{charge_id, amount_minor, method?, note?}`: allocation is *recorded*, never\\n inferred from a balance, so a statement can say which installment is still\\n open rather than only how much is outstanding. **Partial payments are the\\n norm** β€” several credits accumulate against one charge.\\n- **A refund names the payment it returns.** `POST /payments/refunds` takes\\n `{credit_id, …}`, partials allowed, capped by what that credit was worth.\\n This is also the **only** way a mistaken credit is corrected: a credit is\\n never reversed, so money leaving the school is always spelled the one way.\\n- **A retry is not a second payment β€” when the client says so.** Both routes\\n take an optional `request_key` (`[A-Za-z0-9-]`, 1 to 64 characters β€” `_` is\\n the separator inside a ledger id, so a key may not carry one). With\\n one, the line is keyed `<charge>_k_<key>` (a refund: `<credit>_kr_<key>`), so\\n a client retrying after a network timeout gets **the line the first attempt\\n wrote**, not a second charge on the family β€” idempotence by identity, the\\n same rule that keeps a replayed assignment from billing twice, never a \\"has\\n this been recorded yet?\\" scan two concurrent requests can both walk past. The\\n replay is answered **before** the over-payment cap is consulted, so a payment\\n that filled its charge to the penny still replays as itself instead of coming\\n back \\"already paid in full\\". Sending that key again with a **different**\\n `amount_minor` or a different target is a `409`, never the stored line: that\\n is a client bug, and a `201` would bury it. Omit the key and nothing changes\\n from before β€” two identical posts are two payments, which is exactly what a\\n desk taking the same amount twice means.\\n- **A reversal only undoes a `charge` or a `refund`**, for its exact amount and\\n nothing else (`400` on any other kind). It is keyed `<line>_r`, so a line has\\n at most one reversal however often the call is retried, and the reversed line\\n itself stays on the record beside it.\\n- **A refund frees the charge's room.** The cap on a payment is folded over the\\n target's whole source subtree, so refunding a payment gives that charge its\\n room back and the charge **can be paid again** β€” and reversing that refund\\n takes the room back with it. Money that came back out is not money the school\\n still holds.\\n- **The over-payment cap is not the database's.** The `409` past a charge's or\\n a credit's worth is a cross-record fold, which SurrealDB cannot enforce on\\n its own; it holds because the backend is one process and the fold, and the\\n append it authorizes, are taken under one lock. Should an over-payment ever\\n be recorded anyway it is not a crisis: this is human data entry at an office\\n desk, the outcome is an over-paid charge that is plainly visible in the\\n statement, and it is undone by appending a refund. Both lines are true\\n records of money that really arrived β€” refusing them would be the worse lie.\\n- **There is no payment gateway and no card data, ever**, and none is planned:\\n nothing here talks to a bank, a PSP, or a card network. `method` is free text\\n (\\"cash\\", \\"havale\\", …) describing how money that already arrived was handed\\n over, and `note` is whatever the office needs to remember (a receipt number,\\n say).\\n\\n### Statements, balances and `overdue`\\n\\n`GET /payments/ledger/{user}` is the raw lines, newest first, paged.\\n`GET /payments/statement/me` and `/payments/statement/{user}` are the\\n**per-charge rollup** (its rows paged by the usual opt-in `?limit=&offset=`,\\nin an `entries: {items, total, limit, offset}` envelope): one row per charge with its plan, the installment's\\namount and due date, what it collected, what went back out, what is still\\noutstanding, whether the charge itself was reversed (such a charge owes\\nnothing), and whether it is **`overdue`** β€” still owed, and its `due_at` has\\npassed.\\n\\nAll of that is folded from the raw lines **on every request and stored\\nnowhere**, `overdue` included. Paging windows the *returned rows* only, after\\nthat fold: `balance_minor` β€” and every row's own arithmetic β€” is identical on\\nevery page, because it is read from all of the student's lines either way. There is no overdue flag, no sweep that sets\\none, and no stored rollup: a stored rollup is a second version of the truth,\\nand the ledger is the first. `GET /payments/balance/me` and\\n`/payments/balance/{user}` are the same fold reduced to one number.", "source": "README.md"}, {"id": "exam-modes-attempts-retakes-rejoin-live-monitoring", "title": "Exam modes, attempts, retakes, rejoin & live monitoring", "body": "Preparing an exam is slow work, so an exam can be created as a **draft**\\n(`draft: true`): only the course's managers see it (to students it's a `404`\\nthat might as well not exist β€” lists, direct reads, and attempts all hide\\nit), nobody can sit it, and grading it is a `409`. The teacher builds the\\nquestions in peace and publishes with `PATCH /exams/{id}` `{\\"draft\\": false}`.\\nAn exam can go back into hiding the same way β€” but only while it has **no\\nattempts and no results**; after that, re-drafting is a `409` (students never\\nlose sight of an exam they've sat or been graded on). Existing exams (and\\nthose created without the flag) are published from the start.\\n\\nSeparately from drafts, a published exam without a `mode` (all schedule\\nfields `null`) is **offline-graded** β€” a paper exam whose marks are entered\\nby hand; students see it and their marks, but attempts on it are a `409`\\n(\\"nothing to sit\\"). Making an exam sittable means giving it a `mode`, as one\\nconsistent unit (validated together on create and after every `PATCH` merge):\\n\\n- `mode: \\"sync\\"` + `starts_at` + `ends_at` β€” everyone sits inside one window;\\n every attempt's deadline is `ends_at`.\\n- `mode: \\"async\\"` + `starts_at` + `ends_at` + `duration_ms` β€” each student\\n starts anywhere inside the window and gets\\n `min(started_at + duration_ms, ends_at)` as their personal deadline.\\n- `mode: \\"open\\"` β€” no window at all: students sit anytime. `duration_ms` is\\n *optional* β€” set it for a per-attempt countdown (`started_at +\\n duration_ms`), omit it for unlimited time (the attempt only ends by\\n submission).\\n- `duration_ms` is 1 minute to 24 hours wherever it appears, and for `async`\\n cannot exceed the `starts_at`..`ends_at` window (equal to it is fine).\\n `ends_at` must be strictly after `starts_at`, and neither may be *set* in\\n the past β€” on create or `PATCH` (kept values are exempt, so a running exam\\n stays editable). All instants are the usual UTC unix-milliseconds, judged\\n only by the server clock (`GET /time` for sync).\\n\\nTwo per-exam policy knobs ride along, both **live-editable** at any point:\\n\\n- `max_attempts` (default `1`, `0` = unlimited) β€” how many sittings each\\n student gets. Raising it mid-exam grants retakes on the spot; lowering it\\n never kills a running attempt, it only blocks future starts.\\n- `allow_rejoin` (default `true`) β€” whether a student who *left the exam room*\\n may come back in and keep answering (see the exam-room section).\\n- `allow_review` (default `false`) β€” opt-in door to the student self-review\\n reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A\\n student may review only when this is on **and** the teacher has marked them\\n (an `ExamResult` row exists); own-scoped, so no student reads another's sheet.\\n\\nA student **sits** an exam through attempts (sitting 1, 2, … β€” each row id is\\nthe composite `exam_user[_seq]` key, so a sitting exists at most once by\\nconstruction):\\n\\n- `POST /exams/{id}/attempt` starts, resumes, or retakes (students only β€”\\n staff never sit; enrolled; window open where one exists β€” `open` exams start\\n anytime). While the latest\\n sitting runs, re-posting returns it unchanged (`200`, not `201`):\\n reconnecting never resets the clock. Once it is submitted or expired,\\n re-posting mints the next sitting (`201`) **from a blank answer sheet** β€”\\n the previous sitting's answers are wiped β€” until `max_attempts` is spent\\n (`409` after that). Starting is the live-attendance signal.\\n- `GET /exams/{id}/attempt` is the student's exam screen: the latest sitting's\\n `status` (`in_progress` | `submitted` | `expired`), `attempt` (its number),\\n `attempts_used`/`max_attempts`, `deadline`/`remaining_ms` (`null` for an\\n untimed open exam), `left_at`, own `mark` once graded, and the server `now`.\\n- `POST /exams/{id}/attempt/finish` submits. After the deadline the attempt is\\n `expired` β€” a valid terminal state (the student used their full time), and\\n finishing answers `409`. Grading stays per exam+user (one mark), whatever\\n the sitting count β€” the sheet a grader sees is always the latest sitting's.\\n\\nDeadlines are **recomputed from the exam's current schedule on every read**,\\nnever stored: a teacher who `PATCH`es `ends_at` (or a `duration_ms`)\\nwhile the exam runs moves every running deadline instantly. What's frozen once\\nanyone has started is only `mode` (including back to unscheduled) β€” swapping\\nthe deadline rules mid-sitting would be a different exam (`409`).\\n\\nThe course's manager (its creator, or manager+) watches it all live:\\n`GET /exams/{id}/live` returns one snapshot β€”\\nthe enrolled roster joined with attempts and marks (`not_started` | `absent` |\\n`in_progress` | `submitted` | `expired`, per-student `attempt` /\\n`attempts_used` / `left_at` / `deadline` / `remaining_ms` / `mark`, always the\\nlatest sitting) plus summary counts, all judged at a single `now`. Once the\\nwindow closes, `not_started` hardens into `absent` β€” the no-shows, flagged\\nright in the roster (open exams have no window, so never an `absent`). The\\nflag is informational: an absent student still has no mark until the teacher\\nrecords one through `POST /exams/{id}/results`. Poll `GET /exams/{id}/live` to\\nkeep a monitor current β€” attendance, ticking clocks, submissions, and marks all\\nride in each snapshot.\\n\\nDeleting an exam (or its course) cascades attempts, questions, answers, and\\nquestion + answer images (blobs included) along with results; unenrolling mid-exam\\nhides the student from the monitor roster but keeps the attempt and mark\\nrows, mirroring the marks report.\\n\\n> **Upgrading a pre-course database**: `exam` rows created before courses\\n> existed lack the now-required `course` field and will fail to deserialize.\\n> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data,\\n> backfill manually with the SurrealDB CLI (server stopped), e.g.\\n> `UPDATE exam SET course = course:<id> WHERE course = NONE;`\\n> after creating a course to attach them to.\\n>\\n> **Upgrading to the attempts/rejoin build needs nothing manual**: the boot\\n> migration backfills `max_attempts = 1`, `allow_rejoin = true`, and attempt\\n> `seq = 1` on existing rows, and swaps the single-attempt unique index for\\n> the per-sitting one. Pre-upgrade attempts keep their record ids and count\\n> as sitting #1.\\n>\\n> **Upgrading to the kind-weight build is a clean break**: weights moved off\\n> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with\\n> no data migration. A database from an older build has string kinds and a\\n> per-exam `weight` column the code no longer understands β€” delete\\n> `./data/hezarfen.db` and reboot.", "source": "README.md"}, {"id": "taking-an-exam-questions-answers-the-exam-room", "title": "Taking an exam: questions, answers & the exam room", "body": "Teachers author a question list per exam; students answer inside their\\nattempt, autosaved as they go; choice questions are machine-checked as a\\n**suggestion** β€” the final mark stays a human call through the existing\\n`POST /exams/{id}/results`.\\n\\n**Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`,\\ncourse-management rights): each has a mandatory `subject_id` (one of the\\ncourse's subjects, `GET /courses/{id}/subjects` β€” the topic the question\\nbelongs to), `text` (≀ 2000 chars), `points` `1`–`100`\\n(its share of the auto-score), and a `kind`:\\n\\n- `kind: \\"choice\\"` β€” carries `choices` (2–10 options, each ≀ 500 chars) and\\n `correct`, the zero-based index of the right option. Auto-scorable.\\n- `kind: \\"text\\"` β€” free text, judged by the grader; carries neither.\\n\\nThe kind bundle is validated as a unit (create and after every `PATCH` merge):\\nswitching a question to `text` needs explicit `\\"choices\\": null, \\"correct\\":\\nnull`, switching to `choice` must bring both along. Presentation order is\\ncreation order. The whole list **freezes once anyone has started an attempt**\\n(`409` on create/edit/delete) β€” editing questions under a sitting student\\nwould fork what \\"the exam\\" means. Deleting a question cascades its answers\\nand images.\\n\\n**Question images**: any question may carry one **illustration** (`POST\\n/exams/{id}/questions/{qid}/image` β€” the map the prompt asks about, on\\n`choice` and `text` questions alike), and each option of a `choice` question\\nmay carry a **picture** of its own (`POST .../choices/{choice_id}/image` β€” so\\nthe options themselves can be images: four map crops, pick the right one).\\nUploads are `multipart/form-data` with a single `file` part, capped by the\\nschool's `max_file_bytes`; the declared content type must be `image/png`,\\n`image/jpeg`, `image/webp`, or `image/gif` (rasters only β€” SVG can script,\\nand these bytes render inline for the whole class). One image per slot:\\nre-uploading replaces, `DELETE` on the same paths removes, and replacing a\\nquestion's `choices` list drops all its option pictures (the illustration\\nstays β€” re-upload against the new list). Image writes follow question\\nauthoring exactly: course-management rights, frozen once attempts exist.\\nBoth question views (`GET /exams/{id}/questions` and the sitting view)\\nembed the metadata as `image: {content_type, size} | null` and\\n`choice_images: [...|null]` aligned with `choices`; the bytes come from the\\n`GET` endpoints above β€” course managers anytime, students through the same\\nenrollment + started-attempt wall as the sitting view (no early peek at the\\npictures either), served with `Cache-Control: private, no-store`.\\n\\n**Answering** (student, attempt `in_progress`, deadline judged by the server\\nclock on every save):\\n\\n- `GET /exams/{id}/attempt/questions` β€” the sitting view. Requires\\n enrollment (`403` β€” the questions are course content, so leaving the course\\n closes them) and an attempt (`404` before `POST /exams/{id}/attempt`; also\\n the anti-peek gate), never contains `correct`, and embeds the caller's own\\n saved answer per question (`{selected, text, updated_at}` or `null`). Still\\n readable after submitting/expiry, for review.\\n- `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` β€” an\\n upsert: one row per question+user, re-answering overwrites. The payload must\\n match the question's kind (`selected` indexing a choice, or `text`\\n ≀ 10 000 chars β€” empty clears the draft); mismatches are `400`s. Requires\\n the student role and enrollment (`403`): a promotion out of `student` or an\\n unenrollment mid-exam closes the sheet (the exam room's door checks,\\n re-applied to every save β€” finishing stays open). Once the\\n attempt is submitted or past its deadline every save is a `409` β€” likewise\\n while the student has left the exam room with `allow_rejoin` off; answers\\n saved in time survive untouched for grading. Each sitting keeps its own\\n answers, drawings, and mark, keyed by the attempt's `seq` β€” a retake starts\\n from a blank sheet without erasing the prior one, so the full per-attempt\\n history stays readable (see the grading view).\\n\\n**Answer images**: the student side mirrors the teacher's question images. A\\nstudent may attach one **drawing** to any question in their attempt β€” a\\nsketched answer or worked steps β€” via `POST\\n/exams/{id}/attempt/answers/{qid}/image` (`multipart/form-data`, one `file`\\npart, the same raster allowlist and `max_file_bytes` cap as question images).\\nOne image per question: re-uploading replaces, `DELETE` on the same path\\nremoves. Writes ride the exact `POST /exams/{id}/attempt/answers` gate β€” the\\nstudent role, enrollment, an `in_progress` attempt, and the rejoin door β€” so a\\ndrawing is just another autosaved answer; a drawing-only answer (nothing\\ntyped) still surfaces, and clearing it grooms the empty row away. The bytes\\ncome from `GET` on the same path (the caller's own, behind the sitting-view\\nwall) and, for the grader, `GET /exams/{id}/attempts/{user}/answers/{qid}/image`\\n(course-management rights); both serve inline with `Cache-Control: private,\\nno-store`. The metadata rides the answer as `answer_image: {content_type,\\nsize} | null` on both the sitting view and the grading sheet. To the backend\\nit is a normal raster PNG; the frontend piggybacks its editable stroke data in\\na PNG `tEXt` chunk, opaque here β€” stored on disk under `Config::files_path`\\nby a ULID, metadata in the `answer_image` table, structurally identical to\\nquestion images.\\n\\n**Grading view** (course-management rights): `GET /exams/{id}/attempts/{user}/answers` returns\\nthe student's **latest** sitting's sheet β€” every saved answer with `is_correct`\\n(`true`/`false` for choice, `null` for text: that's the grader's call) plus\\n`auto_score: {earned, possible}` summing the choice questions' points. It is a\\nsuggestion to read while grading, never written anywhere.\\n\\n**Per-attempt history** (course-management rights): prior sittings stay\\nreadable. `GET /exams/{id}/students/{user}/attempts` lists the sitting numbers\\na student has (every `seq` carrying answers or a mark, ascending);\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers` is the grading sheet\\nfor one of them (drawing bytes at\\n`GET /exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image`); and\\n`GET /exams/{id}/students/{user}/marks` is the full per-sitting mark history,\\noldest first. Grading (`POST /exams/{id}/results`) always lands on the current\\nsitting, and the latest seq is the grade-of-record β€” the roster, report, and\\nstatistics reads all show it. Every result payload carries its `seq`, so a mark\\nlinks straight to that sitting's answer sheet β€” without it a marked retake's\\nanswers would be unreachable from the mark.\\n\\n**The exam room (WebSocket)** β€” `GET /exams/{id}/attempt/ws`, cookie-authed\\nlike everything else; REST above remains the full fallback. Gates run before\\nthe upgrade: unknown or draft exam `404`, unscheduled (no mode) `409`, not a\\nstudent `403`, not enrolled `403`, no attempt yet `404` (start it first),\\nsubmitted/expired `409`, left while rejoin is closed `409`. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| server β†’ | `{\\"type\\":\\"state\\", status, attempt, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save |\\n| client β†’ | `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"selected\\":1}` or `{\\"type\\":\\"answer\\", \\"question_id\\":\\"…\\", \\"text\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` |\\n| server β†’ | `{\\"type\\":\\"saved\\", question_id, updated_at, client_seq?}` β€” the autosave ack |\\n| client β†’ | `{\\"type\\":\\"finish\\"}` β€” submit the attempt |\\n| server β†’ | `{\\"type\\":\\"finished\\", finished_at}`, then Close |\\n| server β†’ | `{\\"type\\":\\"expired\\"}`, then Close β€” a tick noticed the deadline |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", message, question_id?, client_seq?}` β€” bad JSON, wrong kind, deadline, … |\\n\\nAn `answer` may carry a `client_seq`: any number the client picks, echoed verbatim on\\nthat message's `saved` or `error` and on nothing else. The server never reads\\nit β€” no uniqueness, no ordering, no dedupe, all the client's business β€” and\\nomits the key entirely when the request omitted it, so leaving it out keeps\\ntoday's frames byte for byte. It exists because `question_id` is not an\\nidentity: save a question, time out, save it again, and two sends are\\noutstanding for the same id β€” the first reply would settle the second and the\\nUI would claim \\"Saved\\" for an answer the server never took. `question_id` on\\nan `error` is the separate, orthogonal question: whether the failure belongs\\nto that one question (payload or question) or to the room, in which case every\\nsave in flight is equally refused. An error can carry `client_seq` without\\n`question_id`.\\n\\nEvery tick and every save re-read the exam, so a mid-exam `ends_at` extension\\nmoves the room's countdown on the next tick, and no stale socket can write\\npast its real deadline β€” the socket shares the exact REST write path. Each\\nroom acts only on the sitting it was opened for: once that sitting is over,\\nits `answer`/`finish` are `error` frames, so a lingering socket can never\\nscribble on (or instantly submit) a retake started elsewhere.\\n\\nThe room is also the presence signal behind the **rejoin door**: connecting\\nclears the attempt's `left_at`, and the *last* socket of the sitting to close\\nwhile it is still running stamps it (visible on the live monitor β€” \\"left the\\nroom three minutes ago\\" at a glance). Closing one of two tabs is not leaving,\\nand a lingering socket from an already-finished sitting never marks a later\\nretake as left β€” each room is bound to the sitting it was opened for. With the exam's `allow_rejoin` off, a stamped\\n`left_at` refuses re-entry *and* any further saves, over the socket or REST,\\nuntil the teacher flips the door back open (`PATCH /exams/{id}\\n{\\"allow_rejoin\\": true}` β€” live, like the times). Finishing stays allowed: a\\nlocked-out student can always submit what they saved. The timer never pauses\\neither way. Students who only ever use REST never trip the door β€” the room is\\nwhat marks leaving.\\nExample client:\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/exams/${id}/attempt/ws`);\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"state\\") renderCountdown(m.remaining_ms, m.answered, m.question_count);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.question_id);\\n};\\nlet clientSeq = 0;\\nconst save = (question_id, selected) =>\\n ws.send(JSON.stringify({ type: \\"answer\\", question_id, selected, client_seq: ++clientSeq }));\\n```\\n\\nThe live monitor rides along: each roster row now carries `answered` and\\n`last_activity` (latest save instant), and the snapshot a top-level\\n`question_count`, so \\"stuck at 3/10 for five minutes\\" is visible at a glance.\\nThe student's own `GET /exams/{id}/attempt` echoes the same\\n`answered`/`question_count` pair.", "source": "README.md"}, {"id": "question-bank", "title": "Question bank", "body": "Writing good questions is slow, and the same one gets asked year after year, so\\nthe school keeps a reusable **question bank**. A bank question is an\\n`ExamQuestion` cut loose from any exam: it has the same shape (`subject_id`,\\n`text`, `kind`, `points`, and β€” for a `choice` β€” `choices` + `correct`), the\\nsame image slots (one illustration, plus a picture per option), and the same\\nnewtype validation, but it carries **no exam link**. Because nothing sits it,\\na bank row **never freezes** β€” its owner can edit or delete it forever.\\n\\n`POST /bank-questions` (teacher+) saves one, stamping the caller as its\\n**owner**. `subject_id` is origin metadata, but it must **exist** β€” an unknown\\nsubject is a `400` (create and PATCH alike). The reverse guard does **not**\\nhold here, unlike exam questions and homework: a template never blocks a\\nsubject delete, which simply clears `subject` off every template that carried\\nit (only a template's owner may re-tag it, so a `409` would be one a manager\\ncould never clear β€” and a private template raising it would leak its\\nexistence). Reads are school-wide: `GET /bank-questions` lists the\\nwhole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` β€” or\\n`?owner=me` β€” by owner) and `GET /bank-questions/{bid}` fetches one with\\n`correct` included β€” any teacher+ can browse and reuse what any colleague\\nbanked. Each response carries its **image metadata** β€” an `image` meta for the\\nillustration and a `choice_images` array aligned with `choices` (per-slot\\n`{content_type, size}`, `null` where a slot has no picture) β€” the same shape an\\nexam question's response uses; the bytes still come from the image endpoints.\\nMutation is **owner-only** (an `admin` bypasses): `PATCH /bank-questions/{bid}`\\nrevalidates the kind bundle as a unit, `DELETE /bank-questions/{bid}` drops the\\nrow and its image blobs. The illustration and option pictures work exactly like\\nan exam question's β€” `POST|GET|DELETE /bank-questions/{bid}/image` and\\n`…/choices/{choice_id}/image`, `multipart/form-data` with one `file` part, raster\\nonly (`png`/`jpeg`/`webp`/`gif`), ≀ `max_file_bytes` β€” reads school-wide,\\nwrites owner-only.\\n\\nThe bank feeds exams by **copying**, never linking. `POST\\n/exams/{id}/questions/from-bank/{bid}` instantiates a bank question into the\\nexam: it mints a **fresh** exam-scoped question (new id, its own answer rows,\\nits image blobs copied to new files), so later edits on either side never\\ntouch the other. The subject on the bank row is origin metadata only β€” the\\ncall takes its own `{subject_id}`, re-checked against the target course's\\nsubjects (`400` on a cross-course subject), and instantiating into an exam\\nthat already has attempts is a `409`, the same freeze that guards hand-authored\\nquestions. The instantiated question records the template it came from in\\n`source_bank`. The reverse, `POST /exams/{id}/questions/{qid}/to-bank`, copies\\nan existing exam question **into** the bank (new detached row, images copied to\\nnew files, owner = caller); the source question is left untouched, and the new\\ntemplate records the origin exam in `source_exam`. Both provenance fields are\\nnullable β€” a hand-authored question or template carries `null` β€” and one-way\\nmetadata (the copies stay fully detached). All bank routes are course-agnostic\\nand require teacher+.\\n\\nCopying means a template edit never reaches the copies, so there is one escape\\nhatch for that divergence: `POST /exams/{id}/questions/{qid}/refresh-from-bank`\\nre-copies the template's *current* content over one exam question β€” text,\\npoints, kind, choices (adopting the **template's** choice ids, so the option\\npictures re-land on the right options), `correct`, the illustration and the\\noption pictures. The question keeps its own id, its exam, its `subject` (the\\ntemplate's is unrelated origin metadata) and its provenance links; anything\\nedited on the copy is overwritten, deliberately. A question with no\\n`source_bank` β€” hand-authored, or its template deleted β€” is a `400`, a template\\nthe caller may not see is a `404` (never a 403), and the usual freeze applies:\\nonce any attempt exists, `409`. Every source blob is read before anything is\\nwritten, so a missing blob is a `500` with the question untouched rather than a\\nhalf-applied refresh.", "source": "README.md"}, {"id": "homework", "title": "Homework", "body": "A course hands out **homework**: `POST /courses/{id}/homework` with a title,\\nan optional description, a **required subject** (one of the course's own β€” and\\nthe same delete guard questions have: a subject with homework refuses deletion\\nwith a `409` until the homework is re-tagged via `PATCH /homework/{id}` or\\ndeleted), and a **required `due_at`** that must not lie in the past (same 60s\\ngrace as every schedule field; late *submissions* are fine β€” a late\\n*assignment* is not).\\n\\n**Audience.** By default the whole course, resolved live: whoever is enrolled\\n*when they act* β€” a student enrolled after the assignment sees and submits it\\nlike everyone else. `assigned` (at create or PATCH) instead pins a named\\nsubset of currently enrolled students (at most 200). The unnamed must not even\\nlearn a subset exists: lists omit it, and direct reads and submits answer\\n`404` β€” the same no-leak a hidden exam draft gets. Narrowing the subset later\\nis refused with a `409` that names the blockers while any submission or grade\\nbelongs to a student the new list would strand.\\n\\n**Submitting.** Students only β€” staff and parents never submit β€” enrolled and\\nin the audience, re-checked on every write. A submission is optional text plus\\nup to **10 files of any content type** (each ≀ the school's\\n`max_file_bytes`): text is replaced whole on each `POST` (omit to clear),\\nfiles are added and removed one by one, and a file upload with no prior\\nsubmission auto-creates an empty one, so a photo-only homework is a single\\nrequest. Two stamps tell the lateness story: `submitted_at` pins the **first**\\nhand-in forever, `updated_at` moves on every text edit and file add/remove,\\nand `late` is **computed on read** (`updated_at > due_at`), never stored β€” so\\ntouching work after the deadline flips it late, and a `due_at` edit re-grades\\nlateness for free. Late submissions are always accepted, only flagged. File\\nbytes always come back as a forced download (`Content-Disposition:\\nattachment`): homework accepts any content type, so rendering an uploaded\\nHTML/SVG inline would run it in the viewer's session.\\n\\n**Grading.** A course manager records a status β€” `done`, `incomplete`, or\\n`missing` β€” plus an optional 0–100 `mark` per student\\n(`POST /homework/{id}/results`, one upsert row per homework+student; the\\nexam walls apply: live students only, enrolled, in the audience, never the\\ngrader themselves). A stored grade **freezes** that submission β€” text edits,\\nfile changes, withdrawal all `409` β€” until\\n`DELETE /homework/{id}/results/{user}` removes it and reopens editing.\\nGrading before the due date, or before anything was submitted, is allowed β€”\\nthe latter is how never-handed-in work gets its `missing` verdict, and\\n`GET /homework/{id}/result` is where its student reads it (their submission\\nendpoints have nothing to show). The teacher-set `missing` **status** is a\\ndeliberate verdict; the roster and the report *also* compute a `missing`\\n**flag** for anyone unsubmitted past due β€” the two are independent. Homework\\nmarks stay out of `/marks`: the weighted course average remains exam-only\\n(the exam *kind* named `homework` still lives there), so nothing\\ndouble-counts.\\n\\n**Roster & report.** `GET /homework/{id}/submissions` (course manager) is the\\ngrading table: one row per audience student β€” plus any straggler outside the\\naudience who still owns a submission or grade (an unenrollment, a promotion,\\nor an audience change leaves work behind; it stays visible, flagged\\n`unenrolled`, though a stale student can neither submit nor be graded).\\n`GET /homework/report/{user}` is the fourth observer read beside marks,\\nattendance, and pomodoro: teacher+ (an exactly-teacher caller narrowed to the\\ncourses they manage), or a **parent linked** to the student β€” per-homework\\nrows of submitted/late/missing plus the grade; statuses and marks only,\\n**never the files**.\\n\\nEvery delete collects its garbage: withdrawing a submission, deleting a\\nhomework, and deleting the whole course each cascade the rows (submissions,\\nfiles, grades) and unlink the file blobs from disk. Role changes never sweep\\nhomework rows: a promoted student's work stays readable on the roster behind\\nthe `unenrolled` flag, while the live-role gates refuse fresh edits and\\ngrades.", "source": "README.md"}, {"id": "lesson-sessions-roll-call-the-work-log-pomodoro-attendance-reports", "title": "Lesson sessions, roll call, the work log, pomodoro & attendance reports", "body": "Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session\\nbelongs to a course and carries a `teacher` (defaults to whoever creates it;\\nany explicit `teacher_id` must hold teacher+ β€” a student cannot teach), an\\noptional `topic`, a required `starts_at`, and an optional `ends_at` (when both\\nare set, `ends_at` must not precede `starts_at`; neither may be set in the\\npast). Sessions are created, edited,\\nand deleted under course-management rights, exactly like exams; session lists\\nare ordered by `starts_at` (a timetable, not a creation log).\\n\\n**Roll call** (`/sessions/{id}/attendance`) deliberately differs from event\\nattendance: students never mark themselves. The session's teacher or a course\\nmanager marks **enrolled** students β€” only students attend classes, so a\\nnon-student or unenrolled target is a `400` β€” and the\\n**session teacher's own** presence row can only be written or removed by\\nmanager+ β€” staff presence is management's call, so a teacher can't declare\\nthemselves present. Listing the roll call follows the same rights as taking\\nit; a student reads their own tallies through the attendance report instead.\\nRe-marking overwrites: one row per session+user, by construction. Deleting a\\nsession (or its course) cascades its roll-call rows.\\n\\nThe **work log** (`/work`) is the staff timesheet, for teachers and above.\\n`POST /work/check-in` opens a stint and `POST /work/check-out` closes it, both\\nstamped by the **server clock** β€” a request never carries an instant, so a\\nwrong device clock (or a crafted request) can't forge presence. At most one\\nopen stint per user holds atomically: double check-ins and check-outs without\\nan open stint answer `409`, and a reconnecting double-click can't reset a\\nrunning clock. `GET /work/me` lists your stints newest-first (the open one has\\n`check_out: null`, closed ones a convenience `duration_ms`); manager+ reads\\nanyone's log (`GET /work/{user}`), corrects a **closed** stint's instants\\n(`PATCH /work/entries/{id}`, `409` while open β€” check out or delete instead),\\nand deletes entries.\\n\\nThe **pomodoro log** (`/pomodoro`) is the students' study-time twin of the\\nwork log. The frontend owns the timer β€” the visible countdown, the work/break\\nrhythm, the durations; the backend stores no timing policy and records only\\n**focus stints**, stamped by the server clock exactly like work stints.\\n`POST /pomodoro/start` opens a session and β€” unlike a work check-in β€” always\\nsucceeds for a student: a dangling unfinished session (a laptop closed\\nmid-timer) is **discarded and replaced**, because it recorded no focus and\\nmust not lock the student out of the next one. `POST /pomodoro/finish` closes\\nthe running session (`409` when nothing runs); breaks are never reported.\\nLogs return the usual page envelope plus `total_focus_ms`, the unpaged sum of\\nevery finished session's duration: `GET /pomodoro/me` for your own,\\n`GET /pomodoro/{user}` for teacher+ (study oversight). Only students start\\nsessions β€” pomodoro is the study tool, the work log is the staff timesheet.\\n\\n**Attendance reports** mirror the marks report: `GET /attendance/me` for any\\nlogged-in user, `GET /attendance/{user}` for teacher+ β€” narrowed to the\\ncourses the caller manages (manager+ sees every course; event tallies are\\nschool-wide either way). The report tallies event attendance and lesson roll\\ncall separately, plus a per-course breakdown:\\n\\n```json\\n{\\n \\"user\\": \\"01J…\\",\\n \\"events\\": { \\"present\\": 4, \\"absent\\": 1, \\"late\\": 0, \\"excused\\": 1, \\"total\\": 6, \\"rate\\": 0.8 },\\n \\"sessions\\": { \\"present\\": 9, \\"absent\\": 2, \\"late\\": 1, \\"excused\\": 0, \\"total\\": 12, \\"rate\\": 0.8333 },\\n \\"courses\\": [ { \\"course\\": { \\"id\\": \\"01J…\\", \\"title\\": \\"algebra\\", … }, \\"counts\\": { … } } ]\\n}\\n```\\n\\n`rate = (present + late) / (present + absent + late)`: arriving late still\\ncounts as attending, and an excused absence counts against no one (`rate` is\\n`null` when every row is excused, or there are none). Per-course blocks appear\\nfor every course the user has roll-call rows in β€” attendance is a historical\\nrecord, so unenrolling hides marks from the marks report but never hides an\\nabsence.", "source": "README.md"}, {"id": "quick-tour-curl", "title": "Quick tour (curl)", "body": "```sh\\nBASE=http://127.0.0.1:8080\\nJAR=/tmp/hz.cookies\\n\\ncurl -s $BASE/auth/register -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\ncurl -s -c $JAR $BASE/auth/login -H 'content-type: application/json' \\\\\\n -d '{\\"username\\":\\"ali\\",\\"password\\":\\"secret1\\"}'\\n\\n# notes\\ncurl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"first\\",\\"content\\":\\"hello\\"}'\\ncurl -s -b $JAR $BASE/notes\\n\\n# note files (multipart; -F sets filename + content type from the file)\\nNO=$(curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"with file\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nFI=$(curl -s -b $JAR $BASE/notes/$NO/files -F 'file=@plan.pdf' \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/notes/$NO/files # list metadata\\ncurl -s -b $JAR -OJ $BASE/notes/$NO/files/$FI # download, original filename\\n\\n# events + attendance\\n# Creating events needs teacher+; grant it first (see \\"Bootstrapping\\" above β€”\\n# e.g. UPDATE user SET role='teacher' WHERE username='ali'), else this is 403.\\nEV=$(curl -s -b $JAR $BASE/events -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"standup\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json' \\\\\\n -d '{\\"status\\":\\"present\\"}'\\ncurl -s -b $JAR $BASE/events/$EV/attendance\\n\\n# courses + weighted marks (as a teacher)\\n# optional, manager+: weigh midterms triple β€” school policy, per kind\\ncurl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \\\\\\n -d '{\\"exam_kinds\\":[{\\"name\\":\\"midterm\\",\\"weight\\":3},{\\"name\\":\\"quiz\\",\\"weight\\":1}]}'\\n# find the student to enroll (here: a registered user \\"veli\\"): fragment\\n# search over username/name, role-narrowed (teacher+)\\nSID=$(curl -s -b $JAR \\"$BASE/users/search?q=vel&role=student\\" \\\\\\n | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\nCO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"algebra\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\nEX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \\\\\\n -d '{\\"title\\":\\"midterm\\",\\"kind\\":\\"midterm\\"}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"mark\\\\\\":90,\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\ncurl -s -b $JAR $BASE/exams/$EX/statistics\\n\\n# lesson sessions + roll call (course manager creates; the session's teacher\\n# or a course manager marks enrolled students)\\nSE=$(curl -s -b $JAR $BASE/courses/$CO/sessions -H 'content-type: application/json' \\\\\\n -d '{\\"topic\\":\\"limits\\",\\"starts_at\\":1900000000000}' | grep -o '\\"id\\":\\"[^\\"]*\\"' | head -1 | cut -d'\\"' -f4)\\ncurl -s -b $JAR $BASE/sessions/$SE/attendance -H 'content-type: application/json' \\\\\\n -d \\"{\\\\\\"status\\\\\\":\\\\\\"present\\\\\\",\\\\\\"user_id\\\\\\":\\\\\\"$SID\\\\\\"}\\"\\n\\n# staff work log (instants are server-stamped)\\ncurl -s -b $JAR -X POST $BASE/work/check-in\\ncurl -s -b $JAR -X POST $BASE/work/check-out\\ncurl -s -b $JAR $BASE/work/me\\n\\n# ...and as the student:\\ncurl -s -b $STUDENT_JAR $BASE/marks/me\\ncurl -s -b $STUDENT_JAR $BASE/attendance/me\\n# pomodoro: start when the timer starts, finish when it rings\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start\\ncurl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/finish\\ncurl -s -b $STUDENT_JAR $BASE/pomodoro/me\\n```", "source": "README.md"}, {"id": "ai-bridge-quic", "title": "AI bridge (QUIC)", "body": "The AI features are separate projects β€” separate repos, separate processes,\\nprobably not Rust. They talk to this backend over a QUIC bridge rather than\\nHTTP.\\n\\nWhy QUIC: stream multiplexing lives in the transport. Each request rides its\\nown **bidirectional stream** on the service's single long-lived connection, so\\nconcurrent requests need no correlation-id bookkeeping and never head-of-line\\nblock each other β€” a 30-second inference on one stream does not delay the\\nanswer on another. Connection setup (and the TLS handshake) happens once, not\\nper request.\\n\\n**The backend listens; the services dial in.** A service can therefore sit\\nbehind NAT, restart without the backend knowing its address, and scale out by\\nopening a second connection β€” each connection is an independent worker.\\n\\nOff by default: with `AI_QUIC_ADDR` unset the bridge never starts and the rest\\nof the API is unaffected.\\n\\n### Handshake\\n\\nThe service connects with ALPN `hab/1`, then opens the **control stream** (the\\nfirst client-initiated bidi stream) and writes one `Hello`:\\n\\n```json\\n{ \\"protocol\\": \\"hab/1\\", \\"service\\": \\"ocr\\", \\"capabilities\\": [\\"ocr.extract\\"],\\n \\"token\\": \\"<AI_SHARED_TOKEN>\\", \\"max_concurrent\\": 8 }\\n```\\n\\nThe backend answers one `Greeting` and leaves the stream open:\\n\\n```json\\n{ \\"type\\": \\"welcome\\", \\"worker_id\\": \\"01J...\\", \\"protocol\\": \\"hab/1\\" }\\n{ \\"type\\": \\"rejected\\", \\"code\\": \\"unauthorized\\", \\"message\\": \\"invalid token\\" }\\n```\\n\\nReject codes: `unsupported_protocol`, `unauthorized`, `no_capabilities`,\\n`malformed`. The token is compared in constant time; the handshake must\\ncomplete within 10s.\\n\\nThe control stream carries no further frames. **Its closure is the goodbye** β€”\\nthere is no heartbeat. A service that dies silently is dropped by the QUIC idle\\ntimeout (30s, with a 10s keepalive) and deregistered then.\\n\\n`max_concurrent` is advisory and clamped to `1..=64` (default 8). Requests\\nbeyond it are refused with \\"busy\\" rather than queued.\\n\\n### Requests\\n\\nFor each request the **backend** opens a bidi stream, writes one `Request`,\\nfinishes its send side, and reads one `Response`:\\n\\n```json\\n{ \\"id\\": \\"01J...\\", \\"capability\\": \\"ocr.extract\\", \\"deadline_ms\\": 30000,\\n \\"payload\\": { \\"image\\": \\"<base64>\\" } }\\n```\\n\\n```json\\n{ \\"status\\": \\"ok\\", \\"id\\": \\"01J...\\", \\"payload\\": { \\"text\\": \\"...\\" } }\\n{ \\"status\\": \\"err\\", \\"id\\": \\"01J...\\", \\"code\\": \\"unsupported_image\\",\\n \\"message\\": \\"only png and jpeg\\" }\\n```\\n\\n`id` is a trace id for logs on both sides β€” correlation is the stream, not the\\nid. It must still be echoed: an answer carrying a different id means the\\nservice lost track of whose work it is, and the payload is refused. `payload`\\nis opaque to the transport; its shape belongs to the capability.\\n\\n`deadline_ms` is when the backend gives up. A service should abandon the work\\nrather than answer late. A handled failure is an `err` frame; a crash is just a\\ndropped stream.\\n\\n### Framing\\n\\n`u32` big-endian byte length, then that many bytes of JSON. One frame per\\nmessage. The length is validated against the 8 MiB cap **before** any buffer is\\nallocated. JSON rather than a binary codec so a service in any language can\\nspeak it in ~20 lines.\\n\\n### Routing\\n\\nRequests route by exact capability string to the **least-loaded** worker\\noffering it (ties broken by worker id). Least-inflight rather than\\nround-robin because AI request costs are wildly uneven β€” round-robin would\\npile a second long inference onto a busy worker while an idle one sits next\\nto it. Selection and the in-flight increment happen under one lock, so\\nconcurrent dispatches cannot overshoot `max_concurrent`.\\n\\nFailure modes the caller sees: `NoWorker` (nothing registered β€” retryable),\\n`Busy` (all at capacity β€” retryable), `Timeout` (may still be running on the\\nfar side, so it promises nothing), `Remote` (the service's considered no β€”\\nnot retryable), `Protocol` / `IdMismatch` (broken peer), `Transport`.\\n\\n### Conformance suite\\n\\n`tests/ai_protocol.rs` is the wire contract, enforced on every `cargo test`. It\\nspeaks `hab/1` with a client that imports none of the crate's protocol types β€”\\nframes built as byte literals, answers parsed as untyped JSON β€” so it fails on\\nexactly the changes a service in another language would notice: a renamed\\nfield, a re-tagged enum, a flipped length-prefix endianness, a newly-required\\n`Hello` field. (`tests/ai_bridge.rs` drives real QUIC clients too, but shares\\nthe Rust structs with the backend, so it cannot see those.)\\n\\nIt is also the reference implementation: its `raw` module is the whole client\\nside of the protocol in about a hundred lines β€” handshake, framing, request\\nloop β€” and is the shortest thing to port when writing a new service.\\n\\nGuarantees it pins beyond the frame shapes: unknown fields in `Hello` and in a\\nresponse are accepted (a newer service may run against an older backend);\\npayloads pass through byte-for-byte whatever their JSON shape; request ids are\\nunique; answers may come back in any order; a service that drops one request\\nstream fails only that request; a service that ignores `deadline_ms` finds its\\nstream torn down rather than delivering a late answer.\\n\\n### TLS, auth & finding the certificate\\n\\nQUIC has no plaintext mode. With `AI_TLS_CERT`/`AI_TLS_KEY` unset, a\\nself-signed certificate is generated at boot and its sha256 fingerprint logged\\nβ€” services pin that instead of installing a CA. The certificate authenticates\\n*the backend*; the shared token in `Hello` authenticates *the service*.\\n\\nSo a service does not have to be handed a file out of band, the certificate is\\npublished over HTTP:\\n\\n```\\nGET /ai/certificate # no auth; 404 when the bridge is disabled\\n{ \\"protocol\\": \\"hab/1\\",\\n \\"certificate_pem\\": \\"-----BEGIN CERTIFICATE-----\\\\n...\\",\\n \\"fingerprint_sha256\\": \\"6745e8...\\" }\\n```\\n\\nUnauthenticated on purpose: a server certificate is handed to every peer during\\nthe TLS handshake anyway, so publishing it discloses nothing. The private key\\nnever leaves the process, and the shared token β€” the thing that actually\\nauthenticates a service β€” is *not* served here.\\n\\n**A service must re-fetch this on every reconnect, not once at startup.** With\\nno PEM pair configured the bridge re-selfsigns at each boot, so a certificate\\npinned once goes stale the moment the backend restarts; a reconnect loop that\\nonly redials would then fail forever. The service startup sequence is: `GET\\n/ai/certificate` β†’ trust that PEM β†’ dial QUIC β†’ `Hello` β†’ serve; on any\\nconnection loss, start again from the fetch.\\n\\nNote what this is not: fetch-then-pin over plain HTTP is trust-on-first-use,\\nonly as trustworthy as that HTTP hop. On an untrusted network set\\n`AI_TLS_CERT`/`AI_TLS_KEY` to a real certificate and distribute it out of band\\nβ€” the endpoint then simply serves that, stable across restarts.", "source": "README.md"}, {"id": "chatbot", "title": "Chatbot", "body": "Every signed-in user β€” `parent` included β€” keeps private threads with an\\nAI service. The backend is a **relay**: it owns auth, the limits, the thread,\\nthe payload format, and the last look at the answer before anyone sees it; the\\nwords are the service's. There are deliberately **no rule, intent or\\ncanned-answer tables** β€” the thread is free-form, and a school that wants\\ndifferent behaviour changes its AI service, not this backend. A thread is\\nprivate to its owner: no teacher, no admin, nobody reads someone else's, and\\nanother user's thread is a `404`, never a `403`.\\n\\n### Sending is two-phase, and that is the point\\n\\n`POST /chatbot/threads/{id}/messages` answers `202 {message_id, status:\\n\\"pending\\"}` instead of the answer, because an inference outlives a normal\\nrequest (and the request-timeout layer that guards every handler). Before the\\nAI is even called, two rows are written: the user's turn, and an **empty\\n`pending` assistant row** β€” `message_id` is that row. That order is the whole\\ndesign: a reload, a dropped connection, a closed laptop can no longer lose an\\nanswer, because the place it will land already exists and the answering task\\noutlives the HTTP request.\\n\\nThe client then reads that row either way it likes:\\n\\n- **poll** `GET /chatbot/threads/{id}/messages/{mid}` β€” `pending` until it\\n settles, then `complete` with `content` or `failed` with `error_code`;\\n- **stream** `GET /chatbot/threads/{id}/messages/{mid}/stream` β€” the same\\n row over Server-Sent Events.\\n\\nBoth read the same row, so they can never disagree, in any state.\\n\\n### The SSE stream\\n\\n```\\nevent: delta\\ndata: {\\"text\\":\\"Newton'un ikinci yasasΔ± \\"}\\n\\nevent: delta\\ndata: {\\"text\\":\\"kuvvet ile ivme arasΔ±ndaki …\\"}\\n\\nevent: done\\ndata: {\\"message\\":{ …the message DTO… }}\\n```\\n\\nOne to eight `delta` events, then exactly one `done` carrying the finished\\nmessage; or, if the turn failed, a single `error` event\\n(`{\\"code\\":\\"timed_out\\",\\"message\\":\\"…\\"}`) and nothing else. Then the stream\\ncloses. A stream opened *after* the answer already landed still emits\\n`delta`s and a `done` β€” the replay is deliberate, so a client that connects\\nlate (or reconnects) never hangs waiting for events that already happened.\\n\\n**The deltas are sliced by the backend from the finished answer.** `hab/1` is\\nunary β€” the service returns the whole reply text, not tokens β€” so today the\\nchunking is cosmetic pacing, not real streaming. The event shape exists now so\\nthat the day a service streams, it becomes a drop-in change behind an\\nunchanged frontend.\\n\\n### The message DTO\\n\\n```json\\n{ \\"id\\": \\"01J8…\\", \\"thread_id\\": \\"01J8…\\", \\"role\\": \\"assistant\\",\\n \\"status\\": \\"complete\\", \\"content\\": \\"…\\", \\"truncated\\": false, \\"error_code\\": null,\\n \\"created_at\\": 1761820800000, \\"completed_at\\": 1761820803120 }\\n```\\n\\n`role` is `user` or `assistant`; `status` is `pending`, `complete`, or\\n`failed` (a user turn is always `complete`). `content` is empty while pending,\\n`error_code` is set only when failed, `completed_at` is `null` until the turn\\nsettles. `truncated` is `true` when `content` is only the first part of what\\nthe assistant answered β€” the rest was over `max_chatbot_message_len` and was cut;\\nit is always `false` for a user turn and for a failed one. Show it: a clipped\\nanswer that looks whole is worse than one the reader knows is clipped. The same\\nDTO is what the SSE `done` event carries, so the streaming and polling reads\\nagree about `truncated` exactly as they do about every other field.\\n\\n### Status codes\\n\\n| code | when |\\n| --- | --- |\\n| `202` | the turn was accepted; the answer is on its way |\\n| `400` | empty message, or longer than the school's `max_chatbot_message_len` |\\n| `404` | no such thread or message β€” or not the caller's |\\n| `409` | already at `max_chatbot_threads`; delete a thread first |\\n| `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |\\n| `503` | no connected service offers `chat.reply` β€” **nothing was written**, retry later |\\n\\nThe `503` ordering matters: availability is checked before the rows exist, so\\nan unavailable service leaves no dead `pending` row behind, and the rate limit\\nis charged before that, so a refused turn leaves no trace at all. The check is\\nthe backend's own worker registry, which owns the QUIC sockets and is therefore\\nthe whole truth about what can be answered.\\n\\n### A turn always settles\\n\\nOnce the two rows exist the answer never stays `pending` forever, through\\nthree independent mechanisms:\\n\\n- the task that owns the bridge round trip stamps `complete` or `failed` β€”\\n the normal path;\\n- a reader **projects** a `pending` row older than 300 seconds as\\n `failed`/`timed_out` (a read-time projection, not a write β€” the row is left\\n for the task that may still own it);\\n- a **boot sweep** flips every leftover `pending` past the 300-second horizon\\n to `failed`/`interrupted`, which is what a process death mid-inference looks\\n like. Younger rows are left alone, since one may still be in flight.\\n\\nA restart therefore loses a turn that was in flight: it settles\\n`failed`/`interrupted` rather than being answered. Accepted β€” the backend is a\\nsingle process with stop-the-world deploys, so there is no peer that could have\\ntaken it over.\\n\\nTwo more verdicts come from inspecting the answer: an **empty** reply is\\nreported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a\\nbug), and an **over-long** one is truncated to `max_chatbot_message_len` β€” a\\nclipped answer still helps, a discarded one does not β€” with `truncated: true`\\non the stored turn, so the clip is never passed off as the whole answer.\\n\\n`error_code` values a client may see: `unavailable` (no worker, or the bridge\\nis off), `busy`, `timed_out`, `transport`, `protocol`, `bad_reply` (the\\nservice's payload did not parse), `empty_reply`, `service_error`,\\n`interrupted`, `not_found`, `internal` β€” **or a code the AI service itself\\nreturned**, verbatim. Treat it as an open set: branch on the ones you handle,\\nfall back to the human-readable text for the rest.\\n\\n### The `chat.reply` capability (for AI-service authors)\\n\\nA chat service declares `chat.reply` in its `Hello` (see \\"AI bridge (QUIC)\\").\\nRequests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:\\n\\n```json\\n{ \\"message\\": \\"and the second law?\\",\\n \\"history\\": [ {\\"role\\":\\"user\\",\\"content\\":\\"what is the first law?\\"},\\n {\\"role\\":\\"assistant\\",\\"content\\":\\"an object at rest …\\"} ] }\\n```\\n\\n`history` is **oldest first** (index 0 is furthest back), optional (absent or\\n`[]` = a fresh thread), and **excludes** the new message β€” that one is\\n`message`. It carries the last `chatbot_history_turns` **settled messages** β€”\\nentries, not exchanges: the default `10` is five question/answer pairs, and\\n`history` is exactly that many entries long whenever the thread holds enough\\nof them. Only settled turns count: a failed answer is skipped and the window\\nreaches further back for a usable one, rather than coming up short. All of it\\nis re-sent on every request, which is why the service may be stateless: it can\\nrestart, scale out, or be replaced mid-thread without losing context.\\n\\nThe answer is a `Response::Ok` whose payload is:\\n\\n```json\\n{ \\"text\\": \\"the complete reply, not chunked, not partial\\" }\\n```\\n\\nFailures reuse the existing `Response::Err {code, message}` β€” one failure\\nshape on the bridge for every capability β€” and that `code` reaches the client\\nas the message's `error_code`.\\n\\n**Unknown extra keys are ignored on both sides, on purpose.** A service may\\nadd fields (a model name, token counts) and a future backend may send more\\ncontext without either end having to be redeployed in lockstep.", "source": "README.md"}, {"id": "collaborative-whiteboard", "title": "Collaborative whiteboard", "body": "A board is a shared canvas whose membership is an **ad-hoc invite list**: the\\ncreator names participant user ids at `POST /boards` and that is the whole\\nmodel β€” no course, no lesson session, no appointment. Any account from\\n`student` upwards may open one. **Every participant draws; the creator\\nalone clears, locks, closes or deletes.**\\n\\nThe roster is spelled `participants` everywhere β€” in the `POST` body, in the\\n`PATCH` body and in every board response β€” so a client may post back a board it\\njust read. Unlike the rest of this API, the two board request bodies **reject\\nan unknown key** (`422`) rather than ignoring it: a misspelled roster would\\notherwise open a board its author is silently alone on.\\n\\n**No parents, anywhere.** The `parent` role is the school's read-only observer,\\nand it has no whiteboard access at all β€” not a view-only tier, none. It is\\nrefused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named*\\nin an invite list either: `resolve_participants` rejects a parent id with a\\n`400`, so a parent is never on a roster in the first place. That one cut is\\nwhat closes the rest β€” never on a roster means the id-scoped routes and the\\nroom's door already answer the outsider's `404` (never a `403`, which would\\nconfirm the board is there), and no socket opens, so no `stroke` frame can be\\nsent. The role bar is re-checked on the read path and at the door as well, so a\\nboard row written before this rule that still lists a parent is inert: that\\nparent sees a `404` for it like any stranger.\\n\\n**Two doors, two statuses.** A caller who is not on a board gets a `404` on\\nevery route, its existence included β€” an outsider must never learn a board is\\nthere. A participant who is not the creator has already been told it exists, so\\nthe four creator-only commands answer them a `403`: hiding it at that point\\nwould be a lie their client cannot act on. Over the socket the same refusal is\\n`error{code:\\"forbidden\\"}` and the socket **stays open** β€” someone clicking a\\nbutton they don't own must not lose the canvas they were drawing on.\\n\\n**A clear deletes nothing.** Strokes are append-only. `POST /boards/{id}/clear`\\nbumps the board's `epoch` and appends a `clear` **marker** carrying the epoch\\nit closed, that epoch's final stroke count, who cleared and when β€” so the live\\ncanvas empties while every mark ever drawn stays stored and replayable. Those\\nmarkers *are* the epoch index, which is why there is no epochs table and why\\nthe open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.\\n`DELETE /boards/{id}` is the one operation here that really destroys marks.\\n\\n**Three caps, and only one of them is terminal** (all three published at `GET\\n/limits` under `board`):\\n\\n- `max_epoch_strokes` bounds the **live** canvas β€” `epoch_stroke_count`, which\\n every clear resets. Hitting it is **recoverable**: the creator clears, the\\n history is kept, drawing resumes.\\n- `max_board_strokes` bounds the board's **lifetime** storage β€”\\n `total_stroke_count`, which never resets, because a clear keeps its history.\\n Hitting it stamps `closed_at` and the board becomes **permanently\\n read-only**: still fully readable and replayable, never deleted, and there is\\n no reopen β€” open a new board. `POST /boards/{id}/close` is the manual form of\\n the same thing, and idempotent.\\n- `max_boards_per_creator` bounds how many boards one creator holds\\n (`board_count` on the user row). Deleting a board frees a seat; closing one\\n does not β€” a closed board is still stored.\\n\\n**Two ways to read the marks, and the difference matters most to a client\\nauthor.** A socket `join` replays the **current epoch only**; history never\\nrides the socket. History is an explicit paged REST read:\\n`GET /boards/{id}/history` (the board's whole life, oldest first, `clear`\\nmarkers included, `?epoch=` for a single one) and `GET /boards/{id}/epochs`\\n(the marker index β€” enough to offer \\"replay session 3\\" without scanning the\\nlog). `GET /boards/{id}/strokes` is the current epoch over REST, the catch-up\\nand fallback path for the same canvas the socket replays β€” with one deliberate\\ndifference: the REST read is *not* filtered by kind, while the socket serves\\n`kind: \\"stroke\\"` rows only. In the steady state that is a distinction without a\\ndifference, since a marker is written with the epoch it *closed* and the open\\nepoch has none; the case where it shows is a clear landing between the board\\nread and the row read, which surfaces that epoch's closing marker in the page.\\nFor a live canvas the socket is the authority.\\n\\n**The board room (WebSocket)** β€” `GET /boards/{id}/ws`, cookie-authed like\\neverything else and, like the exam room, outside the OpenAPI spec (an upgrade\\nis not describable there); REST remains the full fallback. The gate before the\\nupgrade is the same `404` door: not a participant, no room. Then JSON text\\nframes:\\n\\n| direction | frame |\\n|-----------|-------|\\n| client β†’ | `{\\"type\\":\\"join\\", \\"after\\":\\"<last stroke id>\\", \\"epoch\\":3}` β€” both optional; replay the current epoch |\\n| server β†’ | `{\\"type\\":\\"state\\", board, epoch, locked, closed_at, creator, participants, now}` on connect and every `ws_tick_secs` |\\n| server β†’ | `{\\"type\\":\\"strokes\\", epoch, strokes:[{id, author, payload}]}` β€” one replay chunk, repeated until the epoch is served |\\n| server β†’ | `{\\"type\\":\\"synced\\", epoch, cursor}` β€” the replay is complete; `cursor` is what to resume from |\\n| client β†’ | `{\\"type\\":\\"stroke\\", \\"payload\\":\\"…\\"}`, optionally `+ \\"client_seq\\":7` β€” any participant |\\n| server β†’ | `{\\"type\\":\\"saved\\", id, client_seq?}` β€” your stroke landed |\\n| server β†’ | `{\\"type\\":\\"stroke\\", id, author, payload, epoch}` β€” someone *else* drew |\\n| client β†’ | `{\\"type\\":\\"clear\\"}` / `{\\"type\\":\\"lock\\", \\"locked\\":true}` β€” **creator only** |\\n| server β†’ | `{\\"type\\":\\"cleared\\", …}` / `{\\"type\\":\\"locked\\", locked, by}` β€” the canvas was emptied / drawing was paused |\\n| server β†’ | `{\\"type\\":\\"closed\\", …}` / `{\\"type\\":\\"deleted\\"}` β€” the board is finished; both end the room |\\n| server β†’ | `{\\"type\\":\\"participants\\", creator, participants}` β€” the roster changed; a socket no longer on it is dropped |\\n| client β†’ | `{\\"type\\":\\"ping\\"}` β†’ server `{\\"type\\":\\"pong\\"}` |\\n| server β†’ | `{\\"type\\":\\"error\\", code, message, client_seq?}` |\\n\\nA `stroke` may carry a `client_seq` exactly as an exam-room `answer` does: any\\nvalue the client picks, echoed **verbatim** on that message's `saved` or\\n`error` and on nothing else, omitted entirely when the request omitted it. The\\nserver never reads it.\\n\\n`error` codes are a closed set: `epoch_full` (the live canvas is full β€” clear\\nit and keep drawing), `board_closed` (permanently read-only), `locked`,\\n`forbidden` (a creator-only command from a participant), `resync` (below),\\n`invalid` (bad JSON, an unknown frame, an over-long payload), `not_found`,\\n`unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\n**Persist, then publish.** A stroke is fanned out only after its row has\\nlanded, so the channel can never carry a mark the database refused (a locked\\nboard, a full epoch, a closed board). The database is the canvas; the channel\\nis a notification *about* it β€” which is why a client dedupes by stroke `id`,\\nwhy a resync deliberately re-serves marks it already drew, and why a frame is\\nnever the authority: every stroke, clear and lock re-reads the board and\\nre-checks the roster, so a socket that missed a `participants` or `locked`\\nframe is refused all the same. One consequence of the same read-then-write\\nshape: a stroke carries the epoch the server read for it, so a clear landing in\\nthat instant can file one stroke under the epoch it just closed β€” the stroke is\\nkept and stays replayable in `/history`, it simply is not on the new canvas.\\n\\n**Reconnecting.** `join` carries a cursor: `after`, the last stroke id already\\ndrawn, plus the `epoch` it belongs to. Same epoch and only what is newer is\\nreplayed; an older epoch β€” or no cursor at all β€” gets a `cleared` frame first\\nand then the whole current epoch, because a cursor into a closed epoch no\\nlonger means anything. If the room falls behind a slow socket the server sends\\n`error{code:\\"resync\\"}` and immediately replays the current epoch **out of the\\ndatabase**: the client does not re-join, it throws its canvas away and takes\\nwhat follows. The database is always the source of truth, never the channel.\\n\\n```js\\nconst ws = new WebSocket(`${BASE.replace(\\"http\\", \\"ws\\")}/boards/${id}/ws`);\\nlet epoch = null, cursor = null, seq = 0;\\nws.onopen = () => ws.send(JSON.stringify({ type: \\"join\\", after: cursor, epoch }));\\nws.onmessage = (e) => {\\n const m = JSON.parse(e.data);\\n if (m.type === \\"cleared\\") wipeCanvas();\\n if (m.type === \\"strokes\\") m.strokes.forEach(draw); // dedupe by m.id\\n if (m.type === \\"synced\\") ({ epoch, cursor } = m);\\n if (m.type === \\"stroke\\") draw(m);\\n if (m.type === \\"saved\\") settle(m.client_seq, m.id);\\n if (m.type === \\"error\\" && m.code === \\"resync\\") wipeCanvas();\\n};\\nconst send = (payload) =>\\n ws.send(JSON.stringify({ type: \\"stroke\\", payload, client_seq: ++seq }));\\n```", "source": "README.md"}, {"id": "concurrency-model", "title": "Concurrency model", "body": "The backend runs as **one process against one database**, and that buys less\\nthan it sounds like: every request is an async task, dozens are in flight at\\nonce, and each of them awaits the database in the middle of its work. So\\n\\"read, decide, write\\" is never safe on its own β€” SurrealDB does not\\nconflict-check a cross-record `count()` against a concurrent insert\\n(write-skew), and that fires between two tasks in one process exactly as it\\nwould between two machines. The mutex-only design this replaced was already\\nlosing races at one process. Every invariant is therefore guarded where the\\ndatabase itself decides the winner. Three tiers:\\n\\n1. **Single-row conditional writes** β€” compare-and-set (`save_if_unchanged`),\\n `UPDATE … WHERE`, stored counters (`domain::cap`). A single-record write is\\n atomic, so of N concurrent tasks exactly the allowed number get a non-empty\\n result: the database decides the winner, the loser retries\\n (`CAS_UPDATE_RETRIES`) or gets a 409.\\n2. **In-transaction `IF … THROW` gates** β€” the check runs inside the same\\n statement as the write it authorizes, so it is atomic with it. Used where\\n the rule reads the row being written (state machines, delete guards).\\n \\"Is anything still attached?\\" is answered the same way, by a counter on the\\n row being deleted rather than a `SELECT` over the children: a course is\\n deletable while its `enrollment_count` is zero, a term while its\\n `course_count` is (courses claim that reference *before* they write the\\n link, and give it back when the link moves or the course is deleted). A fee\\n plan reads the same way β€” editable *and* deletable while its\\n `assignment_count` is zero, and frozen for good once it is not, since an\\n assignment is never taken back.\\n Where the child also carries a deterministic id β€” one enrollment per\\n (course, user), one registration per (event, user), one fee-plan assignment\\n per (plan, student) β€” the seat and the row\\n are claimed in one transaction (`cap::claim_and_create`), so a duplicate\\n `CREATE` rolls its own seat back instead of costing a stranger their place.\\n3. **Two accepted races**, reviewed and deliberately left open:\\n - *Attempt-seq late save* β€” an exam-room socket writes into the sitting it\\n joined with, a choice made before any lock is taken, so a save racing a\\n retake can stamp an answer onto the just-terminal previous sitting.\\n Damage: one history row; the grade of record (latest `seq`) is never\\n touched.\\n - *Approved-overlap* β€” two approvals landing in the same instant can\\n double-book a teacher. Damage: one overlapping half-hour, visible to both\\n parties, fixable by cancelling either side.\\n\\nIn-process locks remain, and they are a *second* line, never the guarantee:\\n`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional\\n-write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is\\nthe cap β€” the lock only tames the retry loop, and keeps the tests' in-memory\\nengine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in\\nfront of a rule no single-record write can express. Removing one of them costs\\nthroughput or an accepted race; removing the conditional write behind it costs\\nthe invariant.\\n\\nBoot is unconditional: the schema batches, the backfills and the admin seed all\\nrun on every start, because exactly one process ever starts. Deployment is\\nstop-the-world β€” `podman compose down` then `up`, never overlapping β€” and a\\nrelease that adds or renames a stored counter *requires* it. An old binary\\nwrites rows without touching the new counter, the `= NONE` backfill guard\\n(correctly) refuses to re-seed, and the resulting permanent under-count lets a\\nguard approve exactly what it exists to refuse. In-flight work does not survive\\na restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.", "source": "README.md"}, {"id": "layout", "title": "Layout", "body": "```\\nsrc/\\n main.rs bootstrap: config, db, router, serve\\n lib.rs build_router: routes + OpenAPI/Swagger + CORS + /health\\n config.rs env-sourced Config\\n constant.rs validation limits\\n validate.rs field validators (used by every newtype's try_new)\\n error.rs ValidationError + AppError -> HTTP responses\\n database.rs SurrealDB server connect (ws) + SCHEMAFULL migration\\n migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,\\n MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them\\n rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier\\n state.rs AppState { db, files_path, cookie_secure, rate_limit,\\n chatbot_limit, exam_presence, board_hub, db_up, ai }\\n ai/ QUIC bridge to the out-of-process AI services\\n (see \\"AI bridge (QUIC)\\"; the HTTP half is web/ai.rs)\\n protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing\\n server.rs AiBridge: listener, handshake, dispatch over per-request streams\\n registry.rs connected workers, capability routing, least-inflight leases\\n tls.rs listener certificate (PEM or self-signed) + fingerprint\\n error.rs AiError\\n chat.rs the `chat.reply` payload contract (ChatRequestPayload/ChatReplyPayload)\\n domain/ validated newtypes + entities (derive SurrealValue),\\n each owning its persistence\\n user.rs UserId Β· Username Β· Password Β· PasswordHash Β· User (has role)\\n role.rs Role enum (student < teacher < manager < admin), at_least()\\n field_update.rs FieldUpdate: one UPDATE ... SET built from only the fields a\\n PATCH actually carried (an omitted field is never written)\\n monotonic_id.rs next_ulid: ids that sort in write order β€” one process-wide\\n Generator, so same-millisecond rows never scramble\\n key.rs sitting(): the deterministic per-sitting record key shared by\\n attempts, answers, answer images and results (seq 1 stays bare)\\n cap.rs claim()/release(): the count caps the database enforces β€” an\\n atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter\\n column of the parent row, replacing count-then-write mutexes\\n that could not see a concurrent insert;\\n claim_and_create() commits that seat and the child row in\\n one transaction, for children with a deterministic id\\n text_fold.rs case- and diacritic-insensitive folding for search, shared by\\n the Rust needle and the SurrealQL column (Turkish Δ°/Δ±, ΓΌ, â…)\\n session.rs SessionId Β· SessionToken Β· Session (7-day expiry)\\n timestamp.rs Timestamp (unix-millisecond instant)\\n note.rs NoteId Β· NoteTitle Β· NoteContent Β· Note\\n note_file.rs NoteFileId Β· FileName Β· FileContentType Β· NoteFile (metadata row;\\n blob on disk under FILES_PATH, named by the row's ULID)\\n event.rs EventId Β· EventTitle Β· EventDescription Β· Event\\n attendance.rs AttendanceId Β· AttendanceStatus Β· Attendance\\n course.rs CourseId Β· CourseTitle Β· CourseDescription Β· Course\\n course_session.rs CourseSessionId Β· SessionTopic Β· CourseSession (a course's lesson)\\n session_attendance.rs SessionAttendanceId Β· SessionAttendance (roll call; one row per session+user)\\n work_entry.rs WorkEntryId Β· WorkEntry (staff stint; one open per user by construction)\\n enrollment.rs EnrollmentId Β· Enrollment (one row per course+user)\\n exam.rs ExamId Β· ExamTitle Β· ExamDescription Β· ExamKind Β· ExamWeight Β·\\n ExamMode Β· ExamDuration Β· ExamSchedule Β· Exam (belongs to a course)\\n exam_attempt.rs ExamAttemptId Β· AttemptStatus Β· ExamAttempt (numbered sittings per exam+user, metered by max_attempts)\\n exam_question.rs ExamQuestionId Β· QuestionText Β· QuestionKind Β· QuestionPoints Β·\\n ChoiceText Β· QuestionSpec Β· ExamQuestion (choice|text, per exam)\\n exam_answer.rs ExamAnswerId Β· AnswerText Β· ExamAnswer (one row per question+user) Β·\\n auto_score (choice-question suggestion)\\n exam_result.rs ExamResultId Β· Mark Β· ExamResult (one row per exam+user)\\n question_image.rs QuestionImageId Β· QuestionImage (question/choice picture\\n metadata; bytes on disk under FILES_PATH)\\n answer_image.rs AnswerImageId Β· AnswerImage (student answer-drawing\\n metadata; bytes on disk under FILES_PATH)\\n bank_question.rs BankQuestionId Β· BankQuestion (school-wide reusable\\n question template, copied into exams; no exam FK)\\n bank_question_image.rs BankQuestionImageId Β· BankQuestionImage (bank\\n question/choice picture metadata; bytes on disk under FILES_PATH)\\n profile.rs PersonName Β· Email Β· Phone Β· BirthDate (personal-info newtypes)\\n preferences.rs Theme Β· Language Β· PaletteColor (own UI preferences)\\n message.rs MessageId Β· MessageSubject Β· MessageBody Β· MessageLabel Β·\\n Message (per-copy folders: inbox/sent/archive/trash)\\n parent_link.rs ParentLinkId Β· ParentLink (parent↔student tie = the parent's read grant)\\n registration.rs RegistrationId Β· Registration (a seat on a registration event's signup list)\\n subject.rs SubjectId Β· SubjectName Β· SubjectDescription Β· Subject (course curriculum)\\n term.rs TermId Β· TermName Β· Term (school term window)\\n menu.rs MenuId Β· MenuDate Β· MenuSlot Β· Menu (one published menu per\\n calendar day + meal slot; slot snapshotted as text)\\n menu_dish.rs MenuDishId Β· DishName Β· DishDescription Β· DishPrice Β·\\n DishTags Β· MenuDish (a dish on a menu; price in minor units)\\n dietary_profile.rs DietaryProfileId Β· DietaryTags Β· DietaryNote Β·\\n DietaryProfile (what one student may not eat; keyed by the\\n student, tagged from the same `dietary_tags` list a dish is)\\n meal_booking.rs MealBookingId Β· MealBookingStatus Β· MealBooking (one seat\\n per (menu, student); a cancel flips the status, never deletes)\\n meal_attendance.rs MealAttendanceId Β· MealAttendanceStatus Β· MealAttendance\\n (who actually ate; one row per (menu, student), reporting\\n only β€” it never touches the ledger)\\n meal_ledger.rs MealLedgerId Β· MealLedgerKind Β· LedgerAmount Β· LedgerMethod Β·\\n LedgerNote Β· MealLedger (append-only money; the balance is\\n always the fold, never a stored field)\\n fee_plan.rs FeePlanId Β· FeePlanName Β· Installment Β· FeePlan (a school fee\\n plan; installments embedded on the row, past due dates legal)\\n fee_plan_assignment.rs FeePlanAssignmentId Β· FeePlanAssignment (one plan on\\n one student, keyed `<plan>_<student>`; assigning appends\\n every installment charge, a replay appends nothing)\\n payment_ledger.rs PaymentLedgerId Β· PaymentLedgerKind Β· PaymentLedger\\n (append-only school fees: charge/credit/reversal/refund, a\\n credit names its charge and a refund its credit; the balance\\n is always the fold; over-payment cap is advisory)\\n settings.rs ExamKindDef Β· GradeBand Β· Settings (per-school policy)\\n chatbot_thread.rs ChatbotThreadId Β· ChatbotThreadTitle Β· ChatbotThread (one\\n chatbot thread, private to its owner)\\n chatbot_message.rs ChatbotMessageId Β· ChatContent Β· MessageRole Β· MessageStatus Β·\\n ChatbotMessage (one turn; the assistant row is written\\n `pending` before the AI call and settled after)\\n board.rs BoardId Β· BoardTitle Β· Board (a collaborative whiteboard:\\n creator + ad-hoc participant list, `epoch`, the two stroke\\n counters and `closed_at`)\\n board_stroke.rs BoardStrokeId Β· BoardStroke (the\\n append-only stroke log; a `clear` row is the marker that\\n closed an epoch, carrying its final count β€” nothing is\\n ever deleted)\\n appointment_slot.rs AppointmentSlotId Β· SlotSeries Β· SlotNote Β·\\n AppointmentSlot (a teacher's published availability; a\\n recurring publish is expanded into rows sharing a series id)\\n appointment.rs AppointmentId Β· AppointmentStatus Β· AppointmentReason Β·\\n Appointment (a booking on a slot; occupancy is the slot's\\n stored `occupied` cap-1 counter, overlap is derived under\\n APPOINTMENT_LOCK)\\n pomodoro.rs PomodoroSessionId Β· PomodoroSession (student focus log)\\n pool_question.rs PoolQuestionId Β· PoolQuestionTitle Β· PoolQuestionBody Β·\\n PoolQuestion (student-asked question; teacher-approved into\\n the school-wide pool; optional photo as metadata + disk blob)\\n solution.rs SolutionId Β· SolutionBody Β· Solution (discussion thread on an\\n approved pool question; dies with the question)\\n homework.rs HomeworkId Β· HomeworkTitle Β· HomeworkDescription Β· Homework\\n (per-course assignment; required subject; optional `assigned`\\n student subset β€” absent/empty = the whole enrolled course)\\n homework_submission.rs HomeworkSubmissionId Β· SubmissionText Β·\\n HomeworkSubmission (one row per homework+user; immutable\\n submitted_at + moving updated_at β€” `late` is computed)\\n homework_file.rs HomeworkFileId Β· HomeworkFile (submission attachment\\n metadata; any content type; bytes on disk under FILES_PATH)\\n homework_result.rs HomeworkResultId Β· HomeworkStatus Β· HomeworkResult\\n (teacher grade: done/incomplete/missing + optional Mark; one\\n row per homework+user β€” its existence freezes the submission)\\n web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +\\n auth extractors\\n extractor.rs CurrentUser Β· RequireTeacher Β· RequireManager Β· RequireAdmin\\n dto.rs shared UserResponse Β· CourseResponse Β· ExamResponse Β· SessionResponse schemas\\n exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)\\n board_ws.rs the collaborative board room WebSocket (join replay, strokes\\n fanned out to every participant, clear/lock)\\n room.rs the plumbing both rooms share: sending a frame, classifying\\n an incoming message, an AppError as a readable code, and a\\n client_seq echoed untouched\\n page.rs PageParams Β· Page<T> (shared pagination)\\n etag.rs conditional-GET middleware: ETag over a 200 JSON body,\\n If-None-Match β†’ 304 (GET only; SSE and blobs pass through)\\n auth.rs users.rs notes.rs messages.rs events.rs appointments.rs\\n courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs\\n bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs\\n settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs\\n boards.rs\\n limits.rs GET /limits: every constant.rs bound served as JSON\\n```\\n\\nTests: `cargo test` β€” unit (in-source), integration (`tower::oneshot` + in-memory\\ndb), rate-limit (both tiers, proxy-header and peer-address keying, shipped\\nlimits over every route, two limiters sharing one budget over one db), e2e\\n(real TCP + reqwest cookie jar), persistence\\n(tempfile file engine, including close + reopen), ai-bridge (real QUIC on\\nloopback against a fake AI service), ai-protocol (the `hab/1` wire contract,\\ndriven by a client that shares no code with the backend).", "source": "README.md"}];
96+INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "5f59783c6826e3ee660cde26dda01988e0f2d42e65bd11c705d2e896e206388a"}];
97+DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii;
98+DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25;
99+DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25;
100+REMOVE TABLE IF EXISTS endpoint;
101+INSERT INTO endpoint [{"id": "health", "routes": "| GET | `/health` | no | Liveness check |"}, {"id": "root", "routes": "| GET | `/` | no | Same as `/health` |"}, {"id": "time", "routes": "| GET | `/time` | no | Server clock: `{now}` UTC unix-millis (frontend sync) |"}, {"id": "limits", "routes": "| GET | `/limits` | no | Every fixed validation bound, grouped by resource \\u2014 see Validation limits |"}, {"id": "swagger", "routes": "| GET | `/swagger` | no | Interactive API docs (Swagger UI) |"}, {"id": "api-docs", "routes": "| GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |"}, {"id": "ai", "routes": "| GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + sha256) for a service to pin; `404` when the bridge is off |"}, {"id": "auth", "routes": "| POST | `/auth/register` | no | `{username, password}` -> `{username, role}` (no `id`; new users are `student`); always `201`, even if the name was taken \\u2014 see Auth model |\\n| POST | `/auth/login` | no | `{username, password}` -> cookie|\\n| POST | `/auth/logout` | no | Clear session (no-op if none) |\\n| GET | `/auth/me` | student | Current user (incl. `role` and personal info) |"}, {"id": "users", "routes": "| PATCH | `/users/me` | student | Update own personal info (see below) |\\n| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` \\u2014 own UI preferences (see below) |\\n| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) \\u00b7 paged |\\n| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` \\u2014 find users by username/name fragment (pickers); refs only, no contact info \\u00b7 paged |\\n| GET | `/users` | admin | List all users \\u00b7 paged |\\n| GET | `/users/{id}` | admin | Get one user |\\n| PATCH | `/users/{id}/role` | admin | `{role}` \\u2014 set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |\\n| PATCH | `/users/{id}/profile` | admin | Update any user's personal info |\\n| PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |\\n| POST | `/users/{id}/students` | admin | `{user_id}` \\u2014 tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |\\n| GET | `/users/{id}/students` | admin | List a parent's linked students \\u00b7 paged |\\n| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |"}, {"id": "notes", "routes": "| POST | `/notes` | student | `{title, content?}` |\\n| GET | `/notes` | student | List own notes \\u00b7 paged |\\n| GET | `/notes/{id}` | student | Get own note |\\n| PATCH | `/notes/{id}` | student | `{title?, content?}` |\\n| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) |\\n| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) \\u2014 \\u2264 the school's `max_file_bytes`, \\u2264 10 files per note |\\n| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) \\u00b7 paged |\\n| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) |\\n| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file |"}, {"id": "messages", "routes": "| POST | `/messages` | student | `{recipient_id, subject, body?, label?}` \\u2014 send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag |\\n| GET | `/messages` | student | `?folder=inbox\\\\|sent\\\\|archive\\\\|trash` (default `inbox`) `&read=` \\u2014 the caller's folder, newest first; `?folder=inbox&read=false&limit=1` \\u2192 `total` is the unread badge \\u00b7 paged |\\n| PATCH | `/messages/{id}` | student | `{read?, folder?}` \\u2014 read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) |\\n| DELETE | `/messages/{id}` | student | Permanently delete **own copy** \\u2014 only from the trash (`409` elsewhere); the row vanishes once both sides deleted |"}, {"id": "events", "routes": "| POST | `/events` | teacher | `{title, description?, audience?, starts_at?, ends_at?}` \\u2014 `audience` defaults to school-wide |\\n| GET | `/events` | student | List all events \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/events/{id}` | student | Get event |\\n| PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any); a sent `audience` replaces the old one wholesale |\\n| DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |\\n| POST | `/events/{id}/attendance` | teacher | `{status, user_id?}` \\u2014 mark someone in the event's **audience** (the caller when `user_id` omitted); students never mark |\\n| GET | `/events/{id}/attendance` | teacher | List recorded attendance for event (students read their own tallies via `/attendance/me`) \\u00b7 paged |\\n| GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` \\u00b7 paged |\\n| DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |\\n| POST | `/events/{id}/register` | teacher | `{user_id?}` \\u2014 seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started |\\n| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started |"}, {"id": "appointments", "routes": "| POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` \\u2014 publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, \\u2264 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) \\u2014 a weekly publish is all-or-nothing |\\n| GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar \\u2014 future slots only, demoted teachers' slots left out \\u00b7 paged |\\n| DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it |\\n| DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking |\\n| POST | `/appointments` | student | `{slot, reason}` \\u2014 book a slot; **students and parents only** (a parent books for themselves); lands `pending`, `409` if the slot's window has already started, the slot is taken, the caller is busy at that time, or its teacher is no longer staff |\\n| GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests \\u00b7 paged |\\n| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, when the effective window has already started, or when the time collides with another approved meeting of either side |\\n| PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up |\\n| PATCH | `/appointments/{id}/cancel` | student | `{reason?}` \\u2014 call it off; **the requester only** (`403` for anyone else, the slot's teacher and manager+ included \\u2014 they reject, or reschedule then reject); `409` once settled or the meeting has started |\\n| PATCH | `/appointments/{id}/reschedule` | teacher | `{starts_at, ends_at}` \\u2014 counter-propose another time (same rights); the booking goes back to `pending`; `409` if the proposed window has already started |\\n| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) |\\n| PATCH | `/appointments/{id}/reschedule/decline` | student | Requester only: refuse the proposal \\u2014 this **cancels** the booking, so the cancel deadline applies (`409` once the meeting's window has started) |"}, {"id": "courses", "routes": "| POST | `/courses` | teacher | `{title, description?, kind?, term_id?, capacity?}` \\u2014 `kind` is `course` (default), `study` (et\\u00fct), or `club` (kul\\u00fcp); `capacity` caps the roster (creator manages it) |\\n| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) \\u00b7 paged |\\n| GET | `/courses/me` | student | The caller's **enrolled** courses \\u00b7 paged |\\n| GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |\\n| PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |\\n| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ \\u2014 **not** an assigned teacher; `409` while anyone is still enrolled) |\\n| POST | `/courses/{id}/teachers` | manager | `{user_id}` \\u2014 assign a **teacher+** to run the course (idempotent; returns the course) |\\n| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |\\n| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` \\u2014 enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u00b7 paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` \\u2014 add a lesson (course manager; teacher defaults to the caller) |\\n| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` \\u2014 add a curriculum subject (course manager) |\\n| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, assigned teacher, or manager+) \\u00b7 paged |\\n| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` \\u2014 add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |\\n| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) \\u00b7 paged |\\n| POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` \\u2014 assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, \\u2264 200 (omit/`[]` = the whole course) (course manager) |\\n| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) \\u00b7 paged |"}, {"id": "subjects", "routes": "| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) |\\n| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) |\\n| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions or homework reference it |"}, {"id": "sessions", "routes": "| GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |\\n| PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |\\n| DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |\\n| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` \\u2014 roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |\\n| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) \\u00b7 paged |\\n| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |"}, {"id": "exams", "routes": "| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) \\u00b7 paged \\u00b7 `?starts_after=&ends_after=` window (soonest first) |\\n| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |\\n| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist \\u2014 the rest stays live; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |\\n| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` \\u2014 grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |\\n| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) \\u00b7 paged |\\n| GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |\\n| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |\\n| GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |\\n| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt \\u2014 students only; enrolled; window open where one exists; `409` once `max_attempts` is spent |\\n| GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |\\n| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |\\n| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 add a question tagged with one of the course's subjects (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) \\u00b7 paged |\\n| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question \\u2014 the kind bundle revalidates as a unit (course manager; frozen once attempted) |\\n| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam \\u2014 copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** \\u2014 copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) |\\n| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy the template's **current** content over this question \\u2014 text, points, kind, choices (with the template's choice ids), `correct`, illustration and option pictures; keeps the question's own id, exam, `subject` and provenance links, and overwrites any local edit. `400` if it never came from the bank (or the template is gone), `404` if the template is not visible to the caller, `409` once attempts exist (course manager) |\\n| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) |\\n| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (course manager; frozen once attempted) |\\n| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) |\\n| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above) |\\n| GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | The option picture's bytes (same access as the illustration) |\\n| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option picture (course manager; frozen once attempted) |\\n| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \\\\| text?}` \\u2014 autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) |\\n| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach/replace the caller's drawn answer to a question: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (own in-progress attempt; students only, enrolled, rejoin door open) |\\n| GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes, served inline (same wall as the sitting view: enrolled + attempt started) |\\n| DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) |\\n| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left (answers \\u22c3 marks), ascending \\u2014 the per-attempt history picker (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |\\n| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |\\n| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first \\u2014 the latest seq is the grade-of-record (course manager) |\\n| GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** \\u2014 the answer key the caller checks their own sheet against (same review gate) \\u00b7 paged |\\n| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers \\u22c3 marks), ascending \\u2014 only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |\\n| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |\\n| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see \\"Taking an exam\\") |\\n| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster \\u00d7 latest attempts \\u00d7 marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |"}, {"id": "bank-questions", "routes": "| GET | `/bank-questions` | teacher | The school-wide question bank \\u2014 `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) \\u00b7 paged |\\n| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` \\u2014 save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist \\u2014 `400` otherwise) |\\n| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) |\\n| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question \\u2014 the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze; concurrent edits merge, never silently revert each other) |\\n| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part \\u2014 raster images only (`png`/`jpeg`/`webp`/`gif`), \\u2264 `max_file_bytes` (**owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) |\\n| POST | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Attach/replace one option's picture, keyed by the `id` carried on that choice (`choice` questions; same form and limits as above; **owner only**, admin bypass) |\\n| GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) |\\n| DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) |"}, {"id": "homework", "routes": "| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) \\u00b7 paged |\\n| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) |\\n| PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade \\u2014 the blockers are named) |\\n| DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades \\u2014 file blobs included (course manager) |\\n| POST | `/homework/{id}/submission` | student | `{text?}` \\u2014 hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded |\\n| GET | `/homework/{id}/submission` | student | Own submission: text, both stamps, computed `late`, files, grade-if-any (`404` until submitted) |\\n| DELETE | `/homework/{id}/submission` | student | Withdraw own submission + its files and blobs (`409` once graded) |\\n| POST | `/homework/{id}/submission/files` | student | Attach a file to own submission: `multipart/form-data`, one `file` part \\u2014 **any** content type, \\u2264 `max_file_bytes`, \\u2264 10 per submission; auto-creates the submission (a photo-only homework is one request); `409` once graded or full |\\n| GET | `/homework/{id}/submission/files/{fid}` | student | The file bytes as a **forced download** (`Content-Disposition: attachment`) \\u2014 the owning student, or a course manager; observers never |\\n| DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove own file, row then blob (`409` once graded) |\\n| GET | `/homework/{id}/submissions` | teacher | The grading roster: one row per audience student \\u00d7 submission/files/grade + computed `late`/`missing`/`unenrolled` \\u2014 a straggler's stale work stays visible (course manager) \\u00b7 paged |\\n| POST | `/homework/{id}/results` | teacher | `{user, status, mark?}` \\u2014 grade `done`/`incomplete`/`missing` (+ optional 0\\u2013100 mark) onto an enrolled, assigned **student** (upsert; course manager; never yourself; freezes the submission; unsubmitted work gradable \\u2014 that's `missing`) |\\n| GET | `/homework/{id}/result` | student | The caller's **own** grade (`404` until graded) \\u2014 readable even when nothing was submitted (a `missing` verdict) |\\n| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade \\u2014 un-grading reopens their submission (course manager) |\\n| GET | `/homework/report/{user}` | teacher* | Per-homework report rows \\u2014 submitted/late/missing + the grade (manager+: full; a teacher: their managed courses); *or a `parent` linked to `{user}` \\u2014 full, statuses and marks only, never files \\u00b7 paged |"}, {"id": "questions", "routes": "| POST | `/questions` | student | `{title, body}` \\u2014 ask into the school question pool (**students only**); born `pending`, visible to the asker + teacher+ |\\n| GET | `/questions` | student | `?status=pending\\\\|approved` \\u2014 the pool questions visible to the caller, each with its `solution_count` \\u00b7 paged |\\n| GET | `/questions/{id}` | student | Get one (a `pending` question is a `404` unless asker or teacher+) |\\n| POST | `/questions/{id}/approve` | teacher | Approve a pending question \\u2014 publishes it school-wide; content frozen after (`409` if already approved) |\\n| DELETE | `/questions/{id}` | student | Delete own question (teacher+: any); its solutions go with it |\\n| POST | `/questions/{id}/image` | student | Attach/replace the problem photo (asker only): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/image` | student | The photo bytes |\\n| DELETE | `/questions/{id}/image` | student | Remove the photo (asker only) |\\n| POST | `/questions/{id}/solutions` | student | `{body}` \\u2014 offer a solution on an approved question (anyone in the school) |\\n| GET | `/questions/{id}/solutions` | student | The question's solutions, oldest first \\u2014 a discussion thread \\u00b7 paged |\\n| DELETE | `/questions/{id}/solutions/{sid}` | student | Delete a solution (author, or teacher+); its photo blob goes with it |\\n| PATCH | `/questions/{id}/solutions/{sid}` | student | `{body}` \\u2014 edit own solution (author only, teacher+ included out; solutions never freeze) |\\n| POST | `/questions/{id}/solutions/{sid}/image` | student | Attach/replace the solution's photo (author only, anytime): `multipart/form-data`, one `file` part, raster only, \\u2264 `max_file_bytes` |\\n| GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes (access follows the question) |\\n| DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo (author only) |"}, {"id": "marks", "routes": "| GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |\\n| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "work", "routes": "| POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |\\n| POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |\\n| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) \\u00b7 paged |\\n| GET | `/work/{user}` | manager | A staff member's work log \\u00b7 paged |\\n| PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` \\u2014 correct a **closed** stint (`409` on open) |\\n| DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |"}, {"id": "pomodoro", "routes": "| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** \\u2014 a dangling unfinished session is discarded and replaced) |\\n| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |\\n| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` \\u00b7 paged |\\n| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape \\u00b7 paged; *or a `parent` linked to `{user}` |"}, {"id": "attendance", "routes": "| GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |\\n| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` \\u2014 full |"}, {"id": "settings", "routes": "| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |\\n| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on \\"Invalid lists, bands, file limit, or chat limits\\"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see \\"Per-school policy\\") |"}, {"id": "terms", "routes": "| POST | `/terms` | manager | `{name, starts_at, ends_at}` \\u2014 past dates allowed (calendar backfill) |\\n| GET | `/terms` | student | List terms, newest first \\u00b7 paged |\\n| GET | `/terms/{id}` | student | Get one term |\\n| PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |\\n| DELETE | `/terms/{id}` | manager | Delete a term \\u2014 `409` while any course still links to it |"}, {"id": "meals", "routes": "| POST | `/meals/menus` | manager | `{date, slot, capacity?}` \\u2014 publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |\\n| GET | `/meals/menus` | student | List menus with their dishes, newest day first \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range \\u00b7 paged |\\n| GET | `/meals/menus/{id}` | student | One menu with its dishes |\\n| PATCH | `/meals/menus/{id}` | manager | `{capacity}` \\u2014 the only mutable field (`null` = uncapped); `date` and `slot` are immutable |\\n| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |\\n| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` \\u2014 add a dish (\\u2264 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |\\n| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `\\"description\\": null` clears it) |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |\\n| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |\\n| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |\\n| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` \\u2014 record what a student may not eat (`tags` replaces the list, `\\"note\\": null` clears it); **manager+**, a student never edits their own |\\n| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` \\u2014 take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |\\n| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first \\u00b7 paged |\\n| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included \\u00b7 paged |\\n| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff |\\n| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` \\u2014 mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |\\n| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu \\u00b7 paged |\\n| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history \\u00b7 `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day \\u00b7 paged \\u00b7 own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |\\n| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line |"}, {"id": "payments", "routes": "| POST | `/payments/plans` | manager | `{name, installments}` \\u2014 write a fee plan (1\\u201360 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |\\n| GET | `/payments/plans` | manager | List fee plans, newest first \\u00b7 paged |\\n| GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |\\n| PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan |\\n| DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it \\u2014 its charges name it |\\n| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (\\u2264 200) \\u2014 place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` |\\n| GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first \\u00b7 paged |\\n| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` \\u2014 record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` |\\n| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` \\u2014 hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety |\\n| POST | `/payments/reversals` | manager | `{line_id, note?}` \\u2014 undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line |\\n| GET | `/payments/ledger/{user}` | student | One student's raw lines \\u2014 charges, payments, refunds, reversals \\u2014 newest first \\u00b7 paged \\u00b7 own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) |\\n| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page |\\n| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging |\\n| GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) |\\n| GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger |"}, {"id": "chatbot", "routes": "| POST | `/chatbot/threads` | student | `{title?}` \\u2014 start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |\\n| GET | `/chatbot/threads` | student | The caller's threads, newest activity first \\u00b7 paged |\\n| PATCH | `/chatbot/threads/{id}` | student | `{title}` \\u2014 rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |\\n| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |\\n| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first \\u2014 user and assistant rows alike \\u00b7 paged |\\n| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (\\u2264 `max_chatbot_message_len`) \\u2014 send a turn; `202 {message_id, status: \\"pending\\"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` \\u2014 nothing is written; `429` + `Retry-After` on the send tier) |\\n| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |\\n| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` \\u2014 or one `error` \\u2014 and close; an already-finished answer replays (see \\"Chatbot\\") |"}, {"id": "boards", "routes": "| POST | `/boards` | student | `{title, participants?}` \\u2014 open a whiteboard; the caller becomes its creator, everyone named may draw; `409` at `max_boards_per_creator` |\\n| GET | `/boards` | student | Boards the caller created or was invited to, newest first \\u00b7 paged |\\n| GET | `/boards/{id}` | student | One board \\u2014 a `404`, never a `403`, for anyone not on it |\\n| GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first \\u00b7 paged |\\n| GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included \\u00b7 `?epoch=` for one epoch \\u00b7 paged |\\n| GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) \\u00b7 paged |\\n| PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` \\u2014 re-title (any participant); the roster and the lock are the creator's alone (`403`) |\\n| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap \\u2014 nothing is deleted; `409` on a closed board |\\n| POST | `/boards/{id}/close` | student | **Creator only**: retire the board \\u2014 permanently read-only, still fully readable; idempotent, and there is no reopen |\\n| DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |\\n| GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see \\"Collaborative whiteboard\\") |"}];
src/domain/board.rsmodified+24 -14
@@ -18,7 +18,7 @@ use crate::constant::{
1818 BOARD_TABLE, MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN, MAX_BOARDS_PER_CREATOR,
1919 USER_BOARD_COUNT_FIELD,
2020 };
21-use crate::database::Database;
21+use crate::database::{Database, transaction_with_retry};
2222 use crate::domain::cap;
2323 use crate::domain::monotonic_id::next_ulid;
2424 use crate::domain::page::PagedList;
@@ -297,19 +297,29 @@ impl Board {
297297 /// and issued separately it could leave a board's whole history orphaned
298298 /// under a record that no longer exists.
299299 pub async fn delete(self, db: &Database) -> Result<Board, AppError> {
300- let mut result = db
301- .query(
302- "BEGIN TRANSACTION;
303- DELETE board_stroke WHERE board = $id;
304- LET $gone = (DELETE $id RETURN BEFORE);
305- UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]);
306- RETURN $gone;
307- COMMIT TRANSACTION;",
308- )
309- .bind(("id", self.id.record()))
310- .bind(("usr", self.creator.record()))
311- .await?
312- .check()?;
300+ // A stroke claim writes the very board row this deletes, so the store
301+ // aborts one of the two and a lost round is ordinary here β€” re-sent
302+ // rather than reported as a 500. Re-sending is sound: every statement
303+ // is a `DELETE` or a field-scoped `UPDATE`, none of which can ever
304+ // answer "already exists" (see [`transaction_with_retry`]).
305+ let (mut result, mut errors) = transaction_with_retry(
306+ db,
307+ "BEGIN TRANSACTION;
308+ DELETE board_stroke WHERE board = $id;
309+ LET $gone = (DELETE $id RETURN BEFORE);
310+ UPDATE $usr SET board_count = math::max([(board_count ?? 0) - array::len($gone), 0]);
311+ RETURN $gone;
312+ COMMIT TRANSACTION;",
313+ &[
314+ ("id".into(), self.id.record().into_value()),
315+ ("usr".into(), self.creator.record().into_value()),
316+ ],
317+ &[],
318+ )
319+ .await?;
320+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
321+ return Err(error.into());
322+ }
313323 // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN
314324 // is slot 4.
315325 one(result.take::<Vec<Board>>(4)?)
src/web/boards.rsmodified+10 -3
@@ -205,18 +205,24 @@ impl StrokeResponse {
205205 }
206206 }
207207
208+/// `deny_unknown_fields` on both board request bodies is deliberate: this DTO
209+/// used to spell the roster `participant_ids` while the response and the PATCH
210+/// spelled it `participants`, so a client posting a board it had just read got
211+/// a `201` with a silently empty roster. A misspelled field is now refused
212+/// instead of dropped.
208213 #[derive(Deserialize, ToSchema)]
214+#[serde(deny_unknown_fields)]
209215 struct CreateBoard {
210216 #[schema(max_length = 200)]
211217 title: String,
212218 /// Who may draw, besides the creator. Omit or send an empty list to open a
213219 /// board alone and invite later.
214220 #[schema(max_items = 50)]
215- participant_ids: Option<Vec<String>>,
221+ participants: Option<Vec<String>>,
216222 }
217223
218224 /// Open a whiteboard. The caller becomes its creator β€” the only one who may
219-/// clear, lock, close or delete it β€” and everyone named in `participant_ids`
225+/// clear, lock, close or delete it β€” and everyone named in `participants`
220226 /// may draw on it. Student and above: the `parent` role has no whiteboard
221227 /// access at all, neither as a creator nor as a participant. `409` once the
222228 /// caller holds `max_boards_per_creator` boards (`GET /limits`); delete one to
@@ -241,7 +247,7 @@ async fn create_board(
241247 Json(req): Json<CreateBoard>,
242248 ) -> Result<(StatusCode, Json<BoardResponse>), AppError> {
243249 let title = BoardTitle::try_new(&req.title)?;
244- let participants = resolve_participants(req.participant_ids, &st.db).await?;
250+ let participants = resolve_participants(req.participants, &st.db).await?;
245251 let board = Board::create(user.get_id(), title, participants, &st.db).await?;
246252 Ok((StatusCode::CREATED, Json(BoardResponse::new(&board))))
247253 }
@@ -412,6 +418,7 @@ async fn list_epochs(
412418 }
413419
414420 #[derive(Deserialize, ToSchema)]
421+#[serde(deny_unknown_fields)]
415422 struct UpdateBoard {
416423 /// Re-title. Any participant may. Omit to keep.
417424 #[schema(max_length = 200)]
tests/e2e.rsmodified+1 -1
@@ -2083,7 +2083,7 @@ async fn board_room_fixture() -> BoardRoom {
20832083
20842084 let res = creator
20852085 .post(format!("{base}/boards"))
2086- .json(&json!({ "title": "Geometri", "participant_ids": [veli_id] }))
2086+ .json(&json!({ "title": "Geometri", "participants": [veli_id] }))
20872087 .send()
20882088 .await
20892089 .unwrap();
tests/integration.rsmodified+47 -3
@@ -24075,7 +24075,7 @@ async fn create_board(
2407524075 "POST",
2407624076 "/boards",
2407724077 Some(cookie),
24078- Some(json!({ "title": title, "participant_ids": participants })),
24078+ Some(json!({ "title": title, "participants": participants })),
2407924079 )
2408024080 .await;
2408124081 assert_eq!(
@@ -24267,7 +24267,7 @@ async fn a_parent_gets_no_whiteboard_at_all() {
2426724267 "POST",
2426824268 "/boards",
2426924269 Some(&anne),
24270- Some(json!({ "title": "Gizli", "participant_ids": [] })),
24270+ Some(json!({ "title": "Gizli", "participants": [] })),
2427124271 )
2427224272 .await;
2427324273 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
@@ -24281,7 +24281,7 @@ async fn a_parent_gets_no_whiteboard_at_all() {
2428124281 "POST",
2428224282 "/boards",
2428324283 Some(&ali),
24284- Some(json!({ "title": "Geometri", "participant_ids": [&anne_id] })),
24284+ Some(json!({ "title": "Geometri", "participants": [&anne_id] })),
2428524285 )
2428624286 .await;
2428724287 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
@@ -24338,6 +24338,50 @@ async fn a_parent_gets_no_whiteboard_at_all() {
2433824338 assert!(stored_board(&db, &board).await.is_some());
2433924339 }
2434024340
24341+/// The roster is spelled `participants` on the way in, out and through `PATCH`.
24342+/// It used to be `participant_ids` on `POST` alone, and with serde ignoring the
24343+/// unknown key a client that posted back a board it had just read got a `201`
24344+/// for a board it was silently alone on. A misspelled roster must now be
24345+/// refused, not dropped β€” the assert is the *stored* row, because the response
24346+/// echoing an empty list is exactly what the old bug looked like.
24347+#[tokio::test]
24348+async fn a_misspelled_roster_is_refused_instead_of_silently_dropped() {
24349+ let (app, db) = common::app_and_db().await;
24350+ let ali = login(&app, "ali").await;
24351+ let ali_id = me_id(&app, &ali).await;
24352+ let veli = login(&app, "veli").await;
24353+ let veli_id = me_id(&app, &veli).await;
24354+
24355+ let res = send(
24356+ &app,
24357+ "POST",
24358+ "/boards",
24359+ Some(&ali),
24360+ Some(json!({ "title": "Geometri", "participant_ids": [&veli_id] })),
24361+ )
24362+ .await;
24363+ assert_eq!(
24364+ res.status,
24365+ StatusCode::UNPROCESSABLE_ENTITY,
24366+ "the old spelling must not open a board: {}",
24367+ res.body
24368+ );
24369+ // Refused whole: no solo board, and no seat spent on one.
24370+ assert_eq!(stored_board_count(&db, &ali_id).await, 0);
24371+
24372+ let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await;
24373+ let stored = stored_board(&db, &board).await.unwrap();
24374+ assert_eq!(
24375+ stored
24376+ .get_participants()
24377+ .iter()
24378+ .map(|user| user.key().to_string())
24379+ .collect::<Vec<_>>(),
24380+ vec![veli_id],
24381+ "the roster must reach the row, not just the response"
24382+ );
24383+}
24384+
2434124385 /// The other half of the two-tier line: a participant sees the board and may
2434224386 /// re-title it, but the four commands and the roster/lock arms of `PATCH` are
2434324387 /// the creator's alone β€” a 403, because hiding a board they are already
tests/persistence.rsmodified+1 -1
@@ -1779,7 +1779,7 @@ async fn boards_and_their_strokes_survive_remigration() {
17791779 "POST",
17801780 "/boards",
17811781 Some(&cookie),
1782- Some(json!({ "title": "Geometri", "participant_ids": [veli_id] })),
1782+ Some(json!({ "title": "Geometri", "participants": [veli_id] })),
17831783 )
17841784 .await;
17851785 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
tests/spec_bounds.rsmodified+1 -1
@@ -795,7 +795,7 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
795795 ),
796796 (
797797 "CreateBoard",
798- "participant_ids",
798+ "participants",
799799 "maxItems",
800800 MAX_BOARD_PARTICIPANTS as i64,
801801 ),