diff --git a/README.md b/README.md index 0525c8b..b2144e2 100644 --- a/README.md +++ b/README.md @@ -482,7 +482,14 @@ messages, which any role sends and receives (that's how a parent reaches a teacher). A role change off either end of a tie (the parent stops being a `parent`, the student stops being a `student`) drops the tie, exactly like promotion drops -course enrollments. +course enrollments. A demotion to `parent` also gives back the seats that +account holds on still-open **event signup lists** — a parent cannot reach +`DELETE /events/{id}/register/{user}` and no one else may free a non-student's +seat, so those seats would stay claimed forever and a capped event would answer +"full" for good. Every other role change leaves signups alone: staff free their +own seats by hand. Seats on lists that have already closed (the event started, +or its `ends_at`-only deadline passed) are never touched — that roster is +history, and re-registering is refused. | Action | Minimum role | Notes | |------------------------------------------|--------------|-----------------------------------------------| @@ -650,7 +657,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/users/search` | teacher | `?q=&role=` — find users by username/name fragment (pickers); refs only, no contact info · paged | | GET | `/users` | admin | List all users · paged | | GET | `/users/{id}` | admin | Get one user | -| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) | +| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), and a demotion to `parent` also frees their seats on still-open event signup lists | | PATCH | `/users/{id}/profile` | admin | Update any user's personal info | | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences | | POST | `/users/{id}/students` | admin | `{user_id}` — tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant | @@ -686,11 +693,11 @@ window filtering, before paging; negative values are a `400` naming the field. | DELETE | `/appointments/slots/series/{series}` | teacher | Withdraw a whole recurring publish (same rights); `409` if **any** occurrence has a live booking | | 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 | | GET | `/appointments` | student | Teacher+: bookings on own slots (the request inbox). Everyone else: own requests · paged | -| 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 | +| PATCH | `/appointments/{id}/approve` | teacher | Confirm a pending booking (slot's teacher, or manager+); `409` when settled, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), when the effective window has already started, or when the time collides with another approved meeting of either side | | PATCH | `/appointments/{id}/reject` | teacher | Turn it down (same rights); the slot frees up | | 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 | | 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 | -| PATCH | `/appointments/{id}/reschedule/accept` | student | Requester only: approval at the proposed time (the overlap guard runs again) | +| PATCH | `/appointments/{id}/reschedule/accept` | student | `{proposed_starts_at, proposed_ends_at}` — requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side | | 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) | | 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) | | GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged | @@ -726,7 +733,7 @@ window filtering, before paging; negative values are a `400` naming the field. | DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) | | 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+ | | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged | -| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) | +| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking); a **staff** row — any target whose live role is teacher or higher, not just the session's current teacher — needs manager+ | | 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 | | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged | | 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) | @@ -766,7 +773,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) | | 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) | | 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 | -| 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) | +| 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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) | | 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) | | GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) | | 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") | @@ -951,7 +958,11 @@ someone is a no-op, a full list is a `409`, and the list freezes the moment the event starts — or, when only `ends_at` is set (a pure signup deadline), the moment it passes (register and unregister both). Signup rows survive an audience switch inertly and resurface if the event returns to the registration -kind; deleting the event deletes them. Pre-existing hand-picked (`users`) +kind; deleting the event deletes them, in one transaction with the attendance +rows. A demotion to `parent` sweeps that user's signups off **still-open** +lists and hands each seat back (`PATCH /users/{id}/role`): unregistering is +student-or-self only, so a parent's seat had no other way out. Staff free their +own, and a closed list is never rewritten. Pre-existing hand-picked (`users`) audiences convert on boot: each listed user becomes a signup row credited to the event's creator, and the audience becomes an uncapped registration list. Reading a child collection of a missing parent (`/events/{id}/attendance`, @@ -1059,7 +1070,9 @@ it, so the seat is decided by the database rather than by a count two concurrent bookings can both read as free). The decisions: - `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms. Refused - (`409`) when the effective window has already started. + (`409`) when the effective window has already started, and refused while a + counter-proposal stands: the proposal is the teacher's own, so approving it + here would let them confirm a time the requester never accepted. - `PATCH /{id}/reject` — turns it down; the slot frees up. - `PATCH /{id}/cancel` — **the requester only**, from either live state. Anyone else is a `403`, the slot's teacher and a manager/admin included (the @@ -1078,12 +1091,27 @@ concurrent bookings can both read as free). The decisions: confirmed appointment. The slot stays held meanwhile. A window that has already opened is refused (`409`): the 60-second grace on the times is for clock skew, not for proposing into a meeting already underway — one nobody - could then cancel. -- `PATCH /{id}/reschedule/accept` — the **requester** only: this *is* approval + could then cancel. While the proposal stands, `PATCH /{id}/approve` is + refused (`409`): the effective window is now the teacher's own proposal, so + confirming it there would commit the requester to a time they never agreed + to. Only `/reschedule/accept` may approve at a proposed time, and only the + requester may call it. Re-proposing supersedes the previous proposal, so any + accept still carrying the old one is refused. +- `PATCH /{id}/reschedule/accept` (`{proposed_starts_at, proposed_ends_at}`) — + the **requester** only: this *is* approval at the new time, so the overlap guard runs again — and so does the already-started guard (`409`). Agreeing to a window that has begun does not help: the meeting could never be cancelled. The booking stays `pending`, so the teacher just proposes a time that can still happen. + The body **names the proposal being accepted**, copied from the booking's + `proposed_starts_at`/`proposed_ends_at` as the requester read them. It is not + a request to move the meeting: it pins *which* proposal this answer is for. A + teacher may re-propose at any moment and `/reschedule` takes no lock, so + without the pin the teacher would decide which window the requester's click + commits them to — propose 10:00, wait for them to open the page, propose + 23:00, and their accept lands on 23:00. A superseded pin answers `409` (*the + proposed time has changed*); re-read the booking and accept or decline what + actually stands. - `PATCH /{id}/reschedule/decline` — the requester only, and it **cancels the booking**: the proposal replaced the time that was asked for, so there is nothing to fall back to. The row stays readable as `cancelled` with the @@ -1780,6 +1808,19 @@ Two per-exam policy knobs ride along, both **live-editable** at any point: reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A student may review only when this is on **and** the teacher has marked them (an `ExamResult` row exists); own-scoped, so no student reads another's sheet. + All four reads are refused (`409`) while the caller's latest sitting is still + in progress — a mark on sitting 1 must not open the answer key to someone + midway through sitting 2. Submit the sitting first; an expired one reviews + fine. + + **Known limit, accepted:** that gate is *per exam*. Instantiating one question + bank template into two exams copies its `correct` verbatim into both (the bank + is a copy-into-exam model, not a link), so a student sitting exam A can read + the same question's answer off exam B if B is graded and has review on. The + narrower gate cannot see it, and widening review to "no in-progress sitting on + *any* exam" would close review far too broadly, since `open`-mode sittings + never expire on their own. Teachers reusing one template across a live exam + and a reviewable one should expect that overlap. A student **sits** an exam through attempts (sitting 1, 2, … — each row id is the composite `exam_user[_seq]` key, so a sitting exists at most once by diff --git a/history.txt b/history.txt index 103d7c9..747c6e8 100644 --- a/history.txt +++ b/history.txt @@ -1,101 +1,101 @@ #V2 +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 taught course), **`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 are\\ngrouped into **classes** (*şube* — 9-A, 10-B) when a school teaches that way:\\na class is bulk enrollment and not a second kind of membership — attaching a\\ncourse to it enrolls the whole roster, adding a member enrolls them into every\\ncourse already attached, and what lands are ordinary enrollment rows tagged\\nwith the class that pumped them (untagged = placed by hand, and hand-placed\\nrows are never adopted and never swept). A course without room for everyone\\nrefuses the whole operation, naming it (see \\"Classes (şube)\\"). 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 course 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\\": }`. 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. A role change off `student` also drops the user's **event\\nsignups**, handing each seat back to its event: only students hold signups, so\\nnothing else could ever free one — the seat would sit claimed and a capped\\nevent would answer \\"full\\" forever.\\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| Create / edit / delete a **class** (şube); add or remove its members | manager | Reading classes, their rosters and their course lists is teacher+; a member must be a `student` |\\n| Attach / detach a course on a class | teacher | Course-management rights on **that course** — attaching enrolls the whole class into it, so it takes exactly the right enrolling one student takes |\\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 taught course (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=&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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists — detach that link first — if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member — sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first · paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |\\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); a **staff** row — any target whose live role is teacher or higher, not just the session's current teacher — needs manager+ |\\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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read — nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read — nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 — or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" — a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable — it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |\\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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\": \\"\\"}` (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, and refused while a\\n counter-proposal stands: the proposal is the teacher's own, so approving it\\n here would let them confirm a time the requester never accepted.\\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. While the proposal stands, `PATCH /{id}/approve` is\\n refused (`409`): the effective window is now the teacher's own proposal, so\\n confirming it there would commit the requester to a time they never agreed\\n to. Only `/reschedule/accept` may approve at a proposed time, and only the\\n requester may call it.\\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\\"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\\\\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.\\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 *and classes* may link to one via `term_id` (nullable),\\nand deleting a term is refused with a `409` while any of them still links to\\nit — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with\\n`\\"term_id\\": null`) or delete them first, so the calendar never disappears\\nunder 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- **A slot name may not contain `/`, `\\\\`, `?`, `#` or `%`** — a `400` at\\n `PATCH /settings` when the slot is defined, and again here when a menu is\\n published under one. The name goes verbatim into the menu's record id, and\\n that id is a URL path segment: a slot called `a/b` would publish a menu at\\n `/meals/menus/2026-09-14_a/b`, an address no route can ever match again — the\\n menu could not be read, edited or deleted. Ordinary names are untouched;\\n spaces and Turkish letters percent-encode into one segment as they always\\n have.\\n- **A name the school's stored list already carries is exempt from that rule.**\\n It is younger than the lists it validates, and `PATCH /settings` re-validates\\n the *whole* submitted list — so a school that stored `a/b` before the rule\\n existed could never edit `meal_slots` again: re-sending the name is a `400`\\n and dropping it is a `409` the moment a menu was published under it. The\\n grandfathered name is exactly as unusable as it already was — no menu may be\\n published under it — and dropping it is still the only way to be rid of it.\\n The rule stays in full force for every *new* name.\\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`. Every dish write moves its **menu's** revision in\\nthe same transaction (that is what keeps a booking from freezing a price the\\nmenu has already left, below), which also makes the menu's existence part of\\nthe write: editing or deleting a dish whose menu has since been unpublished is\\na `404`, not a write onto a menu that is gone.\\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+. The exception is the money:\\n`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or\\nthe student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes\\n**and its attendance marks** with it, in the same transaction as the row: a\\ndish has no meaning apart from the menu it was published on, and a menu's\\nrecord id is deterministic on day+slot, so anything left behind would come back\\nattached to the *next* menu published for that meal — the kitchen reading\\n\\"served\\" for a student who never came, priced off food nobody re-entered.\\nCancelled **bookings** deliberately stay: their `attempt` counter is what keeps\\nthe ledger's `(booking, attempt)` ids unique, and a re-book on a republished\\nmenu would otherwise reuse an id the ledger already holds and bill the seat\\nnothing.\\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- **A manager+ may cancel anybody's seat.** Booking is student-and-parent\\n only, and cancelling used to be the same door — which left a seat nobody on\\n the API could give back the moment its student was promoted to staff or its\\n parent was unlinked: the menu refused its own deletion forever and the charge\\n could never be reversed, since cancelling is the only route that reverses\\n one. A role change deliberately sweeps no bookings on its own; moving money\\n is a decision, not a side effect.\\n- **The capacity check is a single conditional write, decided by the\\n database.** Counting rows and then writing one would be write-skew —\\n SurrealDB does not conflict-check a cross-record count against a concurrent\\n insert, so 24 students racing for 3 seats would all pass the count — so the\\n seat is instead claimed on a counter kept on the **menu row itself**, taken\\n and spent by one `UPDATE … WHERE` that also places the booking row in the\\n same transaction. No lock is involved and none would help: a duplicate\\n `POST` rolls its own seat back rather than costing a stranger their place.\\n- **One cutoff closes both ends — for the people it is aimed at.** Within the\\n school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a\\n new 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. It binds\\n **students and parents only**: a manager+ cancelling somebody's seat is not\\n held to it, because the deadline exists to stop students gaming the headcount\\n and that is no reason to leave staff holding a seat they cannot free. Past\\n the cutoff an uncancellable seat also made its menu undeletable forever (a\\n menu with a live booking refuses its own deletion) and its charge\\n unreversable, since cancelling is the only route that reverses one. A meal\\n already closed is therefore still freeable, and its menu still deletable, by\\n manager+ — the same state a school that set no cutoff at all runs under. 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\\nThe menu has to still be there: a mark whose menu is unpublished mid-request is\\na `404` and writes nothing. The existence check *is* the write's own target\\nrather than a read the write then trusts, because a menu's id is deterministic\\non day+slot — an unconditional mark landing just after the delete committed\\nwould be swept by nothing and would reappear as a mark on the next menu\\npublished for that meal.\\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, its row\\n and its money move together in one transaction on *both* sides — the claim\\n writes the charge, the flip writes the reversal — 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, and it is written **by the same\\n transaction that flips the seat** — not appended after it. The two as\\n separate writes left a crash in between with a seat given back and the\\n student still billed, and no later cancel would ever repay it, because the\\n money is keyed to the attempt the flip had already consumed. Folded in, the\\n seat cannot come back without the money. Booking is folded the same way — the\\n charge rides the claim's own transaction, because a charge appended afterwards\\n let a cancel land in the gap, reverse nothing (there was no charge yet), and\\n the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when\\n the charge it undoes is really there, checked inside that same transaction —\\n a refund with no charge behind it invents money. The charge row itself stays.\\n Repeating a cancel replays the reversal, which is what heals a seat flipped\\n before that was true and makes the refund recoverable rather than a one-shot\\n the network can lose; the cutoff is deliberately not re-checked on that path,\\n since the seat is already given back. Re-booking afterwards is a **fresh**\\n charge at the then-current price.\\n- **The price snapshot is pinned by the menu's revision, not by a lock.** The\\n dishes are summed a round trip before the seat is claimed, so a dish landing\\n in between would otherwise be frozen onto the row as \\"the menu was free\\n then\\" — and nothing heals that, since a seat already held is returned as-is,\\n never re-priced. Instead every dish write bumps a revision counter on the\\n menu, and the claim that takes the seat *also* asserts the menu is still at\\n the revision the price was read at: the booking is refused, re-reads, and\\n prices and seats itself again together. A lock around the read could not have\\n promised this — the price is read a round trip before the claim either way —\\n so what is frozen is always a price the menu genuinely carried at the instant\\n the seat was taken. A menu edited over and over under one booking gives up\\n after a few rounds with a `409`.\\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. The target must be a\\n **student, or anyone who already carries meal-ledger lines**: only a student\\n runs up a meal balance, so crediting anyone else is a typo and a typo here is\\n money in the wrong ledger — but a debt outlives its debtor's role change, and\\n the student-only rule alone made a promoted student's debt permanently\\n unsettleable, since no other route appends a credit. A mistyped staff id\\n carries no lines, so it is still a `400`. 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\\n**manager+** or a `parent_link` to that student — **a teacher gets a `403`**,\\nthe one pair in this block narrower than the rest of it. Canteen debt is\\nfamily debt: the money follows the `/payments` rule, not the classroom one,\\nwhile the dietary profile, booking and attendance reads stay teacher+. 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. The\\ncanteen's balance and ledger follow the same rule, for the same reason.\\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 `_k_` (a refund: `_kr_`), 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 `_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 All four reads are refused (`409`) while the caller's latest sitting is still\\n in progress — a mark on sitting 1 must not open the answer key to someone\\n midway through sitting 2. Submit the sitting first; an expired one reviews\\n fine.\\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: 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=` narrows by origin subject, `?owner=` — 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": "classes-ube", "title": "Classes (şube)", "body": "A **class** is the group a school actually teaches in — 9-A, 10-B — and here\\nit is a bulk-enrollment tool rather than a second kind of membership. A class\\nrow carries a name, an optional free-text `grade` label in the school's own\\nvocabulary (`\\"9\\"`, `\\"Lise 2\\"`; `\\"\\"` means no grade, exactly like omitting it)\\nand an optional `term_id`; nothing else about a course changes because a class\\nexists. Schools that run electives or a college-style timetable simply never\\ncreate one — individual enrollment is untouched, and classes are a\\nconvenience.\\n\\n**The pump.** A class holds **members** (students) and **attached courses**,\\nand owes the product of the two: every member enrolled in every attached\\ncourse. So both writes push the same way — attaching a course\\n(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a\\nmember (`POST /classes/{id}/members`) enrolls them into every course the class\\nalready carries — and what gets written is an ordinary `enrollment` row, the\\nsame one `POST /courses/{id}/enrollments` writes, counted against the same\\n`enrollment_count`. Each row a class writes is tagged with it as the row's\\n`source`; **no `source` means placed by hand**, and that one bit is what makes\\nthe sweeps below safe. It rides back out on every enrollment response\\n(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a\\nhand-placed row — without it no client could tell which of the roster rows it\\nis showing a class change is about to remove.\\n\\n**Already enrolled is skipped.** A pair that already has an enrollment row is\\nleft exactly as it stands — no second seat charged, no `source` rewritten. A\\nstudent a teacher enrolled by hand *stays* hand-placed when the class later\\nattaches that course, so the class never quietly adopts someone else's roster\\ndecision.\\n\\n**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims\\none seat per pair that needs a new row, each against its own course's\\n`capacity` — and if any single course has no room the whole call is a `409`\\nnaming it (`course: is full, so the class cannot take this student`,\\n`course: cannot hold the whole class`). Nothing lands, not even the seats\\nclaimed earlier in the same run: a half-enrolled class is worse than a refused\\none, and the refusal names the course whose capacity to raise.\\n\\nA second `409` reads off the same claim and is deliberately told apart from it:\\none of the class's attached courses **no longer exists**\\n(`course: no longer exists — detach it from this class first`). A seat\\nclaim that matches nothing means \\"full\\" *or* \\"no such row\\", and reporting a\\nstale attachment as a full course would send staff off to raise a capacity that\\nis not there — on a class every member-add now fails on. Detach the link and\\nthe class works again.\\n\\n**Removals take back only what the class pumped, and repair before they\\ndelete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or\\ndetaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the\\nenrollment rows whose `source` is *this* class and no others — hand-placed\\nrows survive every class operation. Even a tagged row is not automatically\\ndeleted: if a **second class** still claims that pair (it holds the same\\nstudent *and* that course attached), the row is re-tagged to that class\\ninstead, because the row it skipped writing is the row now being swept and the\\nstudent is still owed the seat. The heir is the lowest class id among the\\nclaimants, so repeating a sweep lands on the same class. Only a row nobody is\\nleft to claim is deleted and its seat handed back. Sweeps also tolerate rows\\nthat are already gone — deleting a course wipes its enrollments wholesale\\nwhile the class memberships survive — so \\"this class has a member\\" and \\"that\\nmember holds a pumped row\\" are independent facts.\\n\\n**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}`\\non a pumped student is allowed and sticks: nothing re-pumps them while they\\nremain a member, because the pump runs on writes, never on a schedule. Staff\\nput them back by enrolling them by hand (which makes the row hand-placed) or\\nby detaching and re-attaching the course.\\n\\n**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`\\nlanding on a row a class pumped takes the row *off* that class — its `source`\\nis cleared, the response comes back with `\\"source\\": null` — so no later class\\nsweep can undo a placement an operator made on purpose. That is the mirror of\\nthe rule above: hand-placed beats pumped in both directions, and without it\\n\\"hand-placed\\" was a state only a *first* enroll could ever reach.\\n\\n**Delete guards.** A class still holding members or attached courses refuses\\ndeletion with a `409` (\\"remove its members and detach its courses first\\") —\\nthe roster it owes is never dropped out from under the courses silently. A\\nterm linked by any class refuses deletion the same way courses make it refuse.\\nDeleting a **course** detaches it from every class it was on (its enrollments\\ngo with it), and a role change that takes a user off `student` drops their\\nclass memberships exactly as it drops their enrollments — in one transaction,\\nbecause a membership left behind would keep pumping them back into courses,\\nwhile an enrollment left behind would stay tagged with a class the released\\ncounters had already made deletable, and nothing could ever sweep it again.\\n\\n**A link to a deleted course detaches instead of refusing.** Should a\\n`class_course` row ever be left pointing at a course row that is gone,\\n`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights\\nare read *off* the course, so a stale link had no readable owner and the detach\\nused to `404` forever — which also left the class permanently undeletable, its\\nattachment counter counting a row nothing could sweep. There is no roster left\\nto protect, and the caller is already teacher+.\\n\\n**Who may.** Creating, editing and deleting a class, and adding or removing\\nits members, is **manager+** — a class is school structure, not classroom\\nwork. Attaching or detaching a course takes management rights on **that\\ncourse** (its creator, a teacher assigned to it, or manager+), since the call\\nwrites that course's roster and nothing else: the same right enrolling one\\nstudent takes. Every read (`GET /classes`, `/classes/{id}`, its members and\\nits courses, all paged, newest first) is **teacher+** — and \\"newest\\" here means\\nwhen the student was *added* or the course *attached*, not the student's or the\\ncourse's own id, which is what a link row keyed on the pair would otherwise\\nsort by. Rows written before that stamp existed carry none, and sort last.\\n\\n**Codes.** Adding a member or attaching a course answers `201`; a repeat is a\\n`409` (\\"the student is already in this class\\", \\"the course is already on this\\nclass\\"). An id in the **body** that names nothing — an unknown `user_id` or\\n`course_id`, or a member who is not a `student` — is a `400`; an id in the\\n**path** that names nothing (the class, or a member/course that was not on it)\\nis a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, **at most 200 students\\nand 50 courses** per class (`max_class_members`, `max_class_courses`), all four\\npublished in the `course` group of `GET /limits`. Past either ceiling the\\nadd or the attach is a `409` naming it (\\"this class already holds 200\\nstudents\\") — a standing class someone can make room in, which is why it is not\\nthe `404` a deleted class answers. Those two numbers are not comfort limits:\\nadding a member writes one enrollment per attached course and attaching a\\ncourse writes one per member, both in a *single* transaction, so each axis's\\nceiling is the bound on the other axis's write loop — an unbounded class is an\\nunbounded transaction any manager could trigger.\\n\\nWhich is why each write is refused on the **other** axis too. A class already\\nstanding *above* a ceiling cannot take a member while it holds more than 50\\ncourses (\\"this class holds more than 50 courses — detach some before adding a\\nstudent\\"), nor a course while it holds more than 200 students (\\"this class\\nholds more than 200 students — remove some before attaching a course\\"), both\\n`409`. Room on the axis being written is not the question: the write loop's\\nlength is set by the other one, and letting it run because *this* side has\\nspace is exactly the unbounded transaction the ceilings exist to prevent. Only\\na class that predates the ceilings can be there, and only shrinking the\\noverloaded axis clears it.", "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\\": \\"\\", \\"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\\": \\"\\" } }\\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 the field never changes name\\nbetween a request and a reply. That is the *only* thing the shared spelling\\nbuys: unlike the rest of this API, the two board request bodies **reject an\\nunknown key** (`422`) rather than ignoring it, because a misspelled roster\\nwould otherwise open a board its author is silently alone on. So a body must\\ncarry **only** the fields that request accepts — a board it just read is not a\\nlegal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all\\nunknown to `POST` and `PATCH`. A read-modify-write client sends the writable\\nfields it changed, never the whole board object back.\\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**A blank canvas cannot be cleared** (`409` — as a closed board is, while a\\nparticipant who is not the creator gets the `403` the two doors above give\\nthem). The marker is a real stored row and it is charged to the board's\\nlifetime budget, so a clear has to close at least one mark to be worth one —\\nwithout that rule every press of a button the creator can hold down minted a\\nfree row, and the epoch index filled with zero-stroke sessions.\\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 It counts **rows on the board**, not strokes drawn: a `clear` marker is a\\n stored row, so it costs one unit of the budget like any mark. The marker's\\n own unit is the one thing not refused at the ceiling — the last stroke of a\\n board's budget may well be closed by a clear, and refusing that would drop\\n the very marker the history needs to index the final epoch — so a board holds\\n at most `max_board_strokes + 1` rows. That held only for boards born after\\n the marker started paying, so **boot recomputes every board's\\n `total_stroke_count` from its actual rows**: a board an older binary cleared\\n is short exactly one per past clear, and an under-counting board is one that\\n keeps taking marks past the storage ceiling. This is the one backfill that is\\n not `= NONE`-guarded, and the one counter that may be recomputed — it is not\\n an opinion the live system maintains, it is the board's row count, so\\n recomputing converges instead of overwriting and the next boot writes nothing.\\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\\":\\"\\", \\"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), `canvas_blank` (there was nothing on the canvas to clear\\n— the board is still live and still drawable), `board_closed` (permanently\\nread-only), `locked`, `forbidden` (a creator-only command from a participant),\\n`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload),\\n`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\nThe two that look alike are the two that must not be confused: `board_closed`\\nis **terminal** and `canvas_blank` is **nothing to do**. A client that treats\\nthem alike sends a live room off clearing a canvas it never needed to lose —\\nwhich is exactly what a code guessed from a *substring* of the refusal did\\n(\\"the canvas is already blank\\" contains the word \\"closed\\"), so the server now\\nmatches the refusal constants by value and a test pairs every one of them with\\nthe code its client must act on.\\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. The one exception is a counter\\nthat is not an opinion but a plain row count — a board's `total_stroke_count`,\\nrecomputed from its strokes on every boot rather than seeded once, which is why\\nthat repair heals an under-count the `= NONE` guard would have skipped.\\nIn-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; `source`\\n names the class that pumped it, absent when hand-placed)\\n class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;\\n deletable only with no members and no attached courses)\\n class_member.rs ClassMember (one student in a class; adding them enrolls\\n them into every course the class holds)\\n class_course.rs ClassCourse (one course on a class; attaching it enrolls\\n the class's whole roster)\\n class_pump.rs attach/detach (the shared transaction behind both of those:\\n link row, class counter and the enrollments it implies move\\n together or not at all)\\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 `_`; 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 (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 classes.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"}]; +INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "9f2c3caf48fb60b75d5a22093a3486acf212d820b25387d42fae5da1e63f30c3"}]; +DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii; DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25; DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25; REMOVE TABLE IF EXISTS endpoint; -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=&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=` filters by origin subject, `?owner=` (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\\") |"}]; +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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u2014 each row carries `source`, the class that pumped it or `null` for hand-placed \\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": "classes", "routes": "| POST | `/classes` | manager | `{name, grade?, term_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class \\u2014 `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` \\u2014 add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists \\u2014 detach that link first \\u2014 if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first \\u00b7 paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member \\u2014 sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` \\u2014 attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first \\u00b7 paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) \\u2014 the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |"}, {"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); a **staff** row \\u2014 any target whose live role is teacher or higher, not just the session's current teacher \\u2014 needs manager+ |"}, {"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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read \\u2014 nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read \\u2014 nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 \\u2014 or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" \\u2014 a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable \\u2014 it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) \\u2014 its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** \\u2014 a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link \\u2014 a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |"}, {"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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\") |"}]; +SELECT VALUE sha256 FROM meta:readme; REMOVE TABLE IF EXISTS doc; REMOVE TABLE IF EXISTS meta; -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\\": }`. 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=&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=&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=` filters by origin subject, `?owner=` (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\\": \\"\\"}` (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 `_k_` (a refund: `_kr_`), 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 `_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: 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=` narrows by origin subject, `?owner=` — 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\\": \\"\\", \\"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\\": \\"\\" } }\\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\\":\\"\\", \\"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 `_`; 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 (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"}]; -INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "e68a65f85e3d7ee237d59c79c8f1dca0ea1a9ed2088eeede2a6732c6294ce561"}]; +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 taught course), **`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 are\\ngrouped into **classes** (*şube* — 9-A, 10-B) when a school teaches that way:\\na class is bulk enrollment and not a second kind of membership — attaching a\\ncourse to it enrolls the whole roster, adding a member enrolls them into every\\ncourse already attached, and what lands are ordinary enrollment rows tagged\\nwith the class that pumped them (untagged = placed by hand, and hand-placed\\nrows are never adopted and never swept). A course without room for everyone\\nrefuses the whole operation, naming it (see \\"Classes (şube)\\"). 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 course 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\\": }`. 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. A role change off `student` also drops the user's **event\\nsignups**, handing each seat back to its event: only students hold signups, so\\nnothing else could ever free one — the seat would sit claimed and a capped\\nevent would answer \\"full\\" forever.\\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| Create / edit / delete a **class** (şube); add or remove its members | manager | Reading classes, their rosters and their course lists is teacher+; a member must be a `student` |\\n| Attach / detach a course on a class | teacher | Course-management rights on **that course** — attaching enrolls the whole class into it, so it takes exactly the right enrolling one student takes |\\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 taught course (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=&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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists — detach that link first — if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member — sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first · paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |\\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); a **staff** row — any target whose live role is teacher or higher, not just the session's current teacher — needs manager+ |\\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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read — nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read — nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 — or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" — a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable — it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |\\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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\": \\"\\"}` (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, in one transaction with the attendance\\nrows. A role change off `student` sweeps the user's signups and hands each\\nseat back (`PATCH /users/{id}/role`): unregistering is student-or-self only,\\nso a demoted holder's seat had no other way out and a capped event stayed\\nfull forever. 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, and refused while a\\n counter-proposal stands: the proposal is the teacher's own, so approving it\\n here would let them confirm a time the requester never accepted.\\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. While the proposal stands, `PATCH /{id}/approve` is\\n refused (`409`): the effective window is now the teacher's own proposal, so\\n confirming it there would commit the requester to a time they never agreed\\n to. Only `/reschedule/accept` may approve at a proposed time, and only the\\n requester may call it.\\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\\"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\\\\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.\\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 *and classes* may link to one via `term_id` (nullable),\\nand deleting a term is refused with a `409` while any of them still links to\\nit — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with\\n`\\"term_id\\": null`) or delete them first, so the calendar never disappears\\nunder 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- **A slot name may not contain `/`, `\\\\`, `?`, `#` or `%`** — a `400` at\\n `PATCH /settings` when the slot is defined, and again here when a menu is\\n published under one. The name goes verbatim into the menu's record id, and\\n that id is a URL path segment: a slot called `a/b` would publish a menu at\\n `/meals/menus/2026-09-14_a/b`, an address no route can ever match again — the\\n menu could not be read, edited or deleted. Ordinary names are untouched;\\n spaces and Turkish letters percent-encode into one segment as they always\\n have.\\n- **A name the school's stored list already carries is exempt from that rule.**\\n It is younger than the lists it validates, and `PATCH /settings` re-validates\\n the *whole* submitted list — so a school that stored `a/b` before the rule\\n existed could never edit `meal_slots` again: re-sending the name is a `400`\\n and dropping it is a `409` the moment a menu was published under it. The\\n grandfathered name is exactly as unusable as it already was — no menu may be\\n published under it — and dropping it is still the only way to be rid of it.\\n The rule stays in full force for every *new* name.\\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`. Every dish write moves its **menu's** revision in\\nthe same transaction (that is what keeps a booking from freezing a price the\\nmenu has already left, below), which also makes the menu's existence part of\\nthe write: editing or deleting a dish whose menu has since been unpublished is\\na `404`, not a write onto a menu that is gone.\\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+. The exception is the money:\\n`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or\\nthe student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes\\n**and its attendance marks** with it, in the same transaction as the row: a\\ndish has no meaning apart from the menu it was published on, and a menu's\\nrecord id is deterministic on day+slot, so anything left behind would come back\\nattached to the *next* menu published for that meal — the kitchen reading\\n\\"served\\" for a student who never came, priced off food nobody re-entered.\\nCancelled **bookings** deliberately stay: their `attempt` counter is what keeps\\nthe ledger's `(booking, attempt)` ids unique, and a re-book on a republished\\nmenu would otherwise reuse an id the ledger already holds and bill the seat\\nnothing.\\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- **A manager+ may cancel anybody's seat.** Booking is student-and-parent\\n only, and cancelling used to be the same door — which left a seat nobody on\\n the API could give back the moment its student was promoted to staff or its\\n parent was unlinked: the menu refused its own deletion forever and the charge\\n could never be reversed, since cancelling is the only route that reverses\\n one. A role change deliberately sweeps no bookings on its own; moving money\\n is a decision, not a side effect.\\n- **The capacity check is a single conditional write, decided by the\\n database.** Counting rows and then writing one would be write-skew —\\n SurrealDB does not conflict-check a cross-record count against a concurrent\\n insert, so 24 students racing for 3 seats would all pass the count — so the\\n seat is instead claimed on a counter kept on the **menu row itself**, taken\\n and spent by one `UPDATE … WHERE` that also places the booking row in the\\n same transaction. No lock is involved and none would help: a duplicate\\n `POST` rolls its own seat back rather than costing a stranger their place.\\n- **One cutoff closes both ends — for the people it is aimed at.** Within the\\n school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a\\n new 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. It binds\\n **students and parents only**: a manager+ cancelling somebody's seat is not\\n held to it, because the deadline exists to stop students gaming the headcount\\n and that is no reason to leave staff holding a seat they cannot free. Past\\n the cutoff an uncancellable seat also made its menu undeletable forever (a\\n menu with a live booking refuses its own deletion) and its charge\\n unreversable, since cancelling is the only route that reverses one. A meal\\n already closed is therefore still freeable, and its menu still deletable, by\\n manager+ — the same state a school that set no cutoff at all runs under. 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\\nThe menu has to still be there: a mark whose menu is unpublished mid-request is\\na `404` and writes nothing. The existence check *is* the write's own target\\nrather than a read the write then trusts, because a menu's id is deterministic\\non day+slot — an unconditional mark landing just after the delete committed\\nwould be swept by nothing and would reappear as a mark on the next menu\\npublished for that meal.\\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, its row\\n and its money move together in one transaction on *both* sides — the claim\\n writes the charge, the flip writes the reversal — 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, and it is written **by the same\\n transaction that flips the seat** — not appended after it. The two as\\n separate writes left a crash in between with a seat given back and the\\n student still billed, and no later cancel would ever repay it, because the\\n money is keyed to the attempt the flip had already consumed. Folded in, the\\n seat cannot come back without the money. Booking is folded the same way — the\\n charge rides the claim's own transaction, because a charge appended afterwards\\n let a cancel land in the gap, reverse nothing (there was no charge yet), and\\n the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when\\n the charge it undoes is really there, checked inside that same transaction —\\n a refund with no charge behind it invents money. The charge row itself stays.\\n Repeating a cancel replays the reversal, which is what heals a seat flipped\\n before that was true and makes the refund recoverable rather than a one-shot\\n the network can lose; the cutoff is deliberately not re-checked on that path,\\n since the seat is already given back. Re-booking afterwards is a **fresh**\\n charge at the then-current price.\\n- **The price snapshot is pinned by the menu's revision, not by a lock.** The\\n dishes are summed a round trip before the seat is claimed, so a dish landing\\n in between would otherwise be frozen onto the row as \\"the menu was free\\n then\\" — and nothing heals that, since a seat already held is returned as-is,\\n never re-priced. Instead every dish write bumps a revision counter on the\\n menu, and the claim that takes the seat *also* asserts the menu is still at\\n the revision the price was read at: the booking is refused, re-reads, and\\n prices and seats itself again together. A lock around the read could not have\\n promised this — the price is read a round trip before the claim either way —\\n so what is frozen is always a price the menu genuinely carried at the instant\\n the seat was taken. A menu edited over and over under one booking gives up\\n after a few rounds with a `409`.\\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. The target must be a\\n **student, or anyone who already carries meal-ledger lines**: only a student\\n runs up a meal balance, so crediting anyone else is a typo and a typo here is\\n money in the wrong ledger — but a debt outlives its debtor's role change, and\\n the student-only rule alone made a promoted student's debt permanently\\n unsettleable, since no other route appends a credit. A mistyped staff id\\n carries no lines, so it is still a `400`. 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\\n**manager+** or a `parent_link` to that student — **a teacher gets a `403`**,\\nthe one pair in this block narrower than the rest of it. Canteen debt is\\nfamily debt: the money follows the `/payments` rule, not the classroom one,\\nwhile the dietary profile, booking and attendance reads stay teacher+. 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. The\\ncanteen's balance and ledger follow the same rule, for the same reason.\\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 `_k_` (a refund: `_kr_`), 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 `_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 All four reads are refused (`409`) while the caller's latest sitting is still\\n in progress — a mark on sitting 1 must not open the answer key to someone\\n midway through sitting 2. Submit the sitting first; an expired one reviews\\n fine.\\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: 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=` narrows by origin subject, `?owner=` — 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": "classes-ube", "title": "Classes (şube)", "body": "A **class** is the group a school actually teaches in — 9-A, 10-B — and here\\nit is a bulk-enrollment tool rather than a second kind of membership. A class\\nrow carries a name, an optional free-text `grade` label in the school's own\\nvocabulary (`\\"9\\"`, `\\"Lise 2\\"`; `\\"\\"` means no grade, exactly like omitting it)\\nand an optional `term_id`; nothing else about a course changes because a class\\nexists. Schools that run electives or a college-style timetable simply never\\ncreate one — individual enrollment is untouched, and classes are a\\nconvenience.\\n\\n**The pump.** A class holds **members** (students) and **attached courses**,\\nand owes the product of the two: every member enrolled in every attached\\ncourse. So both writes push the same way — attaching a course\\n(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a\\nmember (`POST /classes/{id}/members`) enrolls them into every course the class\\nalready carries — and what gets written is an ordinary `enrollment` row, the\\nsame one `POST /courses/{id}/enrollments` writes, counted against the same\\n`enrollment_count`. Each row a class writes is tagged with it as the row's\\n`source`; **no `source` means placed by hand**, and that one bit is what makes\\nthe sweeps below safe. It rides back out on every enrollment response\\n(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a\\nhand-placed row — without it no client could tell which of the roster rows it\\nis showing a class change is about to remove.\\n\\n**Already enrolled is skipped.** A pair that already has an enrollment row is\\nleft exactly as it stands — no second seat charged, no `source` rewritten. A\\nstudent a teacher enrolled by hand *stays* hand-placed when the class later\\nattaches that course, so the class never quietly adopts someone else's roster\\ndecision.\\n\\n**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims\\none seat per pair that needs a new row, each against its own course's\\n`capacity` — and if any single course has no room the whole call is a `409`\\nnaming it (`course: is full, so the class cannot take this student`,\\n`course: cannot hold the whole class`). Nothing lands, not even the seats\\nclaimed earlier in the same run: a half-enrolled class is worse than a refused\\none, and the refusal names the course whose capacity to raise.\\n\\nA second `409` reads off the same claim and is deliberately told apart from it:\\none of the class's attached courses **no longer exists**\\n(`course: no longer exists — detach it from this class first`). A seat\\nclaim that matches nothing means \\"full\\" *or* \\"no such row\\", and reporting a\\nstale attachment as a full course would send staff off to raise a capacity that\\nis not there — on a class every member-add now fails on. Detach the link and\\nthe class works again.\\n\\n**Removals take back only what the class pumped, and repair before they\\ndelete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or\\ndetaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the\\nenrollment rows whose `source` is *this* class and no others — hand-placed\\nrows survive every class operation. Even a tagged row is not automatically\\ndeleted: if a **second class** still claims that pair (it holds the same\\nstudent *and* that course attached), the row is re-tagged to that class\\ninstead, because the row it skipped writing is the row now being swept and the\\nstudent is still owed the seat. The heir is the lowest class id among the\\nclaimants, so repeating a sweep lands on the same class. Only a row nobody is\\nleft to claim is deleted and its seat handed back. Sweeps also tolerate rows\\nthat are already gone — deleting a course wipes its enrollments wholesale\\nwhile the class memberships survive — so \\"this class has a member\\" and \\"that\\nmember holds a pumped row\\" are independent facts.\\n\\n**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}`\\non a pumped student is allowed and sticks: nothing re-pumps them while they\\nremain a member, because the pump runs on writes, never on a schedule. Staff\\nput them back by enrolling them by hand (which makes the row hand-placed) or\\nby detaching and re-attaching the course.\\n\\n**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`\\nlanding on a row a class pumped takes the row *off* that class — its `source`\\nis cleared, the response comes back with `\\"source\\": null` — so no later class\\nsweep can undo a placement an operator made on purpose. That is the mirror of\\nthe rule above: hand-placed beats pumped in both directions, and without it\\n\\"hand-placed\\" was a state only a *first* enroll could ever reach.\\n\\n**Delete guards.** A class still holding members or attached courses refuses\\ndeletion with a `409` (\\"remove its members and detach its courses first\\") —\\nthe roster it owes is never dropped out from under the courses silently. A\\nterm linked by any class refuses deletion the same way courses make it refuse.\\nDeleting a **course** detaches it from every class it was on (its enrollments\\ngo with it), and a role change that takes a user off `student` drops their\\nclass memberships exactly as it drops their enrollments — in one transaction,\\nbecause a membership left behind would keep pumping them back into courses,\\nwhile an enrollment left behind would stay tagged with a class the released\\ncounters had already made deletable, and nothing could ever sweep it again.\\n\\n**A link to a deleted course detaches instead of refusing.** Should a\\n`class_course` row ever be left pointing at a course row that is gone,\\n`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights\\nare read *off* the course, so a stale link had no readable owner and the detach\\nused to `404` forever — which also left the class permanently undeletable, its\\nattachment counter counting a row nothing could sweep. There is no roster left\\nto protect, and the caller is already teacher+.\\n\\n**Who may.** Creating, editing and deleting a class, and adding or removing\\nits members, is **manager+** — a class is school structure, not classroom\\nwork. Attaching or detaching a course takes management rights on **that\\ncourse** (its creator, a teacher assigned to it, or manager+), since the call\\nwrites that course's roster and nothing else: the same right enrolling one\\nstudent takes. Every read (`GET /classes`, `/classes/{id}`, its members and\\nits courses, all paged, newest first) is **teacher+** — and \\"newest\\" here means\\nwhen the student was *added* or the course *attached*, not the student's or the\\ncourse's own id, which is what a link row keyed on the pair would otherwise\\nsort by. Rows written before that stamp existed carry none, and sort last.\\n\\n**Codes.** Adding a member or attaching a course answers `201`; a repeat is a\\n`409` (\\"the student is already in this class\\", \\"the course is already on this\\nclass\\"). An id in the **body** that names nothing — an unknown `user_id` or\\n`course_id`, or a member who is not a `student` — is a `400`; an id in the\\n**path** that names nothing (the class, or a member/course that was not on it)\\nis a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, **at most 200 students\\nand 50 courses** per class (`max_class_members`, `max_class_courses`), all four\\npublished in the `course` group of `GET /limits`. Past either ceiling the\\nadd or the attach is a `409` naming it (\\"this class already holds 200\\nstudents\\") — a standing class someone can make room in, which is why it is not\\nthe `404` a deleted class answers. Those two numbers are not comfort limits:\\nadding a member writes one enrollment per attached course and attaching a\\ncourse writes one per member, both in a *single* transaction, so each axis's\\nceiling is the bound on the other axis's write loop — an unbounded class is an\\nunbounded transaction any manager could trigger.\\n\\nWhich is why each write is refused on the **other** axis too. A class already\\nstanding *above* a ceiling cannot take a member while it holds more than 50\\ncourses (\\"this class holds more than 50 courses — detach some before adding a\\nstudent\\"), nor a course while it holds more than 200 students (\\"this class\\nholds more than 200 students — remove some before attaching a course\\"), both\\n`409`. Room on the axis being written is not the question: the write loop's\\nlength is set by the other one, and letting it run because *this* side has\\nspace is exactly the unbounded transaction the ceilings exist to prevent. Only\\na class that predates the ceilings can be there, and only shrinking the\\noverloaded axis clears it.", "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\\": \\"\\", \\"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\\": \\"\\" } }\\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 the field never changes name\\nbetween a request and a reply. That is the *only* thing the shared spelling\\nbuys: unlike the rest of this API, the two board request bodies **reject an\\nunknown key** (`422`) rather than ignoring it, because a misspelled roster\\nwould otherwise open a board its author is silently alone on. So a body must\\ncarry **only** the fields that request accepts — a board it just read is not a\\nlegal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all\\nunknown to `POST` and `PATCH`. A read-modify-write client sends the writable\\nfields it changed, never the whole board object back.\\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**A blank canvas cannot be cleared** (`409` — as a closed board is, while a\\nparticipant who is not the creator gets the `403` the two doors above give\\nthem). The marker is a real stored row and it is charged to the board's\\nlifetime budget, so a clear has to close at least one mark to be worth one —\\nwithout that rule every press of a button the creator can hold down minted a\\nfree row, and the epoch index filled with zero-stroke sessions.\\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 It counts **rows on the board**, not strokes drawn: a `clear` marker is a\\n stored row, so it costs one unit of the budget like any mark. The marker's\\n own unit is the one thing not refused at the ceiling — the last stroke of a\\n board's budget may well be closed by a clear, and refusing that would drop\\n the very marker the history needs to index the final epoch — so a board holds\\n at most `max_board_strokes + 1` rows. That held only for boards born after\\n the marker started paying, so **boot recomputes every board's\\n `total_stroke_count` from its actual rows**: a board an older binary cleared\\n is short exactly one per past clear, and an under-counting board is one that\\n keeps taking marks past the storage ceiling. This is the one backfill that is\\n not `= NONE`-guarded, and the one counter that may be recomputed — it is not\\n an opinion the live system maintains, it is the board's row count, so\\n recomputing converges instead of overwriting and the next boot writes nothing.\\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\\":\\"\\", \\"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), `canvas_blank` (there was nothing on the canvas to clear\\n— the board is still live and still drawable), `board_closed` (permanently\\nread-only), `locked`, `forbidden` (a creator-only command from a participant),\\n`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload),\\n`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\nThe two that look alike are the two that must not be confused: `board_closed`\\nis **terminal** and `canvas_blank` is **nothing to do**. A client that treats\\nthem alike sends a live room off clearing a canvas it never needed to lose —\\nwhich is exactly what a code guessed from a *substring* of the refusal did\\n(\\"the canvas is already blank\\" contains the word \\"closed\\"), so the server now\\nmatches the refusal constants by value and a test pairs every one of them with\\nthe code its client must act on.\\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. The one exception is a counter\\nthat is not an opinion but a plain row count — a board's `total_stroke_count`,\\nrecomputed from its strokes on every boot rather than seeded once, which is why\\nthat repair heals an under-count the `= NONE` guard would have skipped.\\nIn-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; `source`\\n names the class that pumped it, absent when hand-placed)\\n class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;\\n deletable only with no members and no attached courses)\\n class_member.rs ClassMember (one student in a class; adding them enrolls\\n them into every course the class holds)\\n class_course.rs ClassCourse (one course on a class; attaching it enrolls\\n the class's whole roster)\\n class_pump.rs attach/detach (the shared transaction behind both of those:\\n link row, class counter and the enrollments it implies move\\n together or not at all)\\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 `_`; 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 (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 classes.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"}]; +INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "d00f73e53f50245dfe6bac71a02ff78718a35cf7b2caf59640bb342a6c54a8db"}]; DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii; DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25; DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25; REMOVE TABLE IF EXISTS endpoint; -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=&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=` filters by origin subject, `?owner=` (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\\") |"}]; +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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u2014 each row carries `source`, the class that pumped it or `null` for hand-placed \\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": "classes", "routes": "| POST | `/classes` | manager | `{name, grade?, term_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class \\u2014 `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` \\u2014 add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists \\u2014 detach that link first \\u2014 if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first \\u00b7 paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member \\u2014 sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` \\u2014 attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first \\u00b7 paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) \\u2014 the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |"}, {"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); a **staff** row \\u2014 any target whose live role is teacher or higher, not just the session's current teacher \\u2014 needs manager+ |"}, {"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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read \\u2014 nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read \\u2014 nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 \\u2014 or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" \\u2014 a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable \\u2014 it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) \\u2014 its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** \\u2014 a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link \\u2014 a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |"}, {"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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\") |"}]; SELECT sha256 FROM meta:readme; +CREATE ev:a SET registration_count = 1; +CREATE reg:r1 SET event = ev:a, user = usr:u; +BEGIN TRANSACTION; LET $gone = (DELETE reg WHERE user = usr:u RETURN BEFORE); FOR $row IN ($gone ?? []) { UPDATE $row.event SET registration_count = math::max([(registration_count ?? 0) - 1, 0]); }; COMMIT TRANSACTION; +SELECT * FROM ev; +SELECT * FROM reg; +CREATE reg:r2 SET event = ev:ghost, user = usr:v; +BEGIN TRANSACTION; LET $gone = (DELETE reg WHERE user = usr:v RETURN BEFORE); FOR $row IN ($gone ?? []) { UPDATE $row.event SET registration_count = math::max([(registration_count ?? 0) - 1, 0]); }; COMMIT TRANSACTION; +SELECT * FROM ev; +SELECT * FROM reg; +CREATE ev:b SET registration_count = 0; +CREATE reg:r3 SET event = ev:b, user = usr:w; +CREATE ev:c SET registration_count = 2; +CREATE reg:r4 SET event = ev:c, user = usr:w; +BEGIN TRANSACTION; LET $gone = (DELETE reg WHERE user = usr:w RETURN BEFORE); FOR $row IN ($gone ?? []) { UPDATE $row.event SET registration_count = math::max([(registration_count ?? 0) - 1, 0]); }; COMMIT TRANSACTION; +SELECT id, registration_count FROM ev:b, ev:c; +DEFINE TABLE ev SCHEMAFULL; DEFINE FIELD title ON ev TYPE string; DEFINE FIELD registration_count ON ev TYPE option; +CREATE ev:a SET title = 'x', registration_count = 1; +CREATE reg:r2 SET event = ev:ghost, user = usr:v; +BEGIN TRANSACTION; LET $gone = (DELETE reg WHERE user = usr:v RETURN BEFORE); FOR $row IN ($gone ?? []) { UPDATE $row.event SET registration_count = math::max([(registration_count ?? 0) - 1, 0]); }; COMMIT TRANSACTION; +SELECT * FROM ev; +SELECT * FROM reg; SELECT VALUE sha256 FROM meta:readme; REMOVE TABLE IF EXISTS doc; REMOVE TABLE IF EXISTS meta; -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\\": }`. 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=&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=&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=` filters by origin subject, `?owner=` (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\\": \\"\\"}` (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 `_k_` (a refund: `_kr_`), 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 `_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: 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=` narrows by origin subject, `?owner=` — 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\\": \\"\\", \\"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\\": \\"\\" } }\\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\\":\\"\\", \\"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 `_`; 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 (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"}]; -INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "592d24c8e4b3aa8bba80caa0887acc3610096296f9fe26183256708aeeeb5a32"}]; +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 taught course), **`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 are\\ngrouped into **classes** (*şube* — 9-A, 10-B) when a school teaches that way:\\na class is bulk enrollment and not a second kind of membership — attaching a\\ncourse to it enrolls the whole roster, adding a member enrolls them into every\\ncourse already attached, and what lands are ordinary enrollment rows tagged\\nwith the class that pumped them (untagged = placed by hand, and hand-placed\\nrows are never adopted and never swept). A course without room for everyone\\nrefuses the whole operation, naming it (see \\"Classes (şube)\\"). 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 course 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\\": }`. 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. A role change off `student` also drops the user's **event\\nsignups**, handing each seat back to its event: only students hold signups, so\\nnothing else could ever free one — the seat would sit claimed and a capped\\nevent would answer \\"full\\" forever.\\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| Create / edit / delete a **class** (şube); add or remove its members | manager | Reading classes, their rosters and their course lists is teacher+; a member must be a `student` |\\n| Attach / detach a course on a class | teacher | Course-management rights on **that course** — attaching enrolls the whole class into it, so it takes exactly the right enrolling one student takes |\\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 taught course (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=&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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` — requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists — detach that link first — if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member — sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first · paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |\\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); a **staff** row — any target whose live role is teacher or higher, not just the session's current teacher — needs manager+ |\\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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read — nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read — nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 — or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" — a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable — it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |\\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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\": \\"\\"}` (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, in one transaction with the attendance\\nrows. A role change off `student` sweeps the user's signups and hands each\\nseat back (`PATCH /users/{id}/role`): unregistering is student-or-self only,\\nso a demoted holder's seat had no other way out and a capped event stayed\\nfull forever. 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, and refused while a\\n counter-proposal stands: the proposal is the teacher's own, so approving it\\n here would let them confirm a time the requester never accepted.\\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. While the proposal stands, `PATCH /{id}/approve` is\\n refused (`409`): the effective window is now the teacher's own proposal, so\\n confirming it there would commit the requester to a time they never agreed\\n to. Only `/reschedule/accept` may approve at a proposed time, and only the\\n requester may call it.\\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\\"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\\\\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.\\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 *and classes* may link to one via `term_id` (nullable),\\nand deleting a term is refused with a `409` while any of them still links to\\nit — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with\\n`\\"term_id\\": null`) or delete them first, so the calendar never disappears\\nunder 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- **A slot name may not contain `/`, `\\\\`, `?`, `#` or `%`** — a `400` at\\n `PATCH /settings` when the slot is defined, and again here when a menu is\\n published under one. The name goes verbatim into the menu's record id, and\\n that id is a URL path segment: a slot called `a/b` would publish a menu at\\n `/meals/menus/2026-09-14_a/b`, an address no route can ever match again — the\\n menu could not be read, edited or deleted. Ordinary names are untouched;\\n spaces and Turkish letters percent-encode into one segment as they always\\n have.\\n- **A name the school's stored list already carries is exempt from that rule.**\\n It is younger than the lists it validates, and `PATCH /settings` re-validates\\n the *whole* submitted list — so a school that stored `a/b` before the rule\\n existed could never edit `meal_slots` again: re-sending the name is a `400`\\n and dropping it is a `409` the moment a menu was published under it. The\\n grandfathered name is exactly as unusable as it already was — no menu may be\\n published under it — and dropping it is still the only way to be rid of it.\\n The rule stays in full force for every *new* name.\\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`. Every dish write moves its **menu's** revision in\\nthe same transaction (that is what keeps a booking from freezing a price the\\nmenu has already left, below), which also makes the menu's existence part of\\nthe write: editing or deleting a dish whose menu has since been unpublished is\\na `404`, not a write onto a menu that is gone.\\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+. The exception is the money:\\n`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or\\nthe student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes\\n**and its attendance marks** with it, in the same transaction as the row: a\\ndish has no meaning apart from the menu it was published on, and a menu's\\nrecord id is deterministic on day+slot, so anything left behind would come back\\nattached to the *next* menu published for that meal — the kitchen reading\\n\\"served\\" for a student who never came, priced off food nobody re-entered.\\nCancelled **bookings** deliberately stay: their `attempt` counter is what keeps\\nthe ledger's `(booking, attempt)` ids unique, and a re-book on a republished\\nmenu would otherwise reuse an id the ledger already holds and bill the seat\\nnothing.\\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- **A manager+ may cancel anybody's seat.** Booking is student-and-parent\\n only, and cancelling used to be the same door — which left a seat nobody on\\n the API could give back the moment its student was promoted to staff or its\\n parent was unlinked: the menu refused its own deletion forever and the charge\\n could never be reversed, since cancelling is the only route that reverses\\n one. A role change deliberately sweeps no bookings on its own; moving money\\n is a decision, not a side effect.\\n- **The capacity check is a single conditional write, decided by the\\n database.** Counting rows and then writing one would be write-skew —\\n SurrealDB does not conflict-check a cross-record count against a concurrent\\n insert, so 24 students racing for 3 seats would all pass the count — so the\\n seat is instead claimed on a counter kept on the **menu row itself**, taken\\n and spent by one `UPDATE … WHERE` that also places the booking row in the\\n same transaction. No lock is involved and none would help: a duplicate\\n `POST` rolls its own seat back rather than costing a stranger their place.\\n- **One cutoff closes both ends — for the people it is aimed at.** Within the\\n school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a\\n new 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. It binds\\n **students and parents only**: a manager+ cancelling somebody's seat is not\\n held to it, because the deadline exists to stop students gaming the headcount\\n and that is no reason to leave staff holding a seat they cannot free. Past\\n the cutoff an uncancellable seat also made its menu undeletable forever (a\\n menu with a live booking refuses its own deletion) and its charge\\n unreversable, since cancelling is the only route that reverses one. A meal\\n already closed is therefore still freeable, and its menu still deletable, by\\n manager+ — the same state a school that set no cutoff at all runs under. 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\\nThe menu has to still be there: a mark whose menu is unpublished mid-request is\\na `404` and writes nothing. The existence check *is* the write's own target\\nrather than a read the write then trusts, because a menu's id is deterministic\\non day+slot — an unconditional mark landing just after the delete committed\\nwould be swept by nothing and would reappear as a mark on the next menu\\npublished for that meal.\\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, its row\\n and its money move together in one transaction on *both* sides — the claim\\n writes the charge, the flip writes the reversal — 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, and it is written **by the same\\n transaction that flips the seat** — not appended after it. The two as\\n separate writes left a crash in between with a seat given back and the\\n student still billed, and no later cancel would ever repay it, because the\\n money is keyed to the attempt the flip had already consumed. Folded in, the\\n seat cannot come back without the money. Booking is folded the same way — the\\n charge rides the claim's own transaction, because a charge appended afterwards\\n let a cancel land in the gap, reverse nothing (there was no charge yet), and\\n the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when\\n the charge it undoes is really there, checked inside that same transaction —\\n a refund with no charge behind it invents money. The charge row itself stays.\\n Repeating a cancel replays the reversal, which is what heals a seat flipped\\n before that was true and makes the refund recoverable rather than a one-shot\\n the network can lose; the cutoff is deliberately not re-checked on that path,\\n since the seat is already given back. Re-booking afterwards is a **fresh**\\n charge at the then-current price.\\n- **The price snapshot is pinned by the menu's revision, not by a lock.** The\\n dishes are summed a round trip before the seat is claimed, so a dish landing\\n in between would otherwise be frozen onto the row as \\"the menu was free\\n then\\" — and nothing heals that, since a seat already held is returned as-is,\\n never re-priced. Instead every dish write bumps a revision counter on the\\n menu, and the claim that takes the seat *also* asserts the menu is still at\\n the revision the price was read at: the booking is refused, re-reads, and\\n prices and seats itself again together. A lock around the read could not have\\n promised this — the price is read a round trip before the claim either way —\\n so what is frozen is always a price the menu genuinely carried at the instant\\n the seat was taken. A menu edited over and over under one booking gives up\\n after a few rounds with a `409`.\\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. The target must be a\\n **student, or anyone who already carries meal-ledger lines**: only a student\\n runs up a meal balance, so crediting anyone else is a typo and a typo here is\\n money in the wrong ledger — but a debt outlives its debtor's role change, and\\n the student-only rule alone made a promoted student's debt permanently\\n unsettleable, since no other route appends a credit. A mistyped staff id\\n carries no lines, so it is still a `400`. 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\\n**manager+** or a `parent_link` to that student — **a teacher gets a `403`**,\\nthe one pair in this block narrower than the rest of it. Canteen debt is\\nfamily debt: the money follows the `/payments` rule, not the classroom one,\\nwhile the dietary profile, booking and attendance reads stay teacher+. 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. The\\ncanteen's balance and ledger follow the same rule, for the same reason.\\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 `_k_` (a refund: `_kr_`), 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 `_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 All four reads are refused (`409`) while the caller's latest sitting is still\\n in progress — a mark on sitting 1 must not open the answer key to someone\\n midway through sitting 2. Submit the sitting first; an expired one reviews\\n fine.\\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: 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=` narrows by origin subject, `?owner=` — 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": "classes-ube", "title": "Classes (şube)", "body": "A **class** is the group a school actually teaches in — 9-A, 10-B — and here\\nit is a bulk-enrollment tool rather than a second kind of membership. A class\\nrow carries a name, an optional free-text `grade` label in the school's own\\nvocabulary (`\\"9\\"`, `\\"Lise 2\\"`; `\\"\\"` means no grade, exactly like omitting it)\\nand an optional `term_id`; nothing else about a course changes because a class\\nexists. Schools that run electives or a college-style timetable simply never\\ncreate one — individual enrollment is untouched, and classes are a\\nconvenience.\\n\\n**The pump.** A class holds **members** (students) and **attached courses**,\\nand owes the product of the two: every member enrolled in every attached\\ncourse. So both writes push the same way — attaching a course\\n(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a\\nmember (`POST /classes/{id}/members`) enrolls them into every course the class\\nalready carries — and what gets written is an ordinary `enrollment` row, the\\nsame one `POST /courses/{id}/enrollments` writes, counted against the same\\n`enrollment_count`. Each row a class writes is tagged with it as the row's\\n`source`; **no `source` means placed by hand**, and that one bit is what makes\\nthe sweeps below safe. It rides back out on every enrollment response\\n(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a\\nhand-placed row — without it no client could tell which of the roster rows it\\nis showing a class change is about to remove.\\n\\n**Already enrolled is skipped.** A pair that already has an enrollment row is\\nleft exactly as it stands — no second seat charged, no `source` rewritten. A\\nstudent a teacher enrolled by hand *stays* hand-placed when the class later\\nattaches that course, so the class never quietly adopts someone else's roster\\ndecision.\\n\\n**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims\\none seat per pair that needs a new row, each against its own course's\\n`capacity` — and if any single course has no room the whole call is a `409`\\nnaming it (`course: is full, so the class cannot take this student`,\\n`course: cannot hold the whole class`). Nothing lands, not even the seats\\nclaimed earlier in the same run: a half-enrolled class is worse than a refused\\none, and the refusal names the course whose capacity to raise.\\n\\nA second `409` reads off the same claim and is deliberately told apart from it:\\none of the class's attached courses **no longer exists**\\n(`course: no longer exists — detach it from this class first`). A seat\\nclaim that matches nothing means \\"full\\" *or* \\"no such row\\", and reporting a\\nstale attachment as a full course would send staff off to raise a capacity that\\nis not there — on a class every member-add now fails on. Detach the link and\\nthe class works again.\\n\\n**Removals take back only what the class pumped, and repair before they\\ndelete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or\\ndetaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the\\nenrollment rows whose `source` is *this* class and no others — hand-placed\\nrows survive every class operation. Even a tagged row is not automatically\\ndeleted: if a **second class** still claims that pair (it holds the same\\nstudent *and* that course attached), the row is re-tagged to that class\\ninstead, because the row it skipped writing is the row now being swept and the\\nstudent is still owed the seat. The heir is the lowest class id among the\\nclaimants, so repeating a sweep lands on the same class. Only a row nobody is\\nleft to claim is deleted and its seat handed back. Sweeps also tolerate rows\\nthat are already gone — deleting a course wipes its enrollments wholesale\\nwhile the class memberships survive — so \\"this class has a member\\" and \\"that\\nmember holds a pumped row\\" are independent facts.\\n\\n**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}`\\non a pumped student is allowed and sticks: nothing re-pumps them while they\\nremain a member, because the pump runs on writes, never on a schedule. Staff\\nput them back by enrolling them by hand (which makes the row hand-placed) or\\nby detaching and re-attaching the course.\\n\\n**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`\\nlanding on a row a class pumped takes the row *off* that class — its `source`\\nis cleared, the response comes back with `\\"source\\": null` — so no later class\\nsweep can undo a placement an operator made on purpose. That is the mirror of\\nthe rule above: hand-placed beats pumped in both directions, and without it\\n\\"hand-placed\\" was a state only a *first* enroll could ever reach.\\n\\n**Delete guards.** A class still holding members or attached courses refuses\\ndeletion with a `409` (\\"remove its members and detach its courses first\\") —\\nthe roster it owes is never dropped out from under the courses silently. A\\nterm linked by any class refuses deletion the same way courses make it refuse.\\nDeleting a **course** detaches it from every class it was on (its enrollments\\ngo with it), and a role change that takes a user off `student` drops their\\nclass memberships exactly as it drops their enrollments — in one transaction,\\nbecause a membership left behind would keep pumping them back into courses,\\nwhile an enrollment left behind would stay tagged with a class the released\\ncounters had already made deletable, and nothing could ever sweep it again.\\n\\n**A link to a deleted course detaches instead of refusing.** Should a\\n`class_course` row ever be left pointing at a course row that is gone,\\n`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights\\nare read *off* the course, so a stale link had no readable owner and the detach\\nused to `404` forever — which also left the class permanently undeletable, its\\nattachment counter counting a row nothing could sweep. There is no roster left\\nto protect, and the caller is already teacher+.\\n\\n**Who may.** Creating, editing and deleting a class, and adding or removing\\nits members, is **manager+** — a class is school structure, not classroom\\nwork. Attaching or detaching a course takes management rights on **that\\ncourse** (its creator, a teacher assigned to it, or manager+), since the call\\nwrites that course's roster and nothing else: the same right enrolling one\\nstudent takes. Every read (`GET /classes`, `/classes/{id}`, its members and\\nits courses, all paged, newest first) is **teacher+** — and \\"newest\\" here means\\nwhen the student was *added* or the course *attached*, not the student's or the\\ncourse's own id, which is what a link row keyed on the pair would otherwise\\nsort by. Rows written before that stamp existed carry none, and sort last.\\n\\n**Codes.** Adding a member or attaching a course answers `201`; a repeat is a\\n`409` (\\"the student is already in this class\\", \\"the course is already on this\\nclass\\"). An id in the **body** that names nothing — an unknown `user_id` or\\n`course_id`, or a member who is not a `student` — is a `400`; an id in the\\n**path** that names nothing (the class, or a member/course that was not on it)\\nis a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, **at most 200 students\\nand 50 courses** per class (`max_class_members`, `max_class_courses`), all four\\npublished in the `course` group of `GET /limits`. Past either ceiling the\\nadd or the attach is a `409` naming it (\\"this class already holds 200\\nstudents\\") — a standing class someone can make room in, which is why it is not\\nthe `404` a deleted class answers. Those two numbers are not comfort limits:\\nadding a member writes one enrollment per attached course and attaching a\\ncourse writes one per member, both in a *single* transaction, so each axis's\\nceiling is the bound on the other axis's write loop — an unbounded class is an\\nunbounded transaction any manager could trigger.\\n\\nWhich is why each write is refused on the **other** axis too. A class already\\nstanding *above* a ceiling cannot take a member while it holds more than 50\\ncourses (\\"this class holds more than 50 courses — detach some before adding a\\nstudent\\"), nor a course while it holds more than 200 students (\\"this class\\nholds more than 200 students — remove some before attaching a course\\"), both\\n`409`. Room on the axis being written is not the question: the write loop's\\nlength is set by the other one, and letting it run because *this* side has\\nspace is exactly the unbounded transaction the ceilings exist to prevent. Only\\na class that predates the ceilings can be there, and only shrinking the\\noverloaded axis clears it.", "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\\": \\"\\", \\"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\\": \\"\\" } }\\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 the field never changes name\\nbetween a request and a reply. That is the *only* thing the shared spelling\\nbuys: unlike the rest of this API, the two board request bodies **reject an\\nunknown key** (`422`) rather than ignoring it, because a misspelled roster\\nwould otherwise open a board its author is silently alone on. So a body must\\ncarry **only** the fields that request accepts — a board it just read is not a\\nlegal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all\\nunknown to `POST` and `PATCH`. A read-modify-write client sends the writable\\nfields it changed, never the whole board object back.\\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**A blank canvas cannot be cleared** (`409` — as a closed board is, while a\\nparticipant who is not the creator gets the `403` the two doors above give\\nthem). The marker is a real stored row and it is charged to the board's\\nlifetime budget, so a clear has to close at least one mark to be worth one —\\nwithout that rule every press of a button the creator can hold down minted a\\nfree row, and the epoch index filled with zero-stroke sessions.\\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 It counts **rows on the board**, not strokes drawn: a `clear` marker is a\\n stored row, so it costs one unit of the budget like any mark. The marker's\\n own unit is the one thing not refused at the ceiling — the last stroke of a\\n board's budget may well be closed by a clear, and refusing that would drop\\n the very marker the history needs to index the final epoch — so a board holds\\n at most `max_board_strokes + 1` rows. That held only for boards born after\\n the marker started paying, so **boot recomputes every board's\\n `total_stroke_count` from its actual rows**: a board an older binary cleared\\n is short exactly one per past clear, and an under-counting board is one that\\n keeps taking marks past the storage ceiling. This is the one backfill that is\\n not `= NONE`-guarded, and the one counter that may be recomputed — it is not\\n an opinion the live system maintains, it is the board's row count, so\\n recomputing converges instead of overwriting and the next boot writes nothing.\\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\\":\\"\\", \\"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), `canvas_blank` (there was nothing on the canvas to clear\\n— the board is still live and still drawable), `board_closed` (permanently\\nread-only), `locked`, `forbidden` (a creator-only command from a participant),\\n`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload),\\n`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\nThe two that look alike are the two that must not be confused: `board_closed`\\nis **terminal** and `canvas_blank` is **nothing to do**. A client that treats\\nthem alike sends a live room off clearing a canvas it never needed to lose —\\nwhich is exactly what a code guessed from a *substring* of the refusal did\\n(\\"the canvas is already blank\\" contains the word \\"closed\\"), so the server now\\nmatches the refusal constants by value and a test pairs every one of them with\\nthe code its client must act on.\\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. The one exception is a counter\\nthat is not an opinion but a plain row count — a board's `total_stroke_count`,\\nrecomputed from its strokes on every boot rather than seeded once, which is why\\nthat repair heals an under-count the `= NONE` guard would have skipped.\\nIn-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; `source`\\n names the class that pumped it, absent when hand-placed)\\n class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;\\n deletable only with no members and no attached courses)\\n class_member.rs ClassMember (one student in a class; adding them enrolls\\n them into every course the class holds)\\n class_course.rs ClassCourse (one course on a class; attaching it enrolls\\n the class's whole roster)\\n class_pump.rs attach/detach (the shared transaction behind both of those:\\n link row, class counter and the enrollments it implies move\\n together or not at all)\\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 `_`; 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 (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 classes.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"}]; +INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "ad0eb480378d502151e323a63c8a5a2c5fb6f1659325479f4417ffd0145c4488"}]; DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii; DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25; DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25; REMOVE TABLE IF EXISTS endpoint; -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=&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=` filters by origin subject, `?owner=` (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\\") |"}]; +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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` \\u2014 requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u2014 each row carries `source`, the class that pumped it or `null` for hand-placed \\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": "classes", "routes": "| POST | `/classes` | manager | `{name, grade?, term_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class \\u2014 `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` \\u2014 add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists \\u2014 detach that link first \\u2014 if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first \\u00b7 paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member \\u2014 sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` \\u2014 attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first \\u00b7 paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) \\u2014 the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |"}, {"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); a **staff** row \\u2014 any target whose live role is teacher or higher, not just the session's current teacher \\u2014 needs manager+ |"}, {"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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read \\u2014 nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read \\u2014 nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 \\u2014 or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" \\u2014 a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable \\u2014 it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) \\u2014 its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** \\u2014 a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link \\u2014 a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |"}, {"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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\") |"}]; SELECT VALUE sha256 FROM meta:readme; REMOVE TABLE IF EXISTS doc; REMOVE TABLE IF EXISTS meta; -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\\": }`. 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=&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=&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=` filters by origin subject, `?owner=` (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\\": \\"\\"}` (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 `_k_` (a refund: `_kr_`), 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 `_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: 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=` narrows by origin subject, `?owner=` — 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\\": \\"\\", \\"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\\": \\"\\" } }\\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\\":\\"\\", \\"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 `_`; 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 (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"}]; -INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "711eb80e75da71b94c688418d680df9e365086460d6ec628b81cb20e19d7b605"}]; +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 taught course), **`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 are\\ngrouped into **classes** (*şube* — 9-A, 10-B) when a school teaches that way:\\na class is bulk enrollment and not a second kind of membership — attaching a\\ncourse to it enrolls the whole roster, adding a member enrolls them into every\\ncourse already attached, and what lands are ordinary enrollment rows tagged\\nwith the class that pumped them (untagged = placed by hand, and hand-placed\\nrows are never adopted and never swept). A course without room for everyone\\nrefuses the whole operation, naming it (see \\"Classes (şube)\\"). 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 course 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\\": }`. 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. A role change off `student` also drops the user's **event\\nsignups**, handing each seat back to its event: only students hold signups, so\\nnothing else could ever free one — the seat would sit claimed and a capped\\nevent would answer \\"full\\" forever.\\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| Create / edit / delete a **class** (şube); add or remove its members | manager | Reading classes, their rosters and their course lists is teacher+; a member must be a `student` |\\n| Attach / detach a course on a class | teacher | Course-management rights on **that course** — attaching enrolls the whole class into it, so it takes exactly the right enrolling one student takes |\\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 taught course (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=&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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` — requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists — detach that link first — if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member — sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first · paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |\\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); a **staff** row — any target whose live role is teacher or higher, not just the session's current teacher — needs manager+ |\\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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read — nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read — nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 — or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" — a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable — it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |\\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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\": \\"\\"}` (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, in one transaction with the attendance\\nrows. A role change off `student` sweeps the user's signups and hands each\\nseat back (`PATCH /users/{id}/role`): unregistering is student-or-self only,\\nso a demoted holder's seat had no other way out and a capped event stayed\\nfull forever. 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, and refused while a\\n counter-proposal stands: the proposal is the teacher's own, so approving it\\n here would let them confirm a time the requester never accepted.\\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. While the proposal stands, `PATCH /{id}/approve` is\\n refused (`409`): the effective window is now the teacher's own proposal, so\\n confirming it there would commit the requester to a time they never agreed\\n to. Only `/reschedule/accept` may approve at a proposed time, and only the\\n requester may call it.\\n- `PATCH /{id}/reschedule/accept` (`{proposed_starts_at, proposed_ends_at}`) —\\n 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 The body **names the proposal being accepted**, copied from the booking's\\n `proposed_starts_at`/`proposed_ends_at` as the requester read them. It is not\\n a request to move the meeting: it pins *which* proposal this answer is for. A\\n teacher may re-propose at any moment and `/reschedule` takes no lock, so\\n without the pin the teacher would decide which window the requester's click\\n commits them to — propose 10:00, wait for them to open the page, propose\\n 23:00, and their accept lands on 23:00. A superseded pin answers `409` (*the\\n proposed time has changed*); re-read the booking and accept or decline what\\n actually stands.\\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\\"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\\\\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.\\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 *and classes* may link to one via `term_id` (nullable),\\nand deleting a term is refused with a `409` while any of them still links to\\nit — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with\\n`\\"term_id\\": null`) or delete them first, so the calendar never disappears\\nunder 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- **A slot name may not contain `/`, `\\\\`, `?`, `#` or `%`** — a `400` at\\n `PATCH /settings` when the slot is defined, and again here when a menu is\\n published under one. The name goes verbatim into the menu's record id, and\\n that id is a URL path segment: a slot called `a/b` would publish a menu at\\n `/meals/menus/2026-09-14_a/b`, an address no route can ever match again — the\\n menu could not be read, edited or deleted. Ordinary names are untouched;\\n spaces and Turkish letters percent-encode into one segment as they always\\n have.\\n- **A name the school's stored list already carries is exempt from that rule.**\\n It is younger than the lists it validates, and `PATCH /settings` re-validates\\n the *whole* submitted list — so a school that stored `a/b` before the rule\\n existed could never edit `meal_slots` again: re-sending the name is a `400`\\n and dropping it is a `409` the moment a menu was published under it. The\\n grandfathered name is exactly as unusable as it already was — no menu may be\\n published under it — and dropping it is still the only way to be rid of it.\\n The rule stays in full force for every *new* name.\\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`. Every dish write moves its **menu's** revision in\\nthe same transaction (that is what keeps a booking from freezing a price the\\nmenu has already left, below), which also makes the menu's existence part of\\nthe write: editing or deleting a dish whose menu has since been unpublished is\\na `404`, not a write onto a menu that is gone.\\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+. The exception is the money:\\n`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or\\nthe student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes\\n**and its attendance marks** with it, in the same transaction as the row: a\\ndish has no meaning apart from the menu it was published on, and a menu's\\nrecord id is deterministic on day+slot, so anything left behind would come back\\nattached to the *next* menu published for that meal — the kitchen reading\\n\\"served\\" for a student who never came, priced off food nobody re-entered.\\nCancelled **bookings** deliberately stay: their `attempt` counter is what keeps\\nthe ledger's `(booking, attempt)` ids unique, and a re-book on a republished\\nmenu would otherwise reuse an id the ledger already holds and bill the seat\\nnothing.\\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- **A manager+ may cancel anybody's seat.** Booking is student-and-parent\\n only, and cancelling used to be the same door — which left a seat nobody on\\n the API could give back the moment its student was promoted to staff or its\\n parent was unlinked: the menu refused its own deletion forever and the charge\\n could never be reversed, since cancelling is the only route that reverses\\n one. A role change deliberately sweeps no bookings on its own; moving money\\n is a decision, not a side effect.\\n- **The capacity check is a single conditional write, decided by the\\n database.** Counting rows and then writing one would be write-skew —\\n SurrealDB does not conflict-check a cross-record count against a concurrent\\n insert, so 24 students racing for 3 seats would all pass the count — so the\\n seat is instead claimed on a counter kept on the **menu row itself**, taken\\n and spent by one `UPDATE … WHERE` that also places the booking row in the\\n same transaction. No lock is involved and none would help: a duplicate\\n `POST` rolls its own seat back rather than costing a stranger their place.\\n- **One cutoff closes both ends — for the people it is aimed at.** Within the\\n school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a\\n new 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. It binds\\n **students and parents only**: a manager+ cancelling somebody's seat is not\\n held to it, because the deadline exists to stop students gaming the headcount\\n and that is no reason to leave staff holding a seat they cannot free. Past\\n the cutoff an uncancellable seat also made its menu undeletable forever (a\\n menu with a live booking refuses its own deletion) and its charge\\n unreversable, since cancelling is the only route that reverses one. A meal\\n already closed is therefore still freeable, and its menu still deletable, by\\n manager+ — the same state a school that set no cutoff at all runs under. 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\\nThe menu has to still be there: a mark whose menu is unpublished mid-request is\\na `404` and writes nothing. The existence check *is* the write's own target\\nrather than a read the write then trusts, because a menu's id is deterministic\\non day+slot — an unconditional mark landing just after the delete committed\\nwould be swept by nothing and would reappear as a mark on the next menu\\npublished for that meal.\\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, its row\\n and its money move together in one transaction on *both* sides — the claim\\n writes the charge, the flip writes the reversal — 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, and it is written **by the same\\n transaction that flips the seat** — not appended after it. The two as\\n separate writes left a crash in between with a seat given back and the\\n student still billed, and no later cancel would ever repay it, because the\\n money is keyed to the attempt the flip had already consumed. Folded in, the\\n seat cannot come back without the money. Booking is folded the same way — the\\n charge rides the claim's own transaction, because a charge appended afterwards\\n let a cancel land in the gap, reverse nothing (there was no charge yet), and\\n the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when\\n the charge it undoes is really there, checked inside that same transaction —\\n a refund with no charge behind it invents money. The charge row itself stays.\\n Repeating a cancel replays the reversal, which is what heals a seat flipped\\n before that was true and makes the refund recoverable rather than a one-shot\\n the network can lose; the cutoff is deliberately not re-checked on that path,\\n since the seat is already given back. Re-booking afterwards is a **fresh**\\n charge at the then-current price.\\n- **The price snapshot is pinned by the menu's revision, not by a lock.** The\\n dishes are summed a round trip before the seat is claimed, so a dish landing\\n in between would otherwise be frozen onto the row as \\"the menu was free\\n then\\" — and nothing heals that, since a seat already held is returned as-is,\\n never re-priced. Instead every dish write bumps a revision counter on the\\n menu, and the claim that takes the seat *also* asserts the menu is still at\\n the revision the price was read at: the booking is refused, re-reads, and\\n prices and seats itself again together. A lock around the read could not have\\n promised this — the price is read a round trip before the claim either way —\\n so what is frozen is always a price the menu genuinely carried at the instant\\n the seat was taken. A menu edited over and over under one booking gives up\\n after a few rounds with a `409`.\\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. The target must be a\\n **student, or anyone who already carries meal-ledger lines**: only a student\\n runs up a meal balance, so crediting anyone else is a typo and a typo here is\\n money in the wrong ledger — but a debt outlives its debtor's role change, and\\n the student-only rule alone made a promoted student's debt permanently\\n unsettleable, since no other route appends a credit. A mistyped staff id\\n carries no lines, so it is still a `400`. 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\\n**manager+** or a `parent_link` to that student — **a teacher gets a `403`**,\\nthe one pair in this block narrower than the rest of it. Canteen debt is\\nfamily debt: the money follows the `/payments` rule, not the classroom one,\\nwhile the dietary profile, booking and attendance reads stay teacher+. 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. The\\ncanteen's balance and ledger follow the same rule, for the same reason.\\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 `_k_` (a refund: `_kr_`), 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 `_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 All four reads are refused (`409`) while the caller's latest sitting is still\\n in progress — a mark on sitting 1 must not open the answer key to someone\\n midway through sitting 2. Submit the sitting first; an expired one reviews\\n fine.\\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: 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=` narrows by origin subject, `?owner=` — 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": "classes-ube", "title": "Classes (şube)", "body": "A **class** is the group a school actually teaches in — 9-A, 10-B — and here\\nit is a bulk-enrollment tool rather than a second kind of membership. A class\\nrow carries a name, an optional free-text `grade` label in the school's own\\nvocabulary (`\\"9\\"`, `\\"Lise 2\\"`; `\\"\\"` means no grade, exactly like omitting it)\\nand an optional `term_id`; nothing else about a course changes because a class\\nexists. Schools that run electives or a college-style timetable simply never\\ncreate one — individual enrollment is untouched, and classes are a\\nconvenience.\\n\\n**The pump.** A class holds **members** (students) and **attached courses**,\\nand owes the product of the two: every member enrolled in every attached\\ncourse. So both writes push the same way — attaching a course\\n(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a\\nmember (`POST /classes/{id}/members`) enrolls them into every course the class\\nalready carries — and what gets written is an ordinary `enrollment` row, the\\nsame one `POST /courses/{id}/enrollments` writes, counted against the same\\n`enrollment_count`. Each row a class writes is tagged with it as the row's\\n`source`; **no `source` means placed by hand**, and that one bit is what makes\\nthe sweeps below safe. It rides back out on every enrollment response\\n(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a\\nhand-placed row — without it no client could tell which of the roster rows it\\nis showing a class change is about to remove.\\n\\n**Already enrolled is skipped.** A pair that already has an enrollment row is\\nleft exactly as it stands — no second seat charged, no `source` rewritten. A\\nstudent a teacher enrolled by hand *stays* hand-placed when the class later\\nattaches that course, so the class never quietly adopts someone else's roster\\ndecision.\\n\\n**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims\\none seat per pair that needs a new row, each against its own course's\\n`capacity` — and if any single course has no room the whole call is a `409`\\nnaming it (`course: is full, so the class cannot take this student`,\\n`course: cannot hold the whole class`). Nothing lands, not even the seats\\nclaimed earlier in the same run: a half-enrolled class is worse than a refused\\none, and the refusal names the course whose capacity to raise.\\n\\nA second `409` reads off the same claim and is deliberately told apart from it:\\none of the class's attached courses **no longer exists**\\n(`course: no longer exists — detach it from this class first`). A seat\\nclaim that matches nothing means \\"full\\" *or* \\"no such row\\", and reporting a\\nstale attachment as a full course would send staff off to raise a capacity that\\nis not there — on a class every member-add now fails on. Detach the link and\\nthe class works again.\\n\\n**Removals take back only what the class pumped, and repair before they\\ndelete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or\\ndetaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the\\nenrollment rows whose `source` is *this* class and no others — hand-placed\\nrows survive every class operation. Even a tagged row is not automatically\\ndeleted: if a **second class** still claims that pair (it holds the same\\nstudent *and* that course attached), the row is re-tagged to that class\\ninstead, because the row it skipped writing is the row now being swept and the\\nstudent is still owed the seat. The heir is the lowest class id among the\\nclaimants, so repeating a sweep lands on the same class. Only a row nobody is\\nleft to claim is deleted and its seat handed back. Sweeps also tolerate rows\\nthat are already gone — deleting a course wipes its enrollments wholesale\\nwhile the class memberships survive — so \\"this class has a member\\" and \\"that\\nmember holds a pumped row\\" are independent facts.\\n\\n**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}`\\non a pumped student is allowed and sticks: nothing re-pumps them while they\\nremain a member, because the pump runs on writes, never on a schedule. Staff\\nput them back by enrolling them by hand (which makes the row hand-placed) or\\nby detaching and re-attaching the course.\\n\\n**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`\\nlanding on a row a class pumped takes the row *off* that class — its `source`\\nis cleared, the response comes back with `\\"source\\": null` — so no later class\\nsweep can undo a placement an operator made on purpose. That is the mirror of\\nthe rule above: hand-placed beats pumped in both directions, and without it\\n\\"hand-placed\\" was a state only a *first* enroll could ever reach.\\n\\n**Delete guards.** A class still holding members or attached courses refuses\\ndeletion with a `409` (\\"remove its members and detach its courses first\\") —\\nthe roster it owes is never dropped out from under the courses silently. A\\nterm linked by any class refuses deletion the same way courses make it refuse.\\nDeleting a **course** detaches it from every class it was on (its enrollments\\ngo with it), and a role change that takes a user off `student` drops their\\nclass memberships exactly as it drops their enrollments — in one transaction,\\nbecause a membership left behind would keep pumping them back into courses,\\nwhile an enrollment left behind would stay tagged with a class the released\\ncounters had already made deletable, and nothing could ever sweep it again.\\n\\n**A link to a deleted course detaches instead of refusing.** Should a\\n`class_course` row ever be left pointing at a course row that is gone,\\n`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights\\nare read *off* the course, so a stale link had no readable owner and the detach\\nused to `404` forever — which also left the class permanently undeletable, its\\nattachment counter counting a row nothing could sweep. There is no roster left\\nto protect, and the caller is already teacher+.\\n\\n**Who may.** Creating, editing and deleting a class, and adding or removing\\nits members, is **manager+** — a class is school structure, not classroom\\nwork. Attaching or detaching a course takes management rights on **that\\ncourse** (its creator, a teacher assigned to it, or manager+), since the call\\nwrites that course's roster and nothing else: the same right enrolling one\\nstudent takes. Every read (`GET /classes`, `/classes/{id}`, its members and\\nits courses, all paged, newest first) is **teacher+** — and \\"newest\\" here means\\nwhen the student was *added* or the course *attached*, not the student's or the\\ncourse's own id, which is what a link row keyed on the pair would otherwise\\nsort by. Rows written before that stamp existed carry none, and sort last.\\n\\n**Codes.** Adding a member or attaching a course answers `201`; a repeat is a\\n`409` (\\"the student is already in this class\\", \\"the course is already on this\\nclass\\"). An id in the **body** that names nothing — an unknown `user_id` or\\n`course_id`, or a member who is not a `student` — is a `400`; an id in the\\n**path** that names nothing (the class, or a member/course that was not on it)\\nis a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, **at most 200 students\\nand 50 courses** per class (`max_class_members`, `max_class_courses`), all four\\npublished in the `course` group of `GET /limits`. Past either ceiling the\\nadd or the attach is a `409` naming it (\\"this class already holds 200\\nstudents\\") — a standing class someone can make room in, which is why it is not\\nthe `404` a deleted class answers. Those two numbers are not comfort limits:\\nadding a member writes one enrollment per attached course and attaching a\\ncourse writes one per member, both in a *single* transaction, so each axis's\\nceiling is the bound on the other axis's write loop — an unbounded class is an\\nunbounded transaction any manager could trigger.\\n\\nWhich is why each write is refused on the **other** axis too. A class already\\nstanding *above* a ceiling cannot take a member while it holds more than 50\\ncourses (\\"this class holds more than 50 courses — detach some before adding a\\nstudent\\"), nor a course while it holds more than 200 students (\\"this class\\nholds more than 200 students — remove some before attaching a course\\"), both\\n`409`. Room on the axis being written is not the question: the write loop's\\nlength is set by the other one, and letting it run because *this* side has\\nspace is exactly the unbounded transaction the ceilings exist to prevent. Only\\na class that predates the ceilings can be there, and only shrinking the\\noverloaded axis clears it.", "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\\": \\"\\", \\"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\\": \\"\\" } }\\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 the field never changes name\\nbetween a request and a reply. That is the *only* thing the shared spelling\\nbuys: unlike the rest of this API, the two board request bodies **reject an\\nunknown key** (`422`) rather than ignoring it, because a misspelled roster\\nwould otherwise open a board its author is silently alone on. So a body must\\ncarry **only** the fields that request accepts — a board it just read is not a\\nlegal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all\\nunknown to `POST` and `PATCH`. A read-modify-write client sends the writable\\nfields it changed, never the whole board object back.\\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**A blank canvas cannot be cleared** (`409` — as a closed board is, while a\\nparticipant who is not the creator gets the `403` the two doors above give\\nthem). The marker is a real stored row and it is charged to the board's\\nlifetime budget, so a clear has to close at least one mark to be worth one —\\nwithout that rule every press of a button the creator can hold down minted a\\nfree row, and the epoch index filled with zero-stroke sessions.\\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 It counts **rows on the board**, not strokes drawn: a `clear` marker is a\\n stored row, so it costs one unit of the budget like any mark. The marker's\\n own unit is the one thing not refused at the ceiling — the last stroke of a\\n board's budget may well be closed by a clear, and refusing that would drop\\n the very marker the history needs to index the final epoch — so a board holds\\n at most `max_board_strokes + 1` rows. That held only for boards born after\\n the marker started paying, so **boot recomputes every board's\\n `total_stroke_count` from its actual rows**: a board an older binary cleared\\n is short exactly one per past clear, and an under-counting board is one that\\n keeps taking marks past the storage ceiling. This is the one backfill that is\\n not `= NONE`-guarded, and the one counter that may be recomputed — it is not\\n an opinion the live system maintains, it is the board's row count, so\\n recomputing converges instead of overwriting and the next boot writes nothing.\\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\\":\\"\\", \\"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), `canvas_blank` (there was nothing on the canvas to clear\\n— the board is still live and still drawable), `board_closed` (permanently\\nread-only), `locked`, `forbidden` (a creator-only command from a participant),\\n`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload),\\n`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\nThe two that look alike are the two that must not be confused: `board_closed`\\nis **terminal** and `canvas_blank` is **nothing to do**. A client that treats\\nthem alike sends a live room off clearing a canvas it never needed to lose —\\nwhich is exactly what a code guessed from a *substring* of the refusal did\\n(\\"the canvas is already blank\\" contains the word \\"closed\\"), so the server now\\nmatches the refusal constants by value and a test pairs every one of them with\\nthe code its client must act on.\\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. The one exception is a counter\\nthat is not an opinion but a plain row count — a board's `total_stroke_count`,\\nrecomputed from its strokes on every boot rather than seeded once, which is why\\nthat repair heals an under-count the `= NONE` guard would have skipped.\\nIn-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; `source`\\n names the class that pumped it, absent when hand-placed)\\n class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;\\n deletable only with no members and no attached courses)\\n class_member.rs ClassMember (one student in a class; adding them enrolls\\n them into every course the class holds)\\n class_course.rs ClassCourse (one course on a class; attaching it enrolls\\n the class's whole roster)\\n class_pump.rs attach/detach (the shared transaction behind both of those:\\n link row, class counter and the enrollments it implies move\\n together or not at all)\\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 `_`; 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 (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 classes.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"}]; +INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "60da3dc115614e68fea6b1ae594d6b407416cbd314cbbea4d11293f611fdd2bb"}]; DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii; DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25; DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25; REMOVE TABLE IF EXISTS endpoint; -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=&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=` filters by origin subject, `?owner=` (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\\") |"}]; +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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` \\u2014 requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u2014 each row carries `source`, the class that pumped it or `null` for hand-placed \\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": "classes", "routes": "| POST | `/classes` | manager | `{name, grade?, term_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class \\u2014 `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` \\u2014 add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists \\u2014 detach that link first \\u2014 if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first \\u00b7 paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member \\u2014 sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` \\u2014 attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first \\u00b7 paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) \\u2014 the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |"}, {"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); a **staff** row \\u2014 any target whose live role is teacher or higher, not just the session's current teacher \\u2014 needs manager+ |"}, {"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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read \\u2014 nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read \\u2014 nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 \\u2014 or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" \\u2014 a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable \\u2014 it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) \\u2014 its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** \\u2014 a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link \\u2014 a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |"}, {"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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\") |"}]; SELECT VALUE sha256 FROM meta:readme; REMOVE TABLE IF EXISTS doc; REMOVE TABLE IF EXISTS meta; -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\\": }`. 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=&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=&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=` filters by origin subject, `?owner=` (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\\": \\"\\"}` (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 `_k_` (a refund: `_kr_`), 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 `_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: 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=` narrows by origin subject, `?owner=` — 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\\": \\"\\", \\"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\\": \\"\\" } }\\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\\":\\"\\", \\"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 `_`; 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 (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"}]; -INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "16d576ae0877dbc7b21a88f129316c5b7eb833c95a064763ad4d7557b1dab3f2"}]; +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 taught course), **`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 are\\ngrouped into **classes** (*şube* — 9-A, 10-B) when a school teaches that way:\\na class is bulk enrollment and not a second kind of membership — attaching a\\ncourse to it enrolls the whole roster, adding a member enrolls them into every\\ncourse already attached, and what lands are ordinary enrollment rows tagged\\nwith the class that pumped them (untagged = placed by hand, and hand-placed\\nrows are never adopted and never swept). A course without room for everyone\\nrefuses the whole operation, naming it (see \\"Classes (şube)\\"). 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 course 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\\": }`. 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. A role change off `student` also drops the user's **event\\nsignups**, handing each seat back to its event: only students hold signups, so\\nnothing else could ever free one — the seat would sit claimed and a capped\\nevent would answer \\"full\\" forever.\\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| Create / edit / delete a **class** (şube); add or remove its members | manager | Reading classes, their rosters and their course lists is teacher+; a member must be a `student` |\\n| Attach / detach a course on a class | teacher | Course-management rights on **that course** — attaching enrolls the whole class into it, so it takes exactly the right enrolling one student takes |\\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 taught course (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=&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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` — requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists — detach that link first — if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member — sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first · paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |\\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); a **staff** row — any target whose live role is teacher or higher, not just the session's current teacher — needs manager+ |\\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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read — nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read — nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 — or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" — a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable — it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |\\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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\": \\"\\"}` (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, in one transaction with the attendance\\nrows. A role change off `student` sweeps the user's signups and hands each\\nseat back (`PATCH /users/{id}/role`): unregistering is student-or-self only,\\nso a demoted holder's seat had no other way out and a capped event stayed\\nfull forever. 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, and refused while a\\n counter-proposal stands: the proposal is the teacher's own, so approving it\\n here would let them confirm a time the requester never accepted.\\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. While the proposal stands, `PATCH /{id}/approve` is\\n refused (`409`): the effective window is now the teacher's own proposal, so\\n confirming it there would commit the requester to a time they never agreed\\n to. Only `/reschedule/accept` may approve at a proposed time, and only the\\n requester may call it. Re-proposing supersedes the previous proposal, so any\\n accept still carrying the old one is refused.\\n- `PATCH /{id}/reschedule/accept` (`{proposed_starts_at, proposed_ends_at}`) —\\n 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 The body **names the proposal being accepted**, copied from the booking's\\n `proposed_starts_at`/`proposed_ends_at` as the requester read them. It is not\\n a request to move the meeting: it pins *which* proposal this answer is for. A\\n teacher may re-propose at any moment and `/reschedule` takes no lock, so\\n without the pin the teacher would decide which window the requester's click\\n commits them to — propose 10:00, wait for them to open the page, propose\\n 23:00, and their accept lands on 23:00. A superseded pin answers `409` (*the\\n proposed time has changed*); re-read the booking and accept or decline what\\n actually stands.\\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\\"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\\\\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.\\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 *and classes* may link to one via `term_id` (nullable),\\nand deleting a term is refused with a `409` while any of them still links to\\nit — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with\\n`\\"term_id\\": null`) or delete them first, so the calendar never disappears\\nunder 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- **A slot name may not contain `/`, `\\\\`, `?`, `#` or `%`** — a `400` at\\n `PATCH /settings` when the slot is defined, and again here when a menu is\\n published under one. The name goes verbatim into the menu's record id, and\\n that id is a URL path segment: a slot called `a/b` would publish a menu at\\n `/meals/menus/2026-09-14_a/b`, an address no route can ever match again — the\\n menu could not be read, edited or deleted. Ordinary names are untouched;\\n spaces and Turkish letters percent-encode into one segment as they always\\n have.\\n- **A name the school's stored list already carries is exempt from that rule.**\\n It is younger than the lists it validates, and `PATCH /settings` re-validates\\n the *whole* submitted list — so a school that stored `a/b` before the rule\\n existed could never edit `meal_slots` again: re-sending the name is a `400`\\n and dropping it is a `409` the moment a menu was published under it. The\\n grandfathered name is exactly as unusable as it already was — no menu may be\\n published under it — and dropping it is still the only way to be rid of it.\\n The rule stays in full force for every *new* name.\\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`. Every dish write moves its **menu's** revision in\\nthe same transaction (that is what keeps a booking from freezing a price the\\nmenu has already left, below), which also makes the menu's existence part of\\nthe write: editing or deleting a dish whose menu has since been unpublished is\\na `404`, not a write onto a menu that is gone.\\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+. The exception is the money:\\n`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or\\nthe student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes\\n**and its attendance marks** with it, in the same transaction as the row: a\\ndish has no meaning apart from the menu it was published on, and a menu's\\nrecord id is deterministic on day+slot, so anything left behind would come back\\nattached to the *next* menu published for that meal — the kitchen reading\\n\\"served\\" for a student who never came, priced off food nobody re-entered.\\nCancelled **bookings** deliberately stay: their `attempt` counter is what keeps\\nthe ledger's `(booking, attempt)` ids unique, and a re-book on a republished\\nmenu would otherwise reuse an id the ledger already holds and bill the seat\\nnothing.\\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- **A manager+ may cancel anybody's seat.** Booking is student-and-parent\\n only, and cancelling used to be the same door — which left a seat nobody on\\n the API could give back the moment its student was promoted to staff or its\\n parent was unlinked: the menu refused its own deletion forever and the charge\\n could never be reversed, since cancelling is the only route that reverses\\n one. A role change deliberately sweeps no bookings on its own; moving money\\n is a decision, not a side effect.\\n- **The capacity check is a single conditional write, decided by the\\n database.** Counting rows and then writing one would be write-skew —\\n SurrealDB does not conflict-check a cross-record count against a concurrent\\n insert, so 24 students racing for 3 seats would all pass the count — so the\\n seat is instead claimed on a counter kept on the **menu row itself**, taken\\n and spent by one `UPDATE … WHERE` that also places the booking row in the\\n same transaction. No lock is involved and none would help: a duplicate\\n `POST` rolls its own seat back rather than costing a stranger their place.\\n- **One cutoff closes both ends — for the people it is aimed at.** Within the\\n school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a\\n new 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. It binds\\n **students and parents only**: a manager+ cancelling somebody's seat is not\\n held to it, because the deadline exists to stop students gaming the headcount\\n and that is no reason to leave staff holding a seat they cannot free. Past\\n the cutoff an uncancellable seat also made its menu undeletable forever (a\\n menu with a live booking refuses its own deletion) and its charge\\n unreversable, since cancelling is the only route that reverses one. A meal\\n already closed is therefore still freeable, and its menu still deletable, by\\n manager+ — the same state a school that set no cutoff at all runs under. 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\\nThe menu has to still be there: a mark whose menu is unpublished mid-request is\\na `404` and writes nothing. The existence check *is* the write's own target\\nrather than a read the write then trusts, because a menu's id is deterministic\\non day+slot — an unconditional mark landing just after the delete committed\\nwould be swept by nothing and would reappear as a mark on the next menu\\npublished for that meal.\\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, its row\\n and its money move together in one transaction on *both* sides — the claim\\n writes the charge, the flip writes the reversal — 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, and it is written **by the same\\n transaction that flips the seat** — not appended after it. The two as\\n separate writes left a crash in between with a seat given back and the\\n student still billed, and no later cancel would ever repay it, because the\\n money is keyed to the attempt the flip had already consumed. Folded in, the\\n seat cannot come back without the money. Booking is folded the same way — the\\n charge rides the claim's own transaction, because a charge appended afterwards\\n let a cancel land in the gap, reverse nothing (there was no charge yet), and\\n the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when\\n the charge it undoes is really there, checked inside that same transaction —\\n a refund with no charge behind it invents money. The charge row itself stays.\\n Repeating a cancel replays the reversal, which is what heals a seat flipped\\n before that was true and makes the refund recoverable rather than a one-shot\\n the network can lose; the cutoff is deliberately not re-checked on that path,\\n since the seat is already given back. Re-booking afterwards is a **fresh**\\n charge at the then-current price.\\n- **The price snapshot is pinned by the menu's revision, not by a lock.** The\\n dishes are summed a round trip before the seat is claimed, so a dish landing\\n in between would otherwise be frozen onto the row as \\"the menu was free\\n then\\" — and nothing heals that, since a seat already held is returned as-is,\\n never re-priced. Instead every dish write bumps a revision counter on the\\n menu, and the claim that takes the seat *also* asserts the menu is still at\\n the revision the price was read at: the booking is refused, re-reads, and\\n prices and seats itself again together. A lock around the read could not have\\n promised this — the price is read a round trip before the claim either way —\\n so what is frozen is always a price the menu genuinely carried at the instant\\n the seat was taken. A menu edited over and over under one booking gives up\\n after a few rounds with a `409`.\\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. The target must be a\\n **student, or anyone who already carries meal-ledger lines**: only a student\\n runs up a meal balance, so crediting anyone else is a typo and a typo here is\\n money in the wrong ledger — but a debt outlives its debtor's role change, and\\n the student-only rule alone made a promoted student's debt permanently\\n unsettleable, since no other route appends a credit. A mistyped staff id\\n carries no lines, so it is still a `400`. 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\\n**manager+** or a `parent_link` to that student — **a teacher gets a `403`**,\\nthe one pair in this block narrower than the rest of it. Canteen debt is\\nfamily debt: the money follows the `/payments` rule, not the classroom one,\\nwhile the dietary profile, booking and attendance reads stay teacher+. 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. The\\ncanteen's balance and ledger follow the same rule, for the same reason.\\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 `_k_` (a refund: `_kr_`), 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 `_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 All four reads are refused (`409`) while the caller's latest sitting is still\\n in progress — a mark on sitting 1 must not open the answer key to someone\\n midway through sitting 2. Submit the sitting first; an expired one reviews\\n fine.\\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: 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=` narrows by origin subject, `?owner=` — 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": "classes-ube", "title": "Classes (şube)", "body": "A **class** is the group a school actually teaches in — 9-A, 10-B — and here\\nit is a bulk-enrollment tool rather than a second kind of membership. A class\\nrow carries a name, an optional free-text `grade` label in the school's own\\nvocabulary (`\\"9\\"`, `\\"Lise 2\\"`; `\\"\\"` means no grade, exactly like omitting it)\\nand an optional `term_id`; nothing else about a course changes because a class\\nexists. Schools that run electives or a college-style timetable simply never\\ncreate one — individual enrollment is untouched, and classes are a\\nconvenience.\\n\\n**The pump.** A class holds **members** (students) and **attached courses**,\\nand owes the product of the two: every member enrolled in every attached\\ncourse. So both writes push the same way — attaching a course\\n(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a\\nmember (`POST /classes/{id}/members`) enrolls them into every course the class\\nalready carries — and what gets written is an ordinary `enrollment` row, the\\nsame one `POST /courses/{id}/enrollments` writes, counted against the same\\n`enrollment_count`. Each row a class writes is tagged with it as the row's\\n`source`; **no `source` means placed by hand**, and that one bit is what makes\\nthe sweeps below safe. It rides back out on every enrollment response\\n(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a\\nhand-placed row — without it no client could tell which of the roster rows it\\nis showing a class change is about to remove.\\n\\n**Already enrolled is skipped.** A pair that already has an enrollment row is\\nleft exactly as it stands — no second seat charged, no `source` rewritten. A\\nstudent a teacher enrolled by hand *stays* hand-placed when the class later\\nattaches that course, so the class never quietly adopts someone else's roster\\ndecision.\\n\\n**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims\\none seat per pair that needs a new row, each against its own course's\\n`capacity` — and if any single course has no room the whole call is a `409`\\nnaming it (`course: is full, so the class cannot take this student`,\\n`course: cannot hold the whole class`). Nothing lands, not even the seats\\nclaimed earlier in the same run: a half-enrolled class is worse than a refused\\none, and the refusal names the course whose capacity to raise.\\n\\nA second `409` reads off the same claim and is deliberately told apart from it:\\none of the class's attached courses **no longer exists**\\n(`course: no longer exists — detach it from this class first`). A seat\\nclaim that matches nothing means \\"full\\" *or* \\"no such row\\", and reporting a\\nstale attachment as a full course would send staff off to raise a capacity that\\nis not there — on a class every member-add now fails on. Detach the link and\\nthe class works again.\\n\\n**Removals take back only what the class pumped, and repair before they\\ndelete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or\\ndetaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the\\nenrollment rows whose `source` is *this* class and no others — hand-placed\\nrows survive every class operation. Even a tagged row is not automatically\\ndeleted: if a **second class** still claims that pair (it holds the same\\nstudent *and* that course attached), the row is re-tagged to that class\\ninstead, because the row it skipped writing is the row now being swept and the\\nstudent is still owed the seat. The heir is the lowest class id among the\\nclaimants, so repeating a sweep lands on the same class. Only a row nobody is\\nleft to claim is deleted and its seat handed back. Sweeps also tolerate rows\\nthat are already gone — deleting a course wipes its enrollments wholesale\\nwhile the class memberships survive — so \\"this class has a member\\" and \\"that\\nmember holds a pumped row\\" are independent facts.\\n\\n**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}`\\non a pumped student is allowed and sticks: nothing re-pumps them while they\\nremain a member, because the pump runs on writes, never on a schedule. Staff\\nput them back by enrolling them by hand (which makes the row hand-placed) or\\nby detaching and re-attaching the course.\\n\\n**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`\\nlanding on a row a class pumped takes the row *off* that class — its `source`\\nis cleared, the response comes back with `\\"source\\": null` — so no later class\\nsweep can undo a placement an operator made on purpose. That is the mirror of\\nthe rule above: hand-placed beats pumped in both directions, and without it\\n\\"hand-placed\\" was a state only a *first* enroll could ever reach.\\n\\n**Delete guards.** A class still holding members or attached courses refuses\\ndeletion with a `409` (\\"remove its members and detach its courses first\\") —\\nthe roster it owes is never dropped out from under the courses silently. A\\nterm linked by any class refuses deletion the same way courses make it refuse.\\nDeleting a **course** detaches it from every class it was on (its enrollments\\ngo with it), and a role change that takes a user off `student` drops their\\nclass memberships exactly as it drops their enrollments — in one transaction,\\nbecause a membership left behind would keep pumping them back into courses,\\nwhile an enrollment left behind would stay tagged with a class the released\\ncounters had already made deletable, and nothing could ever sweep it again.\\n\\n**A link to a deleted course detaches instead of refusing.** Should a\\n`class_course` row ever be left pointing at a course row that is gone,\\n`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights\\nare read *off* the course, so a stale link had no readable owner and the detach\\nused to `404` forever — which also left the class permanently undeletable, its\\nattachment counter counting a row nothing could sweep. There is no roster left\\nto protect, and the caller is already teacher+.\\n\\n**Who may.** Creating, editing and deleting a class, and adding or removing\\nits members, is **manager+** — a class is school structure, not classroom\\nwork. Attaching or detaching a course takes management rights on **that\\ncourse** (its creator, a teacher assigned to it, or manager+), since the call\\nwrites that course's roster and nothing else: the same right enrolling one\\nstudent takes. Every read (`GET /classes`, `/classes/{id}`, its members and\\nits courses, all paged, newest first) is **teacher+** — and \\"newest\\" here means\\nwhen the student was *added* or the course *attached*, not the student's or the\\ncourse's own id, which is what a link row keyed on the pair would otherwise\\nsort by. Rows written before that stamp existed carry none, and sort last.\\n\\n**Codes.** Adding a member or attaching a course answers `201`; a repeat is a\\n`409` (\\"the student is already in this class\\", \\"the course is already on this\\nclass\\"). An id in the **body** that names nothing — an unknown `user_id` or\\n`course_id`, or a member who is not a `student` — is a `400`; an id in the\\n**path** that names nothing (the class, or a member/course that was not on it)\\nis a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, **at most 200 students\\nand 50 courses** per class (`max_class_members`, `max_class_courses`), all four\\npublished in the `course` group of `GET /limits`. Past either ceiling the\\nadd or the attach is a `409` naming it (\\"this class already holds 200\\nstudents\\") — a standing class someone can make room in, which is why it is not\\nthe `404` a deleted class answers. Those two numbers are not comfort limits:\\nadding a member writes one enrollment per attached course and attaching a\\ncourse writes one per member, both in a *single* transaction, so each axis's\\nceiling is the bound on the other axis's write loop — an unbounded class is an\\nunbounded transaction any manager could trigger.\\n\\nWhich is why each write is refused on the **other** axis too. A class already\\nstanding *above* a ceiling cannot take a member while it holds more than 50\\ncourses (\\"this class holds more than 50 courses — detach some before adding a\\nstudent\\"), nor a course while it holds more than 200 students (\\"this class\\nholds more than 200 students — remove some before attaching a course\\"), both\\n`409`. Room on the axis being written is not the question: the write loop's\\nlength is set by the other one, and letting it run because *this* side has\\nspace is exactly the unbounded transaction the ceilings exist to prevent. Only\\na class that predates the ceilings can be there, and only shrinking the\\noverloaded axis clears it.", "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\\": \\"\\", \\"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\\": \\"\\" } }\\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 the field never changes name\\nbetween a request and a reply. That is the *only* thing the shared spelling\\nbuys: unlike the rest of this API, the two board request bodies **reject an\\nunknown key** (`422`) rather than ignoring it, because a misspelled roster\\nwould otherwise open a board its author is silently alone on. So a body must\\ncarry **only** the fields that request accepts — a board it just read is not a\\nlegal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all\\nunknown to `POST` and `PATCH`. A read-modify-write client sends the writable\\nfields it changed, never the whole board object back.\\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**A blank canvas cannot be cleared** (`409` — as a closed board is, while a\\nparticipant who is not the creator gets the `403` the two doors above give\\nthem). The marker is a real stored row and it is charged to the board's\\nlifetime budget, so a clear has to close at least one mark to be worth one —\\nwithout that rule every press of a button the creator can hold down minted a\\nfree row, and the epoch index filled with zero-stroke sessions.\\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 It counts **rows on the board**, not strokes drawn: a `clear` marker is a\\n stored row, so it costs one unit of the budget like any mark. The marker's\\n own unit is the one thing not refused at the ceiling — the last stroke of a\\n board's budget may well be closed by a clear, and refusing that would drop\\n the very marker the history needs to index the final epoch — so a board holds\\n at most `max_board_strokes + 1` rows. That held only for boards born after\\n the marker started paying, so **boot recomputes every board's\\n `total_stroke_count` from its actual rows**: a board an older binary cleared\\n is short exactly one per past clear, and an under-counting board is one that\\n keeps taking marks past the storage ceiling. This is the one backfill that is\\n not `= NONE`-guarded, and the one counter that may be recomputed — it is not\\n an opinion the live system maintains, it is the board's row count, so\\n recomputing converges instead of overwriting and the next boot writes nothing.\\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\\":\\"\\", \\"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), `canvas_blank` (there was nothing on the canvas to clear\\n— the board is still live and still drawable), `board_closed` (permanently\\nread-only), `locked`, `forbidden` (a creator-only command from a participant),\\n`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload),\\n`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\nThe two that look alike are the two that must not be confused: `board_closed`\\nis **terminal** and `canvas_blank` is **nothing to do**. A client that treats\\nthem alike sends a live room off clearing a canvas it never needed to lose —\\nwhich is exactly what a code guessed from a *substring* of the refusal did\\n(\\"the canvas is already blank\\" contains the word \\"closed\\"), so the server now\\nmatches the refusal constants by value and a test pairs every one of them with\\nthe code its client must act on.\\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. The one exception is a counter\\nthat is not an opinion but a plain row count — a board's `total_stroke_count`,\\nrecomputed from its strokes on every boot rather than seeded once, which is why\\nthat repair heals an under-count the `= NONE` guard would have skipped.\\nIn-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; `source`\\n names the class that pumped it, absent when hand-placed)\\n class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;\\n deletable only with no members and no attached courses)\\n class_member.rs ClassMember (one student in a class; adding them enrolls\\n them into every course the class holds)\\n class_course.rs ClassCourse (one course on a class; attaching it enrolls\\n the class's whole roster)\\n class_pump.rs attach/detach (the shared transaction behind both of those:\\n link row, class counter and the enrollments it implies move\\n together or not at all)\\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 `_`; 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 (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 classes.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"}]; +INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "8ba15af14f63a17d2ff344d6f10c47fce21814d7c97a52cae5243db1c14d6134"}]; DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii; DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25; DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25; REMOVE TABLE IF EXISTS endpoint; -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=&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=` filters by origin subject, `?owner=` (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\\") |"}]; +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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` \\u2014 requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u2014 each row carries `source`, the class that pumped it or `null` for hand-placed \\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": "classes", "routes": "| POST | `/classes` | manager | `{name, grade?, term_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class \\u2014 `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` \\u2014 add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists \\u2014 detach that link first \\u2014 if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first \\u00b7 paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member \\u2014 sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` \\u2014 attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first \\u00b7 paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) \\u2014 the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |"}, {"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); a **staff** row \\u2014 any target whose live role is teacher or higher, not just the session's current teacher \\u2014 needs manager+ |"}, {"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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read \\u2014 nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read \\u2014 nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 \\u2014 or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" \\u2014 a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable \\u2014 it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) \\u2014 its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** \\u2014 a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link \\u2014 a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |"}, {"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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\") |"}]; +SELECT VALUE sha256 FROM meta:readme; REMOVE TABLE IF EXISTS doc; REMOVE TABLE IF EXISTS meta; -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\\": }`. 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=&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=&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=` filters by origin subject, `?owner=` (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\\": \\"\\"}` (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 `_k_` (a refund: `_kr_`), 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 `_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: 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=` narrows by origin subject, `?owner=` — 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\\": \\"\\", \\"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\\": \\"\\" } }\\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\\":\\"\\", \\"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 `_`; 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 (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"}]; -INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "16d576ae0877dbc7b21a88f129316c5b7eb833c95a064763ad4d7557b1dab3f2"}]; +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 taught course), **`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 are\\ngrouped into **classes** (*şube* — 9-A, 10-B) when a school teaches that way:\\na class is bulk enrollment and not a second kind of membership — attaching a\\ncourse to it enrolls the whole roster, adding a member enrolls them into every\\ncourse already attached, and what lands are ordinary enrollment rows tagged\\nwith the class that pumped them (untagged = placed by hand, and hand-placed\\nrows are never adopted and never swept). A course without room for everyone\\nrefuses the whole operation, naming it (see \\"Classes (şube)\\"). 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 course 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\\": }`. 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. A demotion to `parent` also gives back the seats that\\naccount holds on still-open **event signup lists** — a parent cannot reach\\n`DELETE /events/{id}/register/{user}` and no one else may free a non-student's\\nseat, so those seats would stay claimed forever and a capped event would answer\\n\\"full\\" for good. Every other role change leaves signups alone: staff free their\\nown seats by hand. Seats on lists that have already closed (the event started,\\nor its `ends_at`-only deadline passed) are never touched — that roster is\\nhistory, and re-registering is refused.\\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| Create / edit / delete a **class** (şube); add or remove its members | manager | Reading classes, their rosters and their course lists is teacher+; a member must be a `student` |\\n| Attach / detach a course on a class | teacher | Course-management rights on **that course** — attaching enrolls the whole class into it, so it takes exactly the right enrolling one student takes |\\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 taught course (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=&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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` — requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists — detach that link first — if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member — sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first · paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |\\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); a **staff** row — any target whose live role is teacher or higher, not just the session's current teacher — needs manager+ |\\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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read — nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read — nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 — or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" — a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable — it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |\\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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\": \\"\\"}` (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, in one transaction with the attendance\\nrows. A role change off `student` sweeps the user's signups and hands each\\nseat back (`PATCH /users/{id}/role`): unregistering is student-or-self only,\\nso a demoted holder's seat had no other way out and a capped event stayed\\nfull forever. 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, and refused while a\\n counter-proposal stands: the proposal is the teacher's own, so approving it\\n here would let them confirm a time the requester never accepted.\\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. While the proposal stands, `PATCH /{id}/approve` is\\n refused (`409`): the effective window is now the teacher's own proposal, so\\n confirming it there would commit the requester to a time they never agreed\\n to. Only `/reschedule/accept` may approve at a proposed time, and only the\\n requester may call it. Re-proposing supersedes the previous proposal, so any\\n accept still carrying the old one is refused.\\n- `PATCH /{id}/reschedule/accept` (`{proposed_starts_at, proposed_ends_at}`) —\\n 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 The body **names the proposal being accepted**, copied from the booking's\\n `proposed_starts_at`/`proposed_ends_at` as the requester read them. It is not\\n a request to move the meeting: it pins *which* proposal this answer is for. A\\n teacher may re-propose at any moment and `/reschedule` takes no lock, so\\n without the pin the teacher would decide which window the requester's click\\n commits them to — propose 10:00, wait for them to open the page, propose\\n 23:00, and their accept lands on 23:00. A superseded pin answers `409` (*the\\n proposed time has changed*); re-read the booking and accept or decline what\\n actually stands.\\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\\"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\\\\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.\\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 *and classes* may link to one via `term_id` (nullable),\\nand deleting a term is refused with a `409` while any of them still links to\\nit — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with\\n`\\"term_id\\": null`) or delete them first, so the calendar never disappears\\nunder 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- **A slot name may not contain `/`, `\\\\`, `?`, `#` or `%`** — a `400` at\\n `PATCH /settings` when the slot is defined, and again here when a menu is\\n published under one. The name goes verbatim into the menu's record id, and\\n that id is a URL path segment: a slot called `a/b` would publish a menu at\\n `/meals/menus/2026-09-14_a/b`, an address no route can ever match again — the\\n menu could not be read, edited or deleted. Ordinary names are untouched;\\n spaces and Turkish letters percent-encode into one segment as they always\\n have.\\n- **A name the school's stored list already carries is exempt from that rule.**\\n It is younger than the lists it validates, and `PATCH /settings` re-validates\\n the *whole* submitted list — so a school that stored `a/b` before the rule\\n existed could never edit `meal_slots` again: re-sending the name is a `400`\\n and dropping it is a `409` the moment a menu was published under it. The\\n grandfathered name is exactly as unusable as it already was — no menu may be\\n published under it — and dropping it is still the only way to be rid of it.\\n The rule stays in full force for every *new* name.\\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`. Every dish write moves its **menu's** revision in\\nthe same transaction (that is what keeps a booking from freezing a price the\\nmenu has already left, below), which also makes the menu's existence part of\\nthe write: editing or deleting a dish whose menu has since been unpublished is\\na `404`, not a write onto a menu that is gone.\\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+. The exception is the money:\\n`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or\\nthe student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes\\n**and its attendance marks** with it, in the same transaction as the row: a\\ndish has no meaning apart from the menu it was published on, and a menu's\\nrecord id is deterministic on day+slot, so anything left behind would come back\\nattached to the *next* menu published for that meal — the kitchen reading\\n\\"served\\" for a student who never came, priced off food nobody re-entered.\\nCancelled **bookings** deliberately stay: their `attempt` counter is what keeps\\nthe ledger's `(booking, attempt)` ids unique, and a re-book on a republished\\nmenu would otherwise reuse an id the ledger already holds and bill the seat\\nnothing.\\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- **A manager+ may cancel anybody's seat.** Booking is student-and-parent\\n only, and cancelling used to be the same door — which left a seat nobody on\\n the API could give back the moment its student was promoted to staff or its\\n parent was unlinked: the menu refused its own deletion forever and the charge\\n could never be reversed, since cancelling is the only route that reverses\\n one. A role change deliberately sweeps no bookings on its own; moving money\\n is a decision, not a side effect.\\n- **The capacity check is a single conditional write, decided by the\\n database.** Counting rows and then writing one would be write-skew —\\n SurrealDB does not conflict-check a cross-record count against a concurrent\\n insert, so 24 students racing for 3 seats would all pass the count — so the\\n seat is instead claimed on a counter kept on the **menu row itself**, taken\\n and spent by one `UPDATE … WHERE` that also places the booking row in the\\n same transaction. No lock is involved and none would help: a duplicate\\n `POST` rolls its own seat back rather than costing a stranger their place.\\n- **One cutoff closes both ends — for the people it is aimed at.** Within the\\n school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a\\n new 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. It binds\\n **students and parents only**: a manager+ cancelling somebody's seat is not\\n held to it, because the deadline exists to stop students gaming the headcount\\n and that is no reason to leave staff holding a seat they cannot free. Past\\n the cutoff an uncancellable seat also made its menu undeletable forever (a\\n menu with a live booking refuses its own deletion) and its charge\\n unreversable, since cancelling is the only route that reverses one. A meal\\n already closed is therefore still freeable, and its menu still deletable, by\\n manager+ — the same state a school that set no cutoff at all runs under. 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\\nThe menu has to still be there: a mark whose menu is unpublished mid-request is\\na `404` and writes nothing. The existence check *is* the write's own target\\nrather than a read the write then trusts, because a menu's id is deterministic\\non day+slot — an unconditional mark landing just after the delete committed\\nwould be swept by nothing and would reappear as a mark on the next menu\\npublished for that meal.\\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, its row\\n and its money move together in one transaction on *both* sides — the claim\\n writes the charge, the flip writes the reversal — 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, and it is written **by the same\\n transaction that flips the seat** — not appended after it. The two as\\n separate writes left a crash in between with a seat given back and the\\n student still billed, and no later cancel would ever repay it, because the\\n money is keyed to the attempt the flip had already consumed. Folded in, the\\n seat cannot come back without the money. Booking is folded the same way — the\\n charge rides the claim's own transaction, because a charge appended afterwards\\n let a cancel land in the gap, reverse nothing (there was no charge yet), and\\n the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when\\n the charge it undoes is really there, checked inside that same transaction —\\n a refund with no charge behind it invents money. The charge row itself stays.\\n Repeating a cancel replays the reversal, which is what heals a seat flipped\\n before that was true and makes the refund recoverable rather than a one-shot\\n the network can lose; the cutoff is deliberately not re-checked on that path,\\n since the seat is already given back. Re-booking afterwards is a **fresh**\\n charge at the then-current price.\\n- **The price snapshot is pinned by the menu's revision, not by a lock.** The\\n dishes are summed a round trip before the seat is claimed, so a dish landing\\n in between would otherwise be frozen onto the row as \\"the menu was free\\n then\\" — and nothing heals that, since a seat already held is returned as-is,\\n never re-priced. Instead every dish write bumps a revision counter on the\\n menu, and the claim that takes the seat *also* asserts the menu is still at\\n the revision the price was read at: the booking is refused, re-reads, and\\n prices and seats itself again together. A lock around the read could not have\\n promised this — the price is read a round trip before the claim either way —\\n so what is frozen is always a price the menu genuinely carried at the instant\\n the seat was taken. A menu edited over and over under one booking gives up\\n after a few rounds with a `409`.\\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. The target must be a\\n **student, or anyone who already carries meal-ledger lines**: only a student\\n runs up a meal balance, so crediting anyone else is a typo and a typo here is\\n money in the wrong ledger — but a debt outlives its debtor's role change, and\\n the student-only rule alone made a promoted student's debt permanently\\n unsettleable, since no other route appends a credit. A mistyped staff id\\n carries no lines, so it is still a `400`. 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\\n**manager+** or a `parent_link` to that student — **a teacher gets a `403`**,\\nthe one pair in this block narrower than the rest of it. Canteen debt is\\nfamily debt: the money follows the `/payments` rule, not the classroom one,\\nwhile the dietary profile, booking and attendance reads stay teacher+. 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. The\\ncanteen's balance and ledger follow the same rule, for the same reason.\\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 `_k_` (a refund: `_kr_`), 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 `_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 All four reads are refused (`409`) while the caller's latest sitting is still\\n in progress — a mark on sitting 1 must not open the answer key to someone\\n midway through sitting 2. Submit the sitting first; an expired one reviews\\n fine.\\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: 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=` narrows by origin subject, `?owner=` — 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": "classes-ube", "title": "Classes (şube)", "body": "A **class** is the group a school actually teaches in — 9-A, 10-B — and here\\nit is a bulk-enrollment tool rather than a second kind of membership. A class\\nrow carries a name, an optional free-text `grade` label in the school's own\\nvocabulary (`\\"9\\"`, `\\"Lise 2\\"`; `\\"\\"` means no grade, exactly like omitting it)\\nand an optional `term_id`; nothing else about a course changes because a class\\nexists. Schools that run electives or a college-style timetable simply never\\ncreate one — individual enrollment is untouched, and classes are a\\nconvenience.\\n\\n**The pump.** A class holds **members** (students) and **attached courses**,\\nand owes the product of the two: every member enrolled in every attached\\ncourse. So both writes push the same way — attaching a course\\n(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a\\nmember (`POST /classes/{id}/members`) enrolls them into every course the class\\nalready carries — and what gets written is an ordinary `enrollment` row, the\\nsame one `POST /courses/{id}/enrollments` writes, counted against the same\\n`enrollment_count`. Each row a class writes is tagged with it as the row's\\n`source`; **no `source` means placed by hand**, and that one bit is what makes\\nthe sweeps below safe. It rides back out on every enrollment response\\n(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a\\nhand-placed row — without it no client could tell which of the roster rows it\\nis showing a class change is about to remove.\\n\\n**Already enrolled is skipped.** A pair that already has an enrollment row is\\nleft exactly as it stands — no second seat charged, no `source` rewritten. A\\nstudent a teacher enrolled by hand *stays* hand-placed when the class later\\nattaches that course, so the class never quietly adopts someone else's roster\\ndecision.\\n\\n**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims\\none seat per pair that needs a new row, each against its own course's\\n`capacity` — and if any single course has no room the whole call is a `409`\\nnaming it (`course: is full, so the class cannot take this student`,\\n`course: cannot hold the whole class`). Nothing lands, not even the seats\\nclaimed earlier in the same run: a half-enrolled class is worse than a refused\\none, and the refusal names the course whose capacity to raise.\\n\\nA second `409` reads off the same claim and is deliberately told apart from it:\\none of the class's attached courses **no longer exists**\\n(`course: no longer exists — detach it from this class first`). A seat\\nclaim that matches nothing means \\"full\\" *or* \\"no such row\\", and reporting a\\nstale attachment as a full course would send staff off to raise a capacity that\\nis not there — on a class every member-add now fails on. Detach the link and\\nthe class works again.\\n\\n**Removals take back only what the class pumped, and repair before they\\ndelete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or\\ndetaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the\\nenrollment rows whose `source` is *this* class and no others — hand-placed\\nrows survive every class operation. Even a tagged row is not automatically\\ndeleted: if a **second class** still claims that pair (it holds the same\\nstudent *and* that course attached), the row is re-tagged to that class\\ninstead, because the row it skipped writing is the row now being swept and the\\nstudent is still owed the seat. The heir is the lowest class id among the\\nclaimants, so repeating a sweep lands on the same class. Only a row nobody is\\nleft to claim is deleted and its seat handed back. Sweeps also tolerate rows\\nthat are already gone — deleting a course wipes its enrollments wholesale\\nwhile the class memberships survive — so \\"this class has a member\\" and \\"that\\nmember holds a pumped row\\" are independent facts.\\n\\n**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}`\\non a pumped student is allowed and sticks: nothing re-pumps them while they\\nremain a member, because the pump runs on writes, never on a schedule. Staff\\nput them back by enrolling them by hand (which makes the row hand-placed) or\\nby detaching and re-attaching the course.\\n\\n**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`\\nlanding on a row a class pumped takes the row *off* that class — its `source`\\nis cleared, the response comes back with `\\"source\\": null` — so no later class\\nsweep can undo a placement an operator made on purpose. That is the mirror of\\nthe rule above: hand-placed beats pumped in both directions, and without it\\n\\"hand-placed\\" was a state only a *first* enroll could ever reach.\\n\\n**Delete guards.** A class still holding members or attached courses refuses\\ndeletion with a `409` (\\"remove its members and detach its courses first\\") —\\nthe roster it owes is never dropped out from under the courses silently. A\\nterm linked by any class refuses deletion the same way courses make it refuse.\\nDeleting a **course** detaches it from every class it was on (its enrollments\\ngo with it), and a role change that takes a user off `student` drops their\\nclass memberships exactly as it drops their enrollments — in one transaction,\\nbecause a membership left behind would keep pumping them back into courses,\\nwhile an enrollment left behind would stay tagged with a class the released\\ncounters had already made deletable, and nothing could ever sweep it again.\\n\\n**A link to a deleted course detaches instead of refusing.** Should a\\n`class_course` row ever be left pointing at a course row that is gone,\\n`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights\\nare read *off* the course, so a stale link had no readable owner and the detach\\nused to `404` forever — which also left the class permanently undeletable, its\\nattachment counter counting a row nothing could sweep. There is no roster left\\nto protect, and the caller is already teacher+.\\n\\n**Who may.** Creating, editing and deleting a class, and adding or removing\\nits members, is **manager+** — a class is school structure, not classroom\\nwork. Attaching or detaching a course takes management rights on **that\\ncourse** (its creator, a teacher assigned to it, or manager+), since the call\\nwrites that course's roster and nothing else: the same right enrolling one\\nstudent takes. Every read (`GET /classes`, `/classes/{id}`, its members and\\nits courses, all paged, newest first) is **teacher+** — and \\"newest\\" here means\\nwhen the student was *added* or the course *attached*, not the student's or the\\ncourse's own id, which is what a link row keyed on the pair would otherwise\\nsort by. Rows written before that stamp existed carry none, and sort last.\\n\\n**Codes.** Adding a member or attaching a course answers `201`; a repeat is a\\n`409` (\\"the student is already in this class\\", \\"the course is already on this\\nclass\\"). An id in the **body** that names nothing — an unknown `user_id` or\\n`course_id`, or a member who is not a `student` — is a `400`; an id in the\\n**path** that names nothing (the class, or a member/course that was not on it)\\nis a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, **at most 200 students\\nand 50 courses** per class (`max_class_members`, `max_class_courses`), all four\\npublished in the `course` group of `GET /limits`. Past either ceiling the\\nadd or the attach is a `409` naming it (\\"this class already holds 200\\nstudents\\") — a standing class someone can make room in, which is why it is not\\nthe `404` a deleted class answers. Those two numbers are not comfort limits:\\nadding a member writes one enrollment per attached course and attaching a\\ncourse writes one per member, both in a *single* transaction, so each axis's\\nceiling is the bound on the other axis's write loop — an unbounded class is an\\nunbounded transaction any manager could trigger.\\n\\nWhich is why each write is refused on the **other** axis too. A class already\\nstanding *above* a ceiling cannot take a member while it holds more than 50\\ncourses (\\"this class holds more than 50 courses — detach some before adding a\\nstudent\\"), nor a course while it holds more than 200 students (\\"this class\\nholds more than 200 students — remove some before attaching a course\\"), both\\n`409`. Room on the axis being written is not the question: the write loop's\\nlength is set by the other one, and letting it run because *this* side has\\nspace is exactly the unbounded transaction the ceilings exist to prevent. Only\\na class that predates the ceilings can be there, and only shrinking the\\noverloaded axis clears it.", "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\\": \\"\\", \\"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\\": \\"\\" } }\\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 the field never changes name\\nbetween a request and a reply. That is the *only* thing the shared spelling\\nbuys: unlike the rest of this API, the two board request bodies **reject an\\nunknown key** (`422`) rather than ignoring it, because a misspelled roster\\nwould otherwise open a board its author is silently alone on. So a body must\\ncarry **only** the fields that request accepts — a board it just read is not a\\nlegal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all\\nunknown to `POST` and `PATCH`. A read-modify-write client sends the writable\\nfields it changed, never the whole board object back.\\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**A blank canvas cannot be cleared** (`409` — as a closed board is, while a\\nparticipant who is not the creator gets the `403` the two doors above give\\nthem). The marker is a real stored row and it is charged to the board's\\nlifetime budget, so a clear has to close at least one mark to be worth one —\\nwithout that rule every press of a button the creator can hold down minted a\\nfree row, and the epoch index filled with zero-stroke sessions.\\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 It counts **rows on the board**, not strokes drawn: a `clear` marker is a\\n stored row, so it costs one unit of the budget like any mark. The marker's\\n own unit is the one thing not refused at the ceiling — the last stroke of a\\n board's budget may well be closed by a clear, and refusing that would drop\\n the very marker the history needs to index the final epoch — so a board holds\\n at most `max_board_strokes + 1` rows. That held only for boards born after\\n the marker started paying, so **boot recomputes every board's\\n `total_stroke_count` from its actual rows**: a board an older binary cleared\\n is short exactly one per past clear, and an under-counting board is one that\\n keeps taking marks past the storage ceiling. This is the one backfill that is\\n not `= NONE`-guarded, and the one counter that may be recomputed — it is not\\n an opinion the live system maintains, it is the board's row count, so\\n recomputing converges instead of overwriting and the next boot writes nothing.\\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\\":\\"\\", \\"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), `canvas_blank` (there was nothing on the canvas to clear\\n— the board is still live and still drawable), `board_closed` (permanently\\nread-only), `locked`, `forbidden` (a creator-only command from a participant),\\n`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload),\\n`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\nThe two that look alike are the two that must not be confused: `board_closed`\\nis **terminal** and `canvas_blank` is **nothing to do**. A client that treats\\nthem alike sends a live room off clearing a canvas it never needed to lose —\\nwhich is exactly what a code guessed from a *substring* of the refusal did\\n(\\"the canvas is already blank\\" contains the word \\"closed\\"), so the server now\\nmatches the refusal constants by value and a test pairs every one of them with\\nthe code its client must act on.\\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. The one exception is a counter\\nthat is not an opinion but a plain row count — a board's `total_stroke_count`,\\nrecomputed from its strokes on every boot rather than seeded once, which is why\\nthat repair heals an under-count the `= NONE` guard would have skipped.\\nIn-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; `source`\\n names the class that pumped it, absent when hand-placed)\\n class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;\\n deletable only with no members and no attached courses)\\n class_member.rs ClassMember (one student in a class; adding them enrolls\\n them into every course the class holds)\\n class_course.rs ClassCourse (one course on a class; attaching it enrolls\\n the class's whole roster)\\n class_pump.rs attach/detach (the shared transaction behind both of those:\\n link row, class counter and the enrollments it implies move\\n together or not at all)\\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 `_`; 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 (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 classes.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"}]; +INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "04ca155982409624be6ec02f2eb3b0c587968dd2fbca29a1d86e205e355487ca"}]; DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii; DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25; DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25; REMOVE TABLE IF EXISTS endpoint; -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=&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=` filters by origin subject, `?owner=` (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\\") |"}]; -SELECT sha256 FROM meta:readme; -SELECT VALUE count() FROM user GROUP ALL; -INFO FOR DB; -SELECT * FROM user; -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; -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; -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 }; -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' }; -CREATE user:01KYTW2N7ZSG9RDTN47C0YEG03 CONTENT { username:'staleparent', password_hash:'$argon2id$v=19$m=19456,t=2,p=1$wRqh5DvfiRfBF0oqwbGh/A$ybdhHrHs73ixid1sipo9n4Pw6eTOhcHDCqPArvK51G4', role:'parent' }; -CREATE chatbot_thread:01KYTW2N7ZSG9RDTN47C0YEG11 CONTENT { user_id: user:01KYTW2N7ZSG9RDTN47C0YEG01, title:'old thread one', created_at: 1750000000000, updated_at: 1750000000000 }; -CREATE chatbot_thread:01KYTW2N7ZSG9RDTN47C0YEG12 CONTENT { user_id: user:01KYTW2N7ZSG9RDTN47C0YEG01, title:'old thread two', created_at: 1750000001000, updated_at: 1750000001000 }; -SELECT * FROM user ORDER BY id; -INFO FOR TABLE board; INFO FOR TABLE board_stroke; INFO FOR TABLE user; -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; -INFO FOR DB; -SELECT * FROM user ORDER BY id; -SELECT * FROM user:01KYTW2N7ZSG9RDTN47C0YEG01; -SELECT VALUE count() FROM board GROUP ALL; -SELECT VALUE count() FROM board_stroke GROUP ALL; -SELECT id, creator, creator.role AS creator_role, creator.username AS creator_username FROM board; -SELECT VALUE count() FROM board WHERE creator.role = 'parent' GROUP ALL; -SELECT id, board_count FROM user WHERE board_count != NONE; -SELECT id, board_count FROM user ORDER BY id; -SELECT id, epoch, epoch_stroke_count, total_stroke_count, participants FROM board ORDER BY id; -SELECT VALUE count() FROM board_stroke GROUP ALL; -SELECT VALUE board_count FROM user:01KYTW2N7ZSG9RDTN47C0YEG01; -SELECT VALUE count() FROM board_stroke GROUP ALL; SELECT VALUE board_count FROM user:01KYTW2N7ZSG9RDTN47C0YEG01; SELECT VALUE count() FROM board GROUP ALL; -SELECT id, board_count FROM user ORDER BY id; SELECT id, epoch, total_stroke_count FROM board ORDER BY id; -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; -DELETE board_stroke; -DELETE board; -DELETE exam_answer; DELETE exam_attempt; DELETE exam_question; DELETE exam; -DELETE enrollment; DELETE subject; DELETE course; -DELETE chatbot_thread WHERE user_id IN [user:01KYTW2N7ZSG9RDTN47C0YEG01]; -DELETE session WHERE user IN [user:01KYTW2N7ZSG9RDTN47C0YEG01, user:01KYTW2N7ZSG9RDTN47C0YEG02, user:01KYTW2N7ZSG9RDTN47C0YEG03]; -DELETE user:01KYTW2N7ZSG9RDTN47C0YEG01, user:01KYTW2N7ZSG9RDTN47C0YEG02, user:01KYTW2N7ZSG9RDTN47C0YEG03; -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; +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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` \\u2014 requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u2014 each row carries `source`, the class that pumped it or `null` for hand-placed \\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": "classes", "routes": "| POST | `/classes` | manager | `{name, grade?, term_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class \\u2014 `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` \\u2014 add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists \\u2014 detach that link first \\u2014 if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first \\u00b7 paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member \\u2014 sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` \\u2014 attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first \\u00b7 paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) \\u2014 the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |"}, {"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); a **staff** row \\u2014 any target whose live role is teacher or higher, not just the session's current teacher \\u2014 needs manager+ |"}, {"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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read \\u2014 nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read \\u2014 nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 \\u2014 or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" \\u2014 a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable \\u2014 it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) \\u2014 its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** \\u2014 a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link \\u2014 a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |"}, {"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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\") |"}]; +SELECT VALUE sha256 FROM meta:readme; +REMOVE TABLE IF EXISTS doc; +REMOVE TABLE IF EXISTS meta; +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 taught course), **`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 are\\ngrouped into **classes** (*şube* — 9-A, 10-B) when a school teaches that way:\\na class is bulk enrollment and not a second kind of membership — attaching a\\ncourse to it enrolls the whole roster, adding a member enrolls them into every\\ncourse already attached, and what lands are ordinary enrollment rows tagged\\nwith the class that pumped them (untagged = placed by hand, and hand-placed\\nrows are never adopted and never swept). A course without room for everyone\\nrefuses the whole operation, naming it (see \\"Classes (şube)\\"). 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 course 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\\": }`. 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. A demotion to `parent` also gives back the seats that\\naccount holds on still-open **event signup lists** — a parent cannot reach\\n`DELETE /events/{id}/register/{user}` and no one else may free a non-student's\\nseat, so those seats would stay claimed forever and a capped event would answer\\n\\"full\\" for good. Every other role change leaves signups alone: staff free their\\nown seats by hand. Seats on lists that have already closed (the event started,\\nor its `ends_at`-only deadline passed) are never touched — that roster is\\nhistory, and re-registering is refused.\\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| Create / edit / delete a **class** (şube); add or remove its members | manager | Reading classes, their rosters and their course lists is teacher+; a member must be a `student` |\\n| Attach / detach a course on a class | teacher | Course-management rights on **that course** — attaching enrolls the whole class into it, so it takes exactly the right enrolling one student takes |\\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 taught course (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=&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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` — requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists — detach that link first — if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member — sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first · paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |\\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); a **staff** row — any target whose live role is teacher or higher, not just the session's current teacher — needs manager+ |\\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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read — nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read — nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 — or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" — a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable — it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |\\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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\": \\"\\"}` (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, in one transaction with the attendance\\nrows. A demotion to `parent` sweeps that user's signups off **still-open**\\nlists and hands each seat back (`PATCH /users/{id}/role`): unregistering is\\nstudent-or-self only, so a parent's seat had no other way out. Staff free their\\nown, and a closed list is never rewritten. 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, and refused while a\\n counter-proposal stands: the proposal is the teacher's own, so approving it\\n here would let them confirm a time the requester never accepted.\\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. While the proposal stands, `PATCH /{id}/approve` is\\n refused (`409`): the effective window is now the teacher's own proposal, so\\n confirming it there would commit the requester to a time they never agreed\\n to. Only `/reschedule/accept` may approve at a proposed time, and only the\\n requester may call it. Re-proposing supersedes the previous proposal, so any\\n accept still carrying the old one is refused.\\n- `PATCH /{id}/reschedule/accept` (`{proposed_starts_at, proposed_ends_at}`) —\\n 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 The body **names the proposal being accepted**, copied from the booking's\\n `proposed_starts_at`/`proposed_ends_at` as the requester read them. It is not\\n a request to move the meeting: it pins *which* proposal this answer is for. A\\n teacher may re-propose at any moment and `/reschedule` takes no lock, so\\n without the pin the teacher would decide which window the requester's click\\n commits them to — propose 10:00, wait for them to open the page, propose\\n 23:00, and their accept lands on 23:00. A superseded pin answers `409` (*the\\n proposed time has changed*); re-read the booking and accept or decline what\\n actually stands.\\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\\"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\\\\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.\\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 *and classes* may link to one via `term_id` (nullable),\\nand deleting a term is refused with a `409` while any of them still links to\\nit — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with\\n`\\"term_id\\": null`) or delete them first, so the calendar never disappears\\nunder 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- **A slot name may not contain `/`, `\\\\`, `?`, `#` or `%`** — a `400` at\\n `PATCH /settings` when the slot is defined, and again here when a menu is\\n published under one. The name goes verbatim into the menu's record id, and\\n that id is a URL path segment: a slot called `a/b` would publish a menu at\\n `/meals/menus/2026-09-14_a/b`, an address no route can ever match again — the\\n menu could not be read, edited or deleted. Ordinary names are untouched;\\n spaces and Turkish letters percent-encode into one segment as they always\\n have.\\n- **A name the school's stored list already carries is exempt from that rule.**\\n It is younger than the lists it validates, and `PATCH /settings` re-validates\\n the *whole* submitted list — so a school that stored `a/b` before the rule\\n existed could never edit `meal_slots` again: re-sending the name is a `400`\\n and dropping it is a `409` the moment a menu was published under it. The\\n grandfathered name is exactly as unusable as it already was — no menu may be\\n published under it — and dropping it is still the only way to be rid of it.\\n The rule stays in full force for every *new* name.\\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`. Every dish write moves its **menu's** revision in\\nthe same transaction (that is what keeps a booking from freezing a price the\\nmenu has already left, below), which also makes the menu's existence part of\\nthe write: editing or deleting a dish whose menu has since been unpublished is\\na `404`, not a write onto a menu that is gone.\\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+. The exception is the money:\\n`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or\\nthe student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes\\n**and its attendance marks** with it, in the same transaction as the row: a\\ndish has no meaning apart from the menu it was published on, and a menu's\\nrecord id is deterministic on day+slot, so anything left behind would come back\\nattached to the *next* menu published for that meal — the kitchen reading\\n\\"served\\" for a student who never came, priced off food nobody re-entered.\\nCancelled **bookings** deliberately stay: their `attempt` counter is what keeps\\nthe ledger's `(booking, attempt)` ids unique, and a re-book on a republished\\nmenu would otherwise reuse an id the ledger already holds and bill the seat\\nnothing.\\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- **A manager+ may cancel anybody's seat.** Booking is student-and-parent\\n only, and cancelling used to be the same door — which left a seat nobody on\\n the API could give back the moment its student was promoted to staff or its\\n parent was unlinked: the menu refused its own deletion forever and the charge\\n could never be reversed, since cancelling is the only route that reverses\\n one. A role change deliberately sweeps no bookings on its own; moving money\\n is a decision, not a side effect.\\n- **The capacity check is a single conditional write, decided by the\\n database.** Counting rows and then writing one would be write-skew —\\n SurrealDB does not conflict-check a cross-record count against a concurrent\\n insert, so 24 students racing for 3 seats would all pass the count — so the\\n seat is instead claimed on a counter kept on the **menu row itself**, taken\\n and spent by one `UPDATE … WHERE` that also places the booking row in the\\n same transaction. No lock is involved and none would help: a duplicate\\n `POST` rolls its own seat back rather than costing a stranger their place.\\n- **One cutoff closes both ends — for the people it is aimed at.** Within the\\n school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a\\n new 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. It binds\\n **students and parents only**: a manager+ cancelling somebody's seat is not\\n held to it, because the deadline exists to stop students gaming the headcount\\n and that is no reason to leave staff holding a seat they cannot free. Past\\n the cutoff an uncancellable seat also made its menu undeletable forever (a\\n menu with a live booking refuses its own deletion) and its charge\\n unreversable, since cancelling is the only route that reverses one. A meal\\n already closed is therefore still freeable, and its menu still deletable, by\\n manager+ — the same state a school that set no cutoff at all runs under. 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\\nThe menu has to still be there: a mark whose menu is unpublished mid-request is\\na `404` and writes nothing. The existence check *is* the write's own target\\nrather than a read the write then trusts, because a menu's id is deterministic\\non day+slot — an unconditional mark landing just after the delete committed\\nwould be swept by nothing and would reappear as a mark on the next menu\\npublished for that meal.\\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, its row\\n and its money move together in one transaction on *both* sides — the claim\\n writes the charge, the flip writes the reversal — 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, and it is written **by the same\\n transaction that flips the seat** — not appended after it. The two as\\n separate writes left a crash in between with a seat given back and the\\n student still billed, and no later cancel would ever repay it, because the\\n money is keyed to the attempt the flip had already consumed. Folded in, the\\n seat cannot come back without the money. Booking is folded the same way — the\\n charge rides the claim's own transaction, because a charge appended afterwards\\n let a cancel land in the gap, reverse nothing (there was no charge yet), and\\n the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when\\n the charge it undoes is really there, checked inside that same transaction —\\n a refund with no charge behind it invents money. The charge row itself stays.\\n Repeating a cancel replays the reversal, which is what heals a seat flipped\\n before that was true and makes the refund recoverable rather than a one-shot\\n the network can lose; the cutoff is deliberately not re-checked on that path,\\n since the seat is already given back. Re-booking afterwards is a **fresh**\\n charge at the then-current price.\\n- **The price snapshot is pinned by the menu's revision, not by a lock.** The\\n dishes are summed a round trip before the seat is claimed, so a dish landing\\n in between would otherwise be frozen onto the row as \\"the menu was free\\n then\\" — and nothing heals that, since a seat already held is returned as-is,\\n never re-priced. Instead every dish write bumps a revision counter on the\\n menu, and the claim that takes the seat *also* asserts the menu is still at\\n the revision the price was read at: the booking is refused, re-reads, and\\n prices and seats itself again together. A lock around the read could not have\\n promised this — the price is read a round trip before the claim either way —\\n so what is frozen is always a price the menu genuinely carried at the instant\\n the seat was taken. A menu edited over and over under one booking gives up\\n after a few rounds with a `409`.\\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. The target must be a\\n **student, or anyone who already carries meal-ledger lines**: only a student\\n runs up a meal balance, so crediting anyone else is a typo and a typo here is\\n money in the wrong ledger — but a debt outlives its debtor's role change, and\\n the student-only rule alone made a promoted student's debt permanently\\n unsettleable, since no other route appends a credit. A mistyped staff id\\n carries no lines, so it is still a `400`. 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\\n**manager+** or a `parent_link` to that student — **a teacher gets a `403`**,\\nthe one pair in this block narrower than the rest of it. Canteen debt is\\nfamily debt: the money follows the `/payments` rule, not the classroom one,\\nwhile the dietary profile, booking and attendance reads stay teacher+. 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. The\\ncanteen's balance and ledger follow the same rule, for the same reason.\\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 `_k_` (a refund: `_kr_`), 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 `_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 All four reads are refused (`409`) while the caller's latest sitting is still\\n in progress — a mark on sitting 1 must not open the answer key to someone\\n midway through sitting 2. Submit the sitting first; an expired one reviews\\n fine.\\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: 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=` narrows by origin subject, `?owner=` — 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": "classes-ube", "title": "Classes (şube)", "body": "A **class** is the group a school actually teaches in — 9-A, 10-B — and here\\nit is a bulk-enrollment tool rather than a second kind of membership. A class\\nrow carries a name, an optional free-text `grade` label in the school's own\\nvocabulary (`\\"9\\"`, `\\"Lise 2\\"`; `\\"\\"` means no grade, exactly like omitting it)\\nand an optional `term_id`; nothing else about a course changes because a class\\nexists. Schools that run electives or a college-style timetable simply never\\ncreate one — individual enrollment is untouched, and classes are a\\nconvenience.\\n\\n**The pump.** A class holds **members** (students) and **attached courses**,\\nand owes the product of the two: every member enrolled in every attached\\ncourse. So both writes push the same way — attaching a course\\n(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a\\nmember (`POST /classes/{id}/members`) enrolls them into every course the class\\nalready carries — and what gets written is an ordinary `enrollment` row, the\\nsame one `POST /courses/{id}/enrollments` writes, counted against the same\\n`enrollment_count`. Each row a class writes is tagged with it as the row's\\n`source`; **no `source` means placed by hand**, and that one bit is what makes\\nthe sweeps below safe. It rides back out on every enrollment response\\n(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a\\nhand-placed row — without it no client could tell which of the roster rows it\\nis showing a class change is about to remove.\\n\\n**Already enrolled is skipped.** A pair that already has an enrollment row is\\nleft exactly as it stands — no second seat charged, no `source` rewritten. A\\nstudent a teacher enrolled by hand *stays* hand-placed when the class later\\nattaches that course, so the class never quietly adopts someone else's roster\\ndecision.\\n\\n**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims\\none seat per pair that needs a new row, each against its own course's\\n`capacity` — and if any single course has no room the whole call is a `409`\\nnaming it (`course: is full, so the class cannot take this student`,\\n`course: cannot hold the whole class`). Nothing lands, not even the seats\\nclaimed earlier in the same run: a half-enrolled class is worse than a refused\\none, and the refusal names the course whose capacity to raise.\\n\\nA second `409` reads off the same claim and is deliberately told apart from it:\\none of the class's attached courses **no longer exists**\\n(`course: no longer exists — detach it from this class first`). A seat\\nclaim that matches nothing means \\"full\\" *or* \\"no such row\\", and reporting a\\nstale attachment as a full course would send staff off to raise a capacity that\\nis not there — on a class every member-add now fails on. Detach the link and\\nthe class works again.\\n\\n**Removals take back only what the class pumped, and repair before they\\ndelete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or\\ndetaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the\\nenrollment rows whose `source` is *this* class and no others — hand-placed\\nrows survive every class operation. Even a tagged row is not automatically\\ndeleted: if a **second class** still claims that pair (it holds the same\\nstudent *and* that course attached), the row is re-tagged to that class\\ninstead, because the row it skipped writing is the row now being swept and the\\nstudent is still owed the seat. The heir is the lowest class id among the\\nclaimants, so repeating a sweep lands on the same class. Only a row nobody is\\nleft to claim is deleted and its seat handed back. Sweeps also tolerate rows\\nthat are already gone — deleting a course wipes its enrollments wholesale\\nwhile the class memberships survive — so \\"this class has a member\\" and \\"that\\nmember holds a pumped row\\" are independent facts.\\n\\n**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}`\\non a pumped student is allowed and sticks: nothing re-pumps them while they\\nremain a member, because the pump runs on writes, never on a schedule. Staff\\nput them back by enrolling them by hand (which makes the row hand-placed) or\\nby detaching and re-attaching the course.\\n\\n**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`\\nlanding on a row a class pumped takes the row *off* that class — its `source`\\nis cleared, the response comes back with `\\"source\\": null` — so no later class\\nsweep can undo a placement an operator made on purpose. That is the mirror of\\nthe rule above: hand-placed beats pumped in both directions, and without it\\n\\"hand-placed\\" was a state only a *first* enroll could ever reach.\\n\\n**Delete guards.** A class still holding members or attached courses refuses\\ndeletion with a `409` (\\"remove its members and detach its courses first\\") —\\nthe roster it owes is never dropped out from under the courses silently. A\\nterm linked by any class refuses deletion the same way courses make it refuse.\\nDeleting a **course** detaches it from every class it was on (its enrollments\\ngo with it), and a role change that takes a user off `student` drops their\\nclass memberships exactly as it drops their enrollments — in one transaction,\\nbecause a membership left behind would keep pumping them back into courses,\\nwhile an enrollment left behind would stay tagged with a class the released\\ncounters had already made deletable, and nothing could ever sweep it again.\\n\\n**A link to a deleted course detaches instead of refusing.** Should a\\n`class_course` row ever be left pointing at a course row that is gone,\\n`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights\\nare read *off* the course, so a stale link had no readable owner and the detach\\nused to `404` forever — which also left the class permanently undeletable, its\\nattachment counter counting a row nothing could sweep. There is no roster left\\nto protect, and the caller is already teacher+.\\n\\n**Who may.** Creating, editing and deleting a class, and adding or removing\\nits members, is **manager+** — a class is school structure, not classroom\\nwork. Attaching or detaching a course takes management rights on **that\\ncourse** (its creator, a teacher assigned to it, or manager+), since the call\\nwrites that course's roster and nothing else: the same right enrolling one\\nstudent takes. Every read (`GET /classes`, `/classes/{id}`, its members and\\nits courses, all paged, newest first) is **teacher+** — and \\"newest\\" here means\\nwhen the student was *added* or the course *attached*, not the student's or the\\ncourse's own id, which is what a link row keyed on the pair would otherwise\\nsort by. Rows written before that stamp existed carry none, and sort last.\\n\\n**Codes.** Adding a member or attaching a course answers `201`; a repeat is a\\n`409` (\\"the student is already in this class\\", \\"the course is already on this\\nclass\\"). An id in the **body** that names nothing — an unknown `user_id` or\\n`course_id`, or a member who is not a `student` — is a `400`; an id in the\\n**path** that names nothing (the class, or a member/course that was not on it)\\nis a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, **at most 200 students\\nand 50 courses** per class (`max_class_members`, `max_class_courses`), all four\\npublished in the `course` group of `GET /limits`. Past either ceiling the\\nadd or the attach is a `409` naming it (\\"this class already holds 200\\nstudents\\") — a standing class someone can make room in, which is why it is not\\nthe `404` a deleted class answers. Those two numbers are not comfort limits:\\nadding a member writes one enrollment per attached course and attaching a\\ncourse writes one per member, both in a *single* transaction, so each axis's\\nceiling is the bound on the other axis's write loop — an unbounded class is an\\nunbounded transaction any manager could trigger.\\n\\nWhich is why each write is refused on the **other** axis too. A class already\\nstanding *above* a ceiling cannot take a member while it holds more than 50\\ncourses (\\"this class holds more than 50 courses — detach some before adding a\\nstudent\\"), nor a course while it holds more than 200 students (\\"this class\\nholds more than 200 students — remove some before attaching a course\\"), both\\n`409`. Room on the axis being written is not the question: the write loop's\\nlength is set by the other one, and letting it run because *this* side has\\nspace is exactly the unbounded transaction the ceilings exist to prevent. Only\\na class that predates the ceilings can be there, and only shrinking the\\noverloaded axis clears it.", "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\\": \\"\\", \\"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\\": \\"\\" } }\\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 the field never changes name\\nbetween a request and a reply. That is the *only* thing the shared spelling\\nbuys: unlike the rest of this API, the two board request bodies **reject an\\nunknown key** (`422`) rather than ignoring it, because a misspelled roster\\nwould otherwise open a board its author is silently alone on. So a body must\\ncarry **only** the fields that request accepts — a board it just read is not a\\nlegal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all\\nunknown to `POST` and `PATCH`. A read-modify-write client sends the writable\\nfields it changed, never the whole board object back.\\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**A blank canvas cannot be cleared** (`409` — as a closed board is, while a\\nparticipant who is not the creator gets the `403` the two doors above give\\nthem). The marker is a real stored row and it is charged to the board's\\nlifetime budget, so a clear has to close at least one mark to be worth one —\\nwithout that rule every press of a button the creator can hold down minted a\\nfree row, and the epoch index filled with zero-stroke sessions.\\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 It counts **rows on the board**, not strokes drawn: a `clear` marker is a\\n stored row, so it costs one unit of the budget like any mark. The marker's\\n own unit is the one thing not refused at the ceiling — the last stroke of a\\n board's budget may well be closed by a clear, and refusing that would drop\\n the very marker the history needs to index the final epoch — so a board holds\\n at most `max_board_strokes + 1` rows. That held only for boards born after\\n the marker started paying, so **boot recomputes every board's\\n `total_stroke_count` from its actual rows**: a board an older binary cleared\\n is short exactly one per past clear, and an under-counting board is one that\\n keeps taking marks past the storage ceiling. This is the one backfill that is\\n not `= NONE`-guarded, and the one counter that may be recomputed — it is not\\n an opinion the live system maintains, it is the board's row count, so\\n recomputing converges instead of overwriting and the next boot writes nothing.\\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\\":\\"\\", \\"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), `canvas_blank` (there was nothing on the canvas to clear\\n— the board is still live and still drawable), `board_closed` (permanently\\nread-only), `locked`, `forbidden` (a creator-only command from a participant),\\n`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload),\\n`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\nThe two that look alike are the two that must not be confused: `board_closed`\\nis **terminal** and `canvas_blank` is **nothing to do**. A client that treats\\nthem alike sends a live room off clearing a canvas it never needed to lose —\\nwhich is exactly what a code guessed from a *substring* of the refusal did\\n(\\"the canvas is already blank\\" contains the word \\"closed\\"), so the server now\\nmatches the refusal constants by value and a test pairs every one of them with\\nthe code its client must act on.\\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. The one exception is a counter\\nthat is not an opinion but a plain row count — a board's `total_stroke_count`,\\nrecomputed from its strokes on every boot rather than seeded once, which is why\\nthat repair heals an under-count the `= NONE` guard would have skipped.\\nIn-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; `source`\\n names the class that pumped it, absent when hand-placed)\\n class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;\\n deletable only with no members and no attached courses)\\n class_member.rs ClassMember (one student in a class; adding them enrolls\\n them into every course the class holds)\\n class_course.rs ClassCourse (one course on a class; attaching it enrolls\\n the class's whole roster)\\n class_pump.rs attach/detach (the shared transaction behind both of those:\\n link row, class counter and the enrollments it implies move\\n together or not at all)\\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 `_`; 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 (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 classes.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"}]; +INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "09baee6ab4332a9dcf207ebfae27915109bdb31e6796f02d617ebe4dbd28c56b"}]; +DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii; +DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25; +DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25; +REMOVE TABLE IF EXISTS endpoint; +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=&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 and event signups, freeing each signup's seat (only students enroll or sign up) |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` \\u2014 requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u2014 each row carries `source`, the class that pumped it or `null` for hand-placed \\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": "classes", "routes": "| POST | `/classes` | manager | `{name, grade?, term_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class \\u2014 `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` \\u2014 add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists \\u2014 detach that link first \\u2014 if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first \\u00b7 paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member \\u2014 sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` \\u2014 attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first \\u00b7 paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) \\u2014 the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |"}, {"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); a **staff** row \\u2014 any target whose live role is teacher or higher, not just the session's current teacher \\u2014 needs manager+ |"}, {"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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read \\u2014 nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read \\u2014 nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 \\u2014 or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" \\u2014 a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable \\u2014 it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) \\u2014 its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** \\u2014 a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link \\u2014 a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |"}, {"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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\") |"}]; SELECT VALUE sha256 FROM meta:readme; REMOVE TABLE IF EXISTS doc; REMOVE TABLE IF EXISTS meta; -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\\": }`. 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=&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=&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=` filters by origin subject, `?owner=` (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\\": \\"\\"}` (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 `_k_` (a refund: `_kr_`), 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 `_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: 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=` narrows by origin subject, `?owner=` — 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\\": \\"\\", \\"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\\": \\"\\" } }\\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\\":\\"\\", \\"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 `_`; 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 (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"}]; -INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "5f59783c6826e3ee660cde26dda01988e0f2d42e65bd11c705d2e896e206388a"}]; +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 taught course), **`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 are\\ngrouped into **classes** (*şube* — 9-A, 10-B) when a school teaches that way:\\na class is bulk enrollment and not a second kind of membership — attaching a\\ncourse to it enrolls the whole roster, adding a member enrolls them into every\\ncourse already attached, and what lands are ordinary enrollment rows tagged\\nwith the class that pumped them (untagged = placed by hand, and hand-placed\\nrows are never adopted and never swept). A course without room for everyone\\nrefuses the whole operation, naming it (see \\"Classes (şube)\\"). 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 course 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\\": }`. 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. A demotion to `parent` also gives back the seats that\\naccount holds on still-open **event signup lists** — a parent cannot reach\\n`DELETE /events/{id}/register/{user}` and no one else may free a non-student's\\nseat, so those seats would stay claimed forever and a capped event would answer\\n\\"full\\" for good. Every other role change leaves signups alone: staff free their\\nown seats by hand. Seats on lists that have already closed (the event started,\\nor its `ends_at`-only deadline passed) are never touched — that roster is\\nhistory, and re-registering is refused.\\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| Create / edit / delete a **class** (şube); add or remove its members | manager | Reading classes, their rosters and their course lists is teacher+; a member must be a `student` |\\n| Attach / detach a course on a class | teacher | Course-management rights on **that course** — attaching enrolls the whole class into it, so it takes exactly the right enrolling one student takes |\\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 taught course (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=&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=&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), and a demotion to `parent` also frees their seats on still-open event signup lists |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` — requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) — each row carries `source`, the class that pumped it or `null` for hand-placed · paged |\\n| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |\\n| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` — add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists — detach that link first — if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member — sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` — attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first · paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) — the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |\\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); a **staff** row — any target whose live role is teacher or higher, not just the session's current teacher — needs manager+ |\\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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read — nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read — nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 — or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" — a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable — it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |\\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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\": \\"\\"}` (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, in one transaction with the attendance\\nrows. A demotion to `parent` sweeps that user's signups off **still-open**\\nlists and hands each seat back (`PATCH /users/{id}/role`): unregistering is\\nstudent-or-self only, so a parent's seat had no other way out. Staff free their\\nown, and a closed list is never rewritten. 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, and refused while a\\n counter-proposal stands: the proposal is the teacher's own, so approving it\\n here would let them confirm a time the requester never accepted.\\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. While the proposal stands, `PATCH /{id}/approve` is\\n refused (`409`): the effective window is now the teacher's own proposal, so\\n confirming it there would commit the requester to a time they never agreed\\n to. Only `/reschedule/accept` may approve at a proposed time, and only the\\n requester may call it. Re-proposing supersedes the previous proposal, so any\\n accept still carrying the old one is refused.\\n- `PATCH /{id}/reschedule/accept` (`{proposed_starts_at, proposed_ends_at}`) —\\n 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 The body **names the proposal being accepted**, copied from the booking's\\n `proposed_starts_at`/`proposed_ends_at` as the requester read them. It is not\\n a request to move the meeting: it pins *which* proposal this answer is for. A\\n teacher may re-propose at any moment and `/reschedule` takes no lock, so\\n without the pin the teacher would decide which window the requester's click\\n commits them to — propose 10:00, wait for them to open the page, propose\\n 23:00, and their accept lands on 23:00. A superseded pin answers `409` (*the\\n proposed time has changed*); re-read the booking and accept or decline what\\n actually stands.\\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\\"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\\\\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.\\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 *and classes* may link to one via `term_id` (nullable),\\nand deleting a term is refused with a `409` while any of them still links to\\nit — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with\\n`\\"term_id\\": null`) or delete them first, so the calendar never disappears\\nunder 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- **A slot name may not contain `/`, `\\\\`, `?`, `#` or `%`** — a `400` at\\n `PATCH /settings` when the slot is defined, and again here when a menu is\\n published under one. The name goes verbatim into the menu's record id, and\\n that id is a URL path segment: a slot called `a/b` would publish a menu at\\n `/meals/menus/2026-09-14_a/b`, an address no route can ever match again — the\\n menu could not be read, edited or deleted. Ordinary names are untouched;\\n spaces and Turkish letters percent-encode into one segment as they always\\n have.\\n- **A name the school's stored list already carries is exempt from that rule.**\\n It is younger than the lists it validates, and `PATCH /settings` re-validates\\n the *whole* submitted list — so a school that stored `a/b` before the rule\\n existed could never edit `meal_slots` again: re-sending the name is a `400`\\n and dropping it is a `409` the moment a menu was published under it. The\\n grandfathered name is exactly as unusable as it already was — no menu may be\\n published under it — and dropping it is still the only way to be rid of it.\\n The rule stays in full force for every *new* name.\\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`. Every dish write moves its **menu's** revision in\\nthe same transaction (that is what keeps a booking from freezing a price the\\nmenu has already left, below), which also makes the menu's existence part of\\nthe write: editing or deleting a dish whose menu has since been unpublished is\\na `404`, not a write onto a menu that is gone.\\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+. The exception is the money:\\n`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or\\nthe student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes\\n**and its attendance marks** with it, in the same transaction as the row: a\\ndish has no meaning apart from the menu it was published on, and a menu's\\nrecord id is deterministic on day+slot, so anything left behind would come back\\nattached to the *next* menu published for that meal — the kitchen reading\\n\\"served\\" for a student who never came, priced off food nobody re-entered.\\nCancelled **bookings** deliberately stay: their `attempt` counter is what keeps\\nthe ledger's `(booking, attempt)` ids unique, and a re-book on a republished\\nmenu would otherwise reuse an id the ledger already holds and bill the seat\\nnothing.\\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- **A manager+ may cancel anybody's seat.** Booking is student-and-parent\\n only, and cancelling used to be the same door — which left a seat nobody on\\n the API could give back the moment its student was promoted to staff or its\\n parent was unlinked: the menu refused its own deletion forever and the charge\\n could never be reversed, since cancelling is the only route that reverses\\n one. A role change deliberately sweeps no bookings on its own; moving money\\n is a decision, not a side effect.\\n- **The capacity check is a single conditional write, decided by the\\n database.** Counting rows and then writing one would be write-skew —\\n SurrealDB does not conflict-check a cross-record count against a concurrent\\n insert, so 24 students racing for 3 seats would all pass the count — so the\\n seat is instead claimed on a counter kept on the **menu row itself**, taken\\n and spent by one `UPDATE … WHERE` that also places the booking row in the\\n same transaction. No lock is involved and none would help: a duplicate\\n `POST` rolls its own seat back rather than costing a stranger their place.\\n- **One cutoff closes both ends — for the people it is aimed at.** Within the\\n school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a\\n new 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. It binds\\n **students and parents only**: a manager+ cancelling somebody's seat is not\\n held to it, because the deadline exists to stop students gaming the headcount\\n and that is no reason to leave staff holding a seat they cannot free. Past\\n the cutoff an uncancellable seat also made its menu undeletable forever (a\\n menu with a live booking refuses its own deletion) and its charge\\n unreversable, since cancelling is the only route that reverses one. A meal\\n already closed is therefore still freeable, and its menu still deletable, by\\n manager+ — the same state a school that set no cutoff at all runs under. 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\\nThe menu has to still be there: a mark whose menu is unpublished mid-request is\\na `404` and writes nothing. The existence check *is* the write's own target\\nrather than a read the write then trusts, because a menu's id is deterministic\\non day+slot — an unconditional mark landing just after the delete committed\\nwould be swept by nothing and would reappear as a mark on the next menu\\npublished for that meal.\\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, its row\\n and its money move together in one transaction on *both* sides — the claim\\n writes the charge, the flip writes the reversal — 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, and it is written **by the same\\n transaction that flips the seat** — not appended after it. The two as\\n separate writes left a crash in between with a seat given back and the\\n student still billed, and no later cancel would ever repay it, because the\\n money is keyed to the attempt the flip had already consumed. Folded in, the\\n seat cannot come back without the money. Booking is folded the same way — the\\n charge rides the claim's own transaction, because a charge appended afterwards\\n let a cancel land in the gap, reverse nothing (there was no charge yet), and\\n the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when\\n the charge it undoes is really there, checked inside that same transaction —\\n a refund with no charge behind it invents money. The charge row itself stays.\\n Repeating a cancel replays the reversal, which is what heals a seat flipped\\n before that was true and makes the refund recoverable rather than a one-shot\\n the network can lose; the cutoff is deliberately not re-checked on that path,\\n since the seat is already given back. Re-booking afterwards is a **fresh**\\n charge at the then-current price.\\n- **The price snapshot is pinned by the menu's revision, not by a lock.** The\\n dishes are summed a round trip before the seat is claimed, so a dish landing\\n in between would otherwise be frozen onto the row as \\"the menu was free\\n then\\" — and nothing heals that, since a seat already held is returned as-is,\\n never re-priced. Instead every dish write bumps a revision counter on the\\n menu, and the claim that takes the seat *also* asserts the menu is still at\\n the revision the price was read at: the booking is refused, re-reads, and\\n prices and seats itself again together. A lock around the read could not have\\n promised this — the price is read a round trip before the claim either way —\\n so what is frozen is always a price the menu genuinely carried at the instant\\n the seat was taken. A menu edited over and over under one booking gives up\\n after a few rounds with a `409`.\\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. The target must be a\\n **student, or anyone who already carries meal-ledger lines**: only a student\\n runs up a meal balance, so crediting anyone else is a typo and a typo here is\\n money in the wrong ledger — but a debt outlives its debtor's role change, and\\n the student-only rule alone made a promoted student's debt permanently\\n unsettleable, since no other route appends a credit. A mistyped staff id\\n carries no lines, so it is still a `400`. 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\\n**manager+** or a `parent_link` to that student — **a teacher gets a `403`**,\\nthe one pair in this block narrower than the rest of it. Canteen debt is\\nfamily debt: the money follows the `/payments` rule, not the classroom one,\\nwhile the dietary profile, booking and attendance reads stay teacher+. 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. The\\ncanteen's balance and ledger follow the same rule, for the same reason.\\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 `_k_` (a refund: `_kr_`), 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 `_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 All four reads are refused (`409`) while the caller's latest sitting is still\\n in progress — a mark on sitting 1 must not open the answer key to someone\\n midway through sitting 2. Submit the sitting first; an expired one reviews\\n fine.\\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: 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=` narrows by origin subject, `?owner=` — 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": "classes-ube", "title": "Classes (şube)", "body": "A **class** is the group a school actually teaches in — 9-A, 10-B — and here\\nit is a bulk-enrollment tool rather than a second kind of membership. A class\\nrow carries a name, an optional free-text `grade` label in the school's own\\nvocabulary (`\\"9\\"`, `\\"Lise 2\\"`; `\\"\\"` means no grade, exactly like omitting it)\\nand an optional `term_id`; nothing else about a course changes because a class\\nexists. Schools that run electives or a college-style timetable simply never\\ncreate one — individual enrollment is untouched, and classes are a\\nconvenience.\\n\\n**The pump.** A class holds **members** (students) and **attached courses**,\\nand owes the product of the two: every member enrolled in every attached\\ncourse. So both writes push the same way — attaching a course\\n(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a\\nmember (`POST /classes/{id}/members`) enrolls them into every course the class\\nalready carries — and what gets written is an ordinary `enrollment` row, the\\nsame one `POST /courses/{id}/enrollments` writes, counted against the same\\n`enrollment_count`. Each row a class writes is tagged with it as the row's\\n`source`; **no `source` means placed by hand**, and that one bit is what makes\\nthe sweeps below safe. It rides back out on every enrollment response\\n(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a\\nhand-placed row — without it no client could tell which of the roster rows it\\nis showing a class change is about to remove.\\n\\n**Already enrolled is skipped.** A pair that already has an enrollment row is\\nleft exactly as it stands — no second seat charged, no `source` rewritten. A\\nstudent a teacher enrolled by hand *stays* hand-placed when the class later\\nattaches that course, so the class never quietly adopts someone else's roster\\ndecision.\\n\\n**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims\\none seat per pair that needs a new row, each against its own course's\\n`capacity` — and if any single course has no room the whole call is a `409`\\nnaming it (`course: is full, so the class cannot take this student`,\\n`course: cannot hold the whole class`). Nothing lands, not even the seats\\nclaimed earlier in the same run: a half-enrolled class is worse than a refused\\none, and the refusal names the course whose capacity to raise.\\n\\nA second `409` reads off the same claim and is deliberately told apart from it:\\none of the class's attached courses **no longer exists**\\n(`course: no longer exists — detach it from this class first`). A seat\\nclaim that matches nothing means \\"full\\" *or* \\"no such row\\", and reporting a\\nstale attachment as a full course would send staff off to raise a capacity that\\nis not there — on a class every member-add now fails on. Detach the link and\\nthe class works again.\\n\\n**Removals take back only what the class pumped, and repair before they\\ndelete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or\\ndetaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the\\nenrollment rows whose `source` is *this* class and no others — hand-placed\\nrows survive every class operation. Even a tagged row is not automatically\\ndeleted: if a **second class** still claims that pair (it holds the same\\nstudent *and* that course attached), the row is re-tagged to that class\\ninstead, because the row it skipped writing is the row now being swept and the\\nstudent is still owed the seat. The heir is the lowest class id among the\\nclaimants, so repeating a sweep lands on the same class. Only a row nobody is\\nleft to claim is deleted and its seat handed back. Sweeps also tolerate rows\\nthat are already gone — deleting a course wipes its enrollments wholesale\\nwhile the class memberships survive — so \\"this class has a member\\" and \\"that\\nmember holds a pumped row\\" are independent facts.\\n\\n**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}`\\non a pumped student is allowed and sticks: nothing re-pumps them while they\\nremain a member, because the pump runs on writes, never on a schedule. Staff\\nput them back by enrolling them by hand (which makes the row hand-placed) or\\nby detaching and re-attaching the course.\\n\\n**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`\\nlanding on a row a class pumped takes the row *off* that class — its `source`\\nis cleared, the response comes back with `\\"source\\": null` — so no later class\\nsweep can undo a placement an operator made on purpose. That is the mirror of\\nthe rule above: hand-placed beats pumped in both directions, and without it\\n\\"hand-placed\\" was a state only a *first* enroll could ever reach.\\n\\n**Delete guards.** A class still holding members or attached courses refuses\\ndeletion with a `409` (\\"remove its members and detach its courses first\\") —\\nthe roster it owes is never dropped out from under the courses silently. A\\nterm linked by any class refuses deletion the same way courses make it refuse.\\nDeleting a **course** detaches it from every class it was on (its enrollments\\ngo with it), and a role change that takes a user off `student` drops their\\nclass memberships exactly as it drops their enrollments — in one transaction,\\nbecause a membership left behind would keep pumping them back into courses,\\nwhile an enrollment left behind would stay tagged with a class the released\\ncounters had already made deletable, and nothing could ever sweep it again.\\n\\n**A link to a deleted course detaches instead of refusing.** Should a\\n`class_course` row ever be left pointing at a course row that is gone,\\n`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights\\nare read *off* the course, so a stale link had no readable owner and the detach\\nused to `404` forever — which also left the class permanently undeletable, its\\nattachment counter counting a row nothing could sweep. There is no roster left\\nto protect, and the caller is already teacher+.\\n\\n**Who may.** Creating, editing and deleting a class, and adding or removing\\nits members, is **manager+** — a class is school structure, not classroom\\nwork. Attaching or detaching a course takes management rights on **that\\ncourse** (its creator, a teacher assigned to it, or manager+), since the call\\nwrites that course's roster and nothing else: the same right enrolling one\\nstudent takes. Every read (`GET /classes`, `/classes/{id}`, its members and\\nits courses, all paged, newest first) is **teacher+** — and \\"newest\\" here means\\nwhen the student was *added* or the course *attached*, not the student's or the\\ncourse's own id, which is what a link row keyed on the pair would otherwise\\nsort by. Rows written before that stamp existed carry none, and sort last.\\n\\n**Codes.** Adding a member or attaching a course answers `201`; a repeat is a\\n`409` (\\"the student is already in this class\\", \\"the course is already on this\\nclass\\"). An id in the **body** that names nothing — an unknown `user_id` or\\n`course_id`, or a member who is not a `student` — is a `400`; an id in the\\n**path** that names nothing (the class, or a member/course that was not on it)\\nis a `404`. Bounds: name ≤ 200 characters, grade ≤ 20, **at most 200 students\\nand 50 courses** per class (`max_class_members`, `max_class_courses`), all four\\npublished in the `course` group of `GET /limits`. Past either ceiling the\\nadd or the attach is a `409` naming it (\\"this class already holds 200\\nstudents\\") — a standing class someone can make room in, which is why it is not\\nthe `404` a deleted class answers. Those two numbers are not comfort limits:\\nadding a member writes one enrollment per attached course and attaching a\\ncourse writes one per member, both in a *single* transaction, so each axis's\\nceiling is the bound on the other axis's write loop — an unbounded class is an\\nunbounded transaction any manager could trigger.\\n\\nWhich is why each write is refused on the **other** axis too. A class already\\nstanding *above* a ceiling cannot take a member while it holds more than 50\\ncourses (\\"this class holds more than 50 courses — detach some before adding a\\nstudent\\"), nor a course while it holds more than 200 students (\\"this class\\nholds more than 200 students — remove some before attaching a course\\"), both\\n`409`. Room on the axis being written is not the question: the write loop's\\nlength is set by the other one, and letting it run because *this* side has\\nspace is exactly the unbounded transaction the ceilings exist to prevent. Only\\na class that predates the ceilings can be there, and only shrinking the\\noverloaded axis clears it.", "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\\": \\"\\", \\"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\\": \\"\\" } }\\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 the field never changes name\\nbetween a request and a reply. That is the *only* thing the shared spelling\\nbuys: unlike the rest of this API, the two board request bodies **reject an\\nunknown key** (`422`) rather than ignoring it, because a misspelled roster\\nwould otherwise open a board its author is silently alone on. So a body must\\ncarry **only** the fields that request accepts — a board it just read is not a\\nlegal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all\\nunknown to `POST` and `PATCH`. A read-modify-write client sends the writable\\nfields it changed, never the whole board object back.\\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**A blank canvas cannot be cleared** (`409` — as a closed board is, while a\\nparticipant who is not the creator gets the `403` the two doors above give\\nthem). The marker is a real stored row and it is charged to the board's\\nlifetime budget, so a clear has to close at least one mark to be worth one —\\nwithout that rule every press of a button the creator can hold down minted a\\nfree row, and the epoch index filled with zero-stroke sessions.\\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 It counts **rows on the board**, not strokes drawn: a `clear` marker is a\\n stored row, so it costs one unit of the budget like any mark. The marker's\\n own unit is the one thing not refused at the ceiling — the last stroke of a\\n board's budget may well be closed by a clear, and refusing that would drop\\n the very marker the history needs to index the final epoch — so a board holds\\n at most `max_board_strokes + 1` rows. That held only for boards born after\\n the marker started paying, so **boot recomputes every board's\\n `total_stroke_count` from its actual rows**: a board an older binary cleared\\n is short exactly one per past clear, and an under-counting board is one that\\n keeps taking marks past the storage ceiling. This is the one backfill that is\\n not `= NONE`-guarded, and the one counter that may be recomputed — it is not\\n an opinion the live system maintains, it is the board's row count, so\\n recomputing converges instead of overwriting and the next boot writes nothing.\\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\\":\\"\\", \\"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), `canvas_blank` (there was nothing on the canvas to clear\\n— the board is still live and still drawable), `board_closed` (permanently\\nread-only), `locked`, `forbidden` (a creator-only command from a participant),\\n`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload),\\n`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`.\\n\\nThe two that look alike are the two that must not be confused: `board_closed`\\nis **terminal** and `canvas_blank` is **nothing to do**. A client that treats\\nthem alike sends a live room off clearing a canvas it never needed to lose —\\nwhich is exactly what a code guessed from a *substring* of the refusal did\\n(\\"the canvas is already blank\\" contains the word \\"closed\\"), so the server now\\nmatches the refusal constants by value and a test pairs every one of them with\\nthe code its client must act on.\\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. The one exception is a counter\\nthat is not an opinion but a plain row count — a board's `total_stroke_count`,\\nrecomputed from its strokes on every boot rather than seeded once, which is why\\nthat repair heals an under-count the `= NONE` guard would have skipped.\\nIn-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; `source`\\n names the class that pumped it, absent when hand-placed)\\n class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;\\n deletable only with no members and no attached courses)\\n class_member.rs ClassMember (one student in a class; adding them enrolls\\n them into every course the class holds)\\n class_course.rs ClassCourse (one course on a class; attaching it enrolls\\n the class's whole roster)\\n class_pump.rs attach/detach (the shared transaction behind both of those:\\n link row, class counter and the enrollments it implies move\\n together or not at all)\\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 `_`; 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 (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 classes.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"}]; +INSERT INTO meta [{"id": "readme", "path": "/home/tahinli/Documents/Code/Rust/hezarfen_backend/README.md", "sha256": "f9a42cee0b2b3d5c0888b59d7018906ecf43807adb3ff90a3d4502d01d52a41b"}]; DEFINE ANALYZER simple TOKENIZERS class FILTERS lowercase, ascii; DEFINE INDEX doc_body ON doc FIELDS body FULLTEXT ANALYZER simple BM25; DEFINE INDEX doc_title ON doc FIELDS title FULLTEXT ANALYZER simple BM25; REMOVE TABLE IF EXISTS endpoint; -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=&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=` filters by origin subject, `?owner=` (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\\") |"}]; +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=&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), and a demotion to `parent` also frees their seats on still-open event signup lists |\\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, **while a counter-proposal stands** (only the requester may approve at a proposed time, via `/reschedule/accept`), 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 | `{proposed_starts_at, proposed_ends_at}` \\u2014 requester only: accept the counter-proposal **as read**; this *is* approval at that time (the overlap guard runs again); `409` if the proposal has since changed, if none stands, if the booking is no longer pending, if that time has started, or if it collides with another approved meeting of either side |\\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; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\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); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |\\n| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) \\u2014 each row carries `source`, the class that pumped it or `null` for hand-placed \\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": "classes", "routes": "| POST | `/classes` | manager | `{name, grade?, term_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read \\u2014 nothing written, re-read and retry) |\\n| DELETE | `/classes/{id}` | manager | Delete a class \\u2014 `409` while it still holds students or courses |\\n| POST | `/classes/{id}/members` | manager | `{user_id}` \\u2014 add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists \\u2014 detach that link first \\u2014 if already a member, or once the class holds `max_class_members`) |\\n| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first \\u00b7 paged |\\n| DELETE | `/classes/{id}/members/{user}` | manager | Remove a member \\u2014 sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |\\n| POST | `/classes/{id}/courses` | teacher | `{course_id}` \\u2014 attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |\\n| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first \\u00b7 paged |\\n| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) \\u2014 the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |"}, {"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); a **staff** row \\u2014 any target whose live role is teacher or higher, not just the session's current teacher \\u2014 needs manager+ |"}, {"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; an omitted `subject_id` is filled from the stored row, so *any* edit is a `409` if someone re-tagged the question since the read \\u2014 nothing written, re-read and retry) |\\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 or if the question's subject was re-tagged since the read \\u2014 nothing written, re-read and retry (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), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) |\\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=` filters by origin subject, `?owner=` (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 \\u2014 or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) |\\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\\" \\u2014 a meal slot name carrying `/ \\\\ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable \\u2014 it still cannot carry a new menu); `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 or class 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` and may not contain `/ \\\\ ? # %` (it becomes part of the menu's URL id); `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 and its attendance marks go with it, in the same transaction; `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); `404` once its menu is gone |\\n| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |\\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) \\u2014 its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent \\u2014 cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** \\u2014 a manager+ frees a closed meal's seat |\\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; `404` if the menu is unpublished mid-request; **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 **manager+** or a parent link \\u2014 a teacher gets a `403`, canteen debt is family debt |\\n| GET | `/meals/ledger/{user}` | student | That student's statement \\u2014 every charge, credit, reversal \\u2014 newest first \\u00b7 paged \\u00b7 same gate (manager+, parent link, or own) |\\n| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` \\u2014 record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |"}, {"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, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |\\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\\") |"}]; +SELECT VALUE sha256 FROM meta:readme; diff --git a/src/constant.rs b/src/constant.rs index e5dcd50..46645a6 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -562,8 +562,15 @@ pub const DEFAULT_API_RATE_LIMIT: u32 = 300; /// bridge — which is the cost this tier rations, not this process. pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20; -/// Once the bucket map holds this many distinct client IPs, expired entries are -/// swept out on the next check. Keeps memory bounded without a reaper task. +/// Once the bucket map holds this many distinct clients, a new key sweeps out +/// the expired entries and, if that frees nothing, evicts the least-spent live +/// buckets — **never an exhausted one** — down to three quarters of this. +/// Evicting a bucket that had reached its limit would hand back the very +/// refusal it was enforcing, so a flood cannot make the limiter fail open; the +/// concession is that while the map is saturated with exhausted buckets a +/// never-before-seen client is admitted unmetered, which is preferred to +/// refusing it (that would let an attacker `429` the world). Keeps memory +/// bounded without a reaper task. pub const PURGE_AT: usize = 10_000; /// The shared counter the limiter folds its local admits into, so a window's diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index c41d02f..501846d 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -452,19 +452,59 @@ impl Appointment { Ok(result.take::>(0)?) } - /// Confirm the meeting. Re-runs the double-booking guard for both teacher - /// and requester against a fresh read under [`APPOINTMENT_LOCK`] — the - /// authoritative check, since only approval commits anyone. Refused (409) - /// when the effective window has already started; that also covers - /// [`accept_proposal`], which lands here. + /// Confirm the meeting at the slot's own window. Re-runs the double-booking + /// guard for both teacher and requester against a fresh read under + /// [`APPOINTMENT_LOCK`] — the authoritative check, since only approval + /// commits anyone. Refused (409) when the effective window has already + /// started; that also covers [`accept_proposal`], which lands here. + /// + /// Also refused (409) while a counter-proposal stands: the effective window + /// would then be the *proposed* one, and the deciding side here is the + /// teacher's, so approving would commit the requester to a time only the + /// teacher ever named. That move belongs to [`accept_proposal`], which the + /// web layer opens to the requester alone. pub async fn approve( id: &AppointmentId, decided_by: &UserId, db: &Database, + ) -> Result { + Self::approve_inner(id, decided_by, None, db).await + } + + /// The one approval path. `accepting` carries the window the caller is + /// answering *for*, which is the only way a proposed one may be committed: + /// it both marks the caller as the proposal's counterparty and pins which + /// proposal they saw. Re-checked on every retry round, so a proposal that + /// moved between the read and the write is refused rather than confirmed. + async fn approve_inner( + id: &AppointmentId, + decided_by: &UserId, + accepting: Option<(Timestamp, Timestamp)>, + db: &Database, ) -> Result { let _guard = APPOINTMENT_LOCK.lock().await; for _ in 0..CAS_UPDATE_RETRIES { let expected = Self::read_pending(id, db).await?; + match accepting { + None if expected.has_proposal() => { + return Err(AppError::Conflict( + "a counter-proposal is standing; only the requester can accept it", + )); + } + Some(_) if !expected.has_proposal() => { + return Err(AppError::Conflict("no time has been proposed")); + } + // The proposal moved between the requester reading it and + // accepting it. Committing here would bind them to a window the + // teacher swapped in after they clicked, which is the whole + // thing the requester-only accept exists to prevent. + Some(accepted) if !expected.proposes(accepted) => { + return Err(AppError::Conflict( + "the proposed time has changed; re-read the booking and accept the new one", + )); + } + _ => {} + } let slot = AppointmentSlot::read(&expected.slot, db) .await? .ok_or(AppError::NotFound)?; @@ -612,20 +652,38 @@ impl Appointment { /// Accept the standing proposal — approval at the proposed time. The /// overlap guard runs again because the time moved. + /// + /// `starts_at`/`ends_at` are the proposal the caller is answering, as they + /// read it. They are not a request to move the meeting: they *pin* the one + /// being accepted, and a proposal that has since been superseded is refused + /// (409) rather than committed. `propose` takes no lock and the two calls + /// are minutes apart, so nothing but this pin can tell "the requester + /// agreed to 10:00" from "the requester's click landed on 23:00". pub async fn accept_proposal( id: &AppointmentId, decided_by: &UserId, + starts_at: Timestamp, + ends_at: Timestamp, db: &Database, ) -> Result { - { - let appointment = Self::read(id, db).await?.ok_or(AppError::NotFound)?; - if appointment.proposed_starts_at.is_none() || appointment.proposed_ends_at.is_none() { - return Err(AppError::Conflict("no time has been proposed")); - } - } - // `approve` re-reads under the lock and reads the proposed window off - // the row, so accepting is approval — no second code path. - Self::approve(id, decided_by, db).await + // The same approval path re-reads under the lock and reads the proposed + // window off the row, so accepting is approval — no second code path. + // Only this door passes `accepting`, and the web layer opens it to the + // requester alone. + Self::approve_inner(id, decided_by, Some((starts_at, ends_at)), db).await + } + + /// Is a counter-proposal standing? Both halves, exactly as [`window`](Self::window) + /// prefers them: a half-written triple is not a proposal and the slot's own + /// window still rules. + fn has_proposal(&self) -> bool { + self.proposed_starts_at.is_some() && self.proposed_ends_at.is_some() + } + + /// Is the standing proposal exactly this window? Milliseconds, the one form + /// both the API and the row speak. + fn proposes(&self, (starts_at, ends_at): (Timestamp, Timestamp)) -> bool { + self.proposed_starts_at == Some(starts_at) && self.proposed_ends_at == Some(ends_at) } /// The row, insisting it is still open for a decision. @@ -853,28 +911,54 @@ mod tests { .await .unwrap() .unwrap(); + let (passed_starts_at, passed_ends_at) = (soon(-30_000), soon(30_000)); let mut standing = current.clone(); - standing.proposed_starts_at = Some(soon(-30_000)); - standing.proposed_ends_at = Some(soon(30_000)); + standing.proposed_starts_at = Some(passed_starts_at); + standing.proposed_ends_at = Some(passed_ends_at); standing .save_if_unchanged(¤t, &db) .await .unwrap() .unwrap(); assert!(matches!( - Appointment::accept_proposal(booking.get_id(), &student, &db).await, + Appointment::accept_proposal( + booking.get_id(), + &student, + passed_starts_at, + passed_ends_at, + &db + ) + .await, Err(AppError::Conflict("that time has already started")) )); // Refused, not half-applied: still pending, still decidable at a time // that can actually happen. let after = Appointment::read(booking.get_id(), &db).await.unwrap(); assert_eq!(after.unwrap().get_status(), AppointmentStatus::Pending); - Appointment::propose(booking.get_id(), soon(60_000), soon(120_000), &teacher, &db) - .await - .unwrap(); - let accepted = Appointment::accept_proposal(booking.get_id(), &student, &db) + let (starts_at, ends_at) = (soon(60_000), soon(120_000)); + Appointment::propose(booking.get_id(), starts_at, ends_at, &teacher, &db) .await .unwrap(); + // Accepting a window that is *not* the standing proposal is refused — + // the pin is what the requester saw, not a request to move the meeting. + assert!(matches!( + Appointment::accept_proposal( + booking.get_id(), + &student, + passed_starts_at, + passed_ends_at, + &db + ) + .await, + Err(AppError::Conflict( + "the proposed time has changed; \ + re-read the booking and accept the new one" + )) + )); + let accepted = + Appointment::accept_proposal(booking.get_id(), &student, starts_at, ends_at, &db) + .await + .unwrap(); assert_eq!(accepted.get_status(), AppointmentStatus::Approved); } diff --git a/src/domain/board.rs b/src/domain/board.rs index 770f937..4cb29cb 100644 --- a/src/domain/board.rs +++ b/src/domain/board.rs @@ -270,6 +270,32 @@ impl Board { one(result.take::>(0)?) } + /// Strip `user` off every board roster they are listed on — the sweep for a + /// user demoted below `student`, who may no longer touch a whiteboard at + /// all ([`crate::web::boards`] keeps such a role off every roster at + /// invite time, so a stale row is exactly what a demotion used to leave). + /// Nothing is deleted: no board, no stroke, not even a board whose roster + /// this empties — a role change must never destroy other people's work. + /// + /// Boards the user *created* come back too, and deliberately unchanged: the + /// creator is not a roster entry (`is_participant` reads the column) and + /// removing them is not expressible. They are returned so the caller can + /// prompt those rooms as well. + pub async fn drop_participant_everywhere( + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "UPDATE board SET participants -= $usr \ + WHERE $usr IN participants OR creator = $usr RETURN AFTER", + ) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + /// Retire the board: permanently read-only, history still readable. /// Idempotent by the `WHERE` — a second call matches nothing and the first /// stamp stands, which is what the stroke path's open-guard reads. diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index 990a453..859277a 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -338,26 +338,19 @@ impl ChatbotMessage { Ok(messages) } - /// The user turn this reserved answer belongs to: the newest `user` row - /// written before it in the same thread. + /// The user turn a reserved answer belongs to, by *identity*: the prompt + /// row of the very POST that reserved it, whose id the answering task + /// carries. /// - /// Ordered by `created_at` then `id`, exactly like every other read path — - /// the two rows one POST writes routinely share a millisecond, so the id - /// tie-break is what keeps this from picking the prompt of the *previous* - /// turn (see [`IDS`]). - pub async fn prompt_for(&self, db: &Database) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM chatbot_message WHERE thread_id = $conv AND role = 'user' \ - AND (created_at < $at OR (created_at = $at AND id < $id)) \ - ORDER BY created_at DESC, id DESC LIMIT 1", - ) - .bind(("conv", self.thread_id.record())) - .bind(("at", self.created_at.as_millis())) - .bind(("id", self.id.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + /// Never derived from write order. Two POSTs on one thread interleave + /// across the two creates — the rows land `userA, userB, asstA, asstB` — + /// so "the newest user row written before this answer" resolves *both* + /// answers to prompt B, and prompt A is never answered. + pub async fn prompt_of( + id: &ChatbotMessageId, + db: &Database, + ) -> Result, AppError> { + Ok(db.select(id.record()).await?) } /// Read one turn only if `user` owns it — the poll loop's read. diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index 05fe701..2faa29f 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -4,7 +4,6 @@ //! [`crate::domain::chatbot_message`], and deleting a thread cascades them. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{ CHATBOT_THREAD_COUNT_FIELD, CHATBOT_THREAD_TABLE, DEFAULT_MAX_CHATBOT_THREADS, @@ -12,6 +11,7 @@ use crate::constant::{ }; use crate::database::Database; use crate::domain::cap; +use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -22,8 +22,12 @@ use crate::validate::validate_required; pub struct ChatbotThreadId(RecordId); impl ChatbotThreadId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// threads sort `updated_at DESC, id DESC` and the id breaks the tie + /// between two threads last touched in the same millisecond, + /// and a random low half sorts arbitrarily inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(CHATBOT_THREAD_TABLE, Ulid::new().to_string())) + Self(RecordId::new(CHATBOT_THREAD_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -151,7 +155,7 @@ impl ChatbotThread { ) -> Result<(Vec, i64), AppError> { PagedList::new( "chatbot_thread WHERE user_id = $usr", - "ORDER BY updated_at DESC", + "ORDER BY updated_at DESC, id DESC", ) .bind("usr", user.record()) .run(limit, offset, db) diff --git a/src/domain/course.rs b/src/domain/course.rs index 070e8c5..b5cc8bd 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -1,5 +1,4 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{ CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, @@ -8,6 +7,7 @@ use crate::constant::{ use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; use crate::domain::term::{self, TermId}; use crate::domain::user::UserId; @@ -22,8 +22,11 @@ const ROSTER_MARK: &str = "course_roster"; pub struct CourseId(RecordId); impl CourseId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// courses list `id DESC` (newest first, [`Course::list_all`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(COURSE_TABLE, Ulid::new().to_string())) + Self(RecordId::new(COURSE_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 658424e..e70f6cd 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -1,10 +1,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN}; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::course::CourseId; use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; use crate::domain::timestamp::{Timestamp, range_error}; use crate::domain::user::UserId; @@ -15,8 +15,12 @@ use crate::validate::validate_optional; pub struct CourseSessionId(RecordId); impl CourseSessionId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// a course's sessions sort `starts_at DESC, id DESC` and the id breaks + /// the tie between two sessions starting at the same instant, + /// and a random low half sorts arbitrarily inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(COURSE_SESSION_TABLE, Ulid::new().to_string())) + Self(RecordId::new(COURSE_SESSION_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -132,7 +136,7 @@ impl CourseSession { ) -> Result<(Vec, i64), AppError> { PagedList::new( "course_session WHERE course = $course", - "ORDER BY starts_at DESC", + "ORDER BY starts_at DESC, id DESC", ) .bind("course", course.record()) .run(limit, offset, db) @@ -164,13 +168,34 @@ impl CourseSession { .await } - /// Delete the session and cascade-remove its roll-call rows. + /// Delete the session and cascade-remove its roll-call rows, in one + /// transaction: as two unbatched queries a failure between them stranded + /// roll-call rows on a session that was already gone. The other half of + /// that invariant is [`crate::domain::session_attendance::SessionAttendance::mark`], + /// which proves the session still exists inside its own write — a + /// transaction here cannot stop a mark that commits *after* this one. pub async fn delete(self, db: &Database) -> Result { - db.query("DELETE session_attendance WHERE session = $s") - .bind(("s", self.id.record())) - .await? - .check()?; - let deleted: Option = db.delete(self.id.record()).await?; + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + DELETE session_attendance WHERE session = $s; + LET $before = (DELETE $s RETURN BEFORE); + RETURN $before; + COMMIT TRANSACTION;", + &[("s".into(), self.id.record().into_value())], + // No THROW of its own — an unconditional cascade, so the only + // error worth telling apart is a lost round (see + // [`crate::domain::exam::Exam::delete`]). + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Read through the trailing `RETURN`, never a hand-counted slot. + let slot = result.num_statements().saturating_sub(2); + let deleted: Option = + result.take::>(slot)?.into_iter().next(); deleted.ok_or(AppError::NotFound) } } diff --git a/src/domain/event.rs b/src/domain/event.rs index bb11b85..7de8495 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -1,13 +1,13 @@ // `Value` looks unused but is load-bearing: the `SurrealValue` derive on the // tagged `EventAudience` enum expands to code that names `Value` unqualified. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; -use ulid::Ulid; use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::enrollment::Enrollment; use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; use crate::domain::registration::Registration; use crate::domain::role::Role; use crate::domain::timestamp::{Timestamp, range_error}; @@ -19,8 +19,11 @@ use crate::validate::{validate_optional, validate_required}; pub struct EventId(RecordId); impl EventId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// events list `id DESC` (newest first, [`Event::list_all`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(EVENT_TABLE, Ulid::new().to_string())) + Self(RecordId::new(EVENT_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -282,13 +285,30 @@ impl Event { } /// Delete the event and cascade-remove its attendance and signup rows. + /// + /// Children first, and all of it in one transaction the way + /// [`crate::domain::course::Course::delete`] does it: run as two queries, a + /// registration or a mark that committed in between outlived its event — + /// an orphan no read path can ever reach and no delete can ever reclaim, + /// since every one of them is keyed on the event that is now gone. pub async fn delete(self, db: &Database) -> Result { - db.query("DELETE attendance WHERE event = $ev; DELETE registration WHERE event = $ev;") + let mut result = db + .query( + "BEGIN TRANSACTION; + DELETE attendance WHERE event = $ev; + DELETE registration WHERE event = $ev; + LET $gone = (DELETE $ev RETURN BEFORE); + RETURN $gone; + COMMIT TRANSACTION;", + ) .bind(("ev", self.id.record())) .await? .check()?; - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + result + .take::>(4)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } } diff --git a/src/domain/exam.rs b/src/domain/exam.rs index bee3280..3f7af04 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -1,11 +1,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{ EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS, }; use crate::database::{Database, transaction_with_retry}; use crate::domain::course::CourseId; +use crate::domain::monotonic_id::next_ulid; use crate::domain::settings::ExamKindDef; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -28,8 +28,11 @@ use crate::validate::{ pub struct ExamId(RecordId); impl ExamId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// exams list `id DESC` (newest first, [`Exam::list_all`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(EXAM_TABLE, Ulid::new().to_string())) + Self(RecordId::new(EXAM_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 6472563..93d2823 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -11,7 +11,6 @@ //! same-course by the web layer, exactly like an exam question's subject. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{ HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN, @@ -21,6 +20,7 @@ use crate::database::Database; use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; use crate::domain::subject::SubjectId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -42,8 +42,11 @@ fn subject_gone() -> AppError { pub struct HomeworkId(RecordId); impl HomeworkId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// homework lists `id DESC` (newest first, [`Homework::list_all`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(HOMEWORK_TABLE, Ulid::new().to_string())) + Self(RecordId::new(HOMEWORK_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index bdaff07..17a4803 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -20,6 +20,7 @@ use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::homework::HomeworkId; use crate::domain::homework_submission::{HomeworkSubmission, HomeworkSubmissionId}; +use crate::domain::monotonic_id::next_ulid; use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::timestamp::Timestamp; use crate::error::AppError; @@ -28,8 +29,11 @@ use crate::error::AppError; pub struct HomeworkFileId(RecordId); impl HomeworkFileId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// a submission's files list `id DESC` (newest first, [`HomeworkFile::list_for_submission`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(HOMEWORK_FILE_TABLE, Ulid::new().to_string())) + Self(RecordId::new(HOMEWORK_FILE_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { diff --git a/src/domain/message.rs b/src/domain/message.rs index 02a0e1c..a7af28e 100644 --- a/src/domain/message.rs +++ b/src/domain/message.rs @@ -7,13 +7,13 @@ //! removed. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{ MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, MESSAGE_TABLE, RECIPIENT_FOLDERS, SENDER_FOLDERS, }; use crate::database::Database; +use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -102,8 +102,11 @@ impl Folder { pub struct MessageId(RecordId); impl MessageId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// the folder listings sort `id DESC` (newest first, [`Message::list_folder`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(MESSAGE_TABLE, Ulid::new().to_string())) + Self(RecordId::new(MESSAGE_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -429,6 +432,42 @@ mod tests { assert_eq!(MessageBody::try_new("").unwrap().as_str(), ""); } + /// The `next_ulid` hazard: an inbox is documented newest-first and sorts + /// `id DESC`, so messages sent inside one millisecond must come back in + /// exact reverse write order, not at random (src/domain/monotonic_id.rs). + /// Asserts the *stored* order, not the mint order. + #[tokio::test] + async fn inbox_is_newest_first_within_a_millisecond() { + let db = crate::database::init_mem().await.unwrap(); + let sender = UserId::from_key("a"); + let recipient = UserId::from_key("b"); + let mut sent = Vec::new(); + for i in 0..25 { + let message = Message::send( + &sender, + &recipient, + MessageSubject::try_new(&format!("s{i}")).unwrap(), + MessageBody::try_new("").unwrap(), + None, + &db, + ) + .await + .unwrap(); + sent.push(message.get_id().key().to_string()); + } + + let (listed, total) = Message::list_folder(&recipient, Folder::Inbox, None, None, 0, &db) + .await + .unwrap(); + assert_eq!(total, 25); + sent.reverse(); + let read_back: Vec = listed + .iter() + .map(|row| row.get_id().key().to_string()) + .collect(); + assert_eq!(read_back, sent); + } + #[tokio::test] async fn folder_sides_resolve_by_membership() { let sender = UserId::from_key("a"); diff --git a/src/domain/note.rs b/src/domain/note.rs index 3aded84..1bbe251 100644 --- a/src/domain/note.rs +++ b/src/domain/note.rs @@ -1,9 +1,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN, NOTE_TABLE}; use crate::database::Database; use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -13,8 +13,11 @@ use crate::validate::{validate_optional, validate_required}; pub struct NoteId(RecordId); impl NoteId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// notes list `id DESC` (newest first, [`Note::list_for_user`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(NOTE_TABLE, Ulid::new().to_string())) + Self(RecordId::new(NOTE_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -143,13 +146,35 @@ impl Note { /// disk are the web layer's to remove (it lists them before calling this); /// a crash in between leaves at worst an unreachable blob, never a row /// pointing at nothing. + /// + /// Children first, in one transaction, the way + /// [`crate::domain::course::Course::delete`] does it: as two queries, an + /// upload that committed in between kept its row while the note went, and + /// nothing could ever list or delete it again. + /// + /// ponytail: the blob of *that* upload is still orphaned on disk — the web + /// layer snapshots the file list before this call, so a row created inside + /// the window is deleted here but its file is never unlinked. Ceiling: one + /// leaked blob per racing upload-vs-delete, unreachable but not reclaimed. + /// Upgrade path: return the deleted `note_file` rows from this transaction + /// and have the handler unlink *those* instead of its snapshot. pub async fn delete(self, db: &Database) -> Result { - db.query("DELETE note_file WHERE note = $note") + let mut result = db + .query( + "BEGIN TRANSACTION; + DELETE note_file WHERE note = $note; + LET $gone = (DELETE $note RETURN BEFORE); + RETURN $gone; + COMMIT TRANSACTION;", + ) .bind(("note", self.id.record())) .await? .check()?; - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + result + .take::>(3)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } } diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs index 259c1a0..bf9fed3 100644 --- a/src/domain/note_file.rs +++ b/src/domain/note_file.rs @@ -6,7 +6,6 @@ //! before blob on delete); this module owns the rows. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{ MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, MAX_NOTE_FILES, NOTE_FILE_COUNT_FIELD, @@ -14,6 +13,7 @@ use crate::constant::{ }; use crate::database::Database; use crate::domain::cap; +use crate::domain::monotonic_id::next_ulid; use crate::domain::note::NoteId; use crate::domain::page::PagedList; use crate::error::{AppError, ValidationError}; @@ -22,8 +22,11 @@ use crate::error::{AppError, ValidationError}; pub struct NoteFileId(RecordId); impl NoteFileId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// a note's files list `id DESC` (newest first, [`NoteFile::list_for_note`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(NOTE_FILE_TABLE, Ulid::new().to_string())) + Self(RecordId::new(NOTE_FILE_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs index ac8ff53..537e5c2 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -1,8 +1,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::POMODORO_SESSION_TABLE; use crate::database::{Database, transaction_with_retry}; +use crate::domain::monotonic_id::next_ulid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -11,10 +11,14 @@ use crate::error::AppError; pub struct PomodoroSessionId(RecordId); impl PomodoroSessionId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// the log sorts `started_at DESC, id DESC` and the id breaks the tie between + /// two sessions started at the same instant. The `open_` key below never ties + /// with itself (one running session per user), so it needs no ordering. pub fn generate() -> Self { Self(RecordId::new( POMODORO_SESSION_TABLE, - Ulid::new().to_string(), + next_ulid().to_string(), )) } @@ -148,14 +152,17 @@ impl PomodoroSession { } /// Every session of `user`, newest first — the running one (if any) - /// included. Ordered by `started_at`: the open entry's `open_` key doesn't - /// sort with the ULIDs, so id order would misplace it. + /// included. Ordered by `started_at`, never by id alone: the open entry's + /// `open_` key doesn't sort with the ULIDs, so id order would misplace it. + /// The `id` tie-break behind it only ever separates two *finished* stints + /// sharing a `started_at` — there is one running row per user, so it can + /// never tie with itself. pub async fn list_for_user( user: &UserId, db: &Database, ) -> Result, AppError> { let mut result = db - .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC") + .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC, id DESC") .bind(("usr", user.record())) .await? .check()?; @@ -165,6 +172,8 @@ impl PomodoroSession { #[cfg(test)] mod tests { + use ulid::Ulid; + use super::*; use crate::database; diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index 54fff54..3083483 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -11,13 +11,13 @@ //! this module owns the rows. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{ MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_QUESTION_TABLE, STATUS_APPROVED, STATUS_PENDING, }; use crate::database::Database; +use crate::domain::monotonic_id::next_ulid; use crate::domain::note_file::FileContentType; use crate::domain::solution::Solution; use crate::domain::timestamp::Timestamp; @@ -29,8 +29,11 @@ use crate::validate::validate_required; pub struct PoolQuestionId(RecordId); impl PoolQuestionId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break ([`PoolQuestion::list_all`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(POOL_QUESTION_TABLE, Ulid::new().to_string())) + Self(RecordId::new(POOL_QUESTION_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -294,6 +297,8 @@ impl PoolQuestion { #[cfg(test)] mod tests { + use ulid::Ulid; + use super::*; use crate::database; use crate::domain::solution::{Solution, SolutionBody}; diff --git a/src/domain/registration.rs b/src/domain/registration.rs index ef9b0e3..1844f12 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -172,4 +172,53 @@ impl Registration { .check()?; Ok(result.take::>(3)?.into_iter().next()) } + + /// Free every *still-freeable* seat a demotion to `parent` strands. + /// + /// Only a `parent` is swept, and that is the whole rule rather than the + /// non-student sweep the enrollment side runs: staff free their own seats + /// by hand (`unregister` allows the self case), so a promoted student is + /// never stranded and their signups are theirs to keep. A parent holds no + /// such door — the route is `RequireTeacher`, and no one else may free a + /// non-student's seat — so their row is the one thing on a signup list + /// nothing can ever remove: the event answers "full" forever and the + /// parent stays on the roster and stays markable, because the registration + /// audience resolves on the row's mere existence. + /// + /// A list that has already **frozen** is left exactly as it stands. The + /// freeze is not re-spelled here — [`Event::registration_capacity`] is the + /// one place it is decided, and its `Conflict` arm *is* the freeze (its + /// other refusal is the audience). Past that point the list is historical + /// record, the way a roll-call row keeps its retired exam kind: the seat + /// costs nothing (nobody can book the event again either) and deleting the + /// row would rewrite an attendance roster behind the freeze's back, + /// irrecoverably — re-registering answers 409. + /// + /// Row and seat still move together: each removal is + /// [`Registration::remove`]'s single transaction. Per row rather than one + /// transaction for all of them, because the seats are independent facts on + /// unrelated events — nothing is left inconsistent by stopping halfway. + pub async fn sweep_for_parent(user: &UserId, db: &Database) -> Result<(), AppError> { + let mut result = db + .query("SELECT * FROM registration WHERE user = $usr") + .bind(("usr", user.record())) + .await? + .check()?; + for row in result.take::>(0)? { + // A row whose event record is *gone* is deleted, never skipped: + // there is no seat to hand back and no list to freeze, so the + // carve-out below cannot apply to it — and `unregister` answers 404 + // on the missing event, so a skipped orphan is stranded forever. + if let Some(event) = Event::read(&row.event, db).await? + && matches!( + event.registration_capacity(), + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) + ) + { + continue; + } + Self::remove(&row.event, user, db).await?; + } + Ok(()) + } } diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index f6452bb..6c2a14b 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -1,7 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::SESSION_ATTENDANCE_TABLE; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::attendance::AttendanceStatus; use crate::domain::course::CourseId; use crate::domain::course_session::{CourseSession, CourseSessionId}; @@ -77,6 +77,22 @@ impl SessionAttendance { /// Record (or overwrite) `user`'s status for the session. One row per /// (session, user), keyed by a deterministic composite id so this is a /// single atomic UPSERT — concurrent marks converge on the one row. + /// + /// The "session still exists" gate rides in the same transaction as the + /// mark, the mirror of the cascade in [`CourseSession::delete`]: the + /// caller's pre-flight read sits four round trips in front of this write, + /// so a delete landing in that gap used to leave a roll-call row on a + /// session that was gone — and that row was *unremovable*, its only delete + /// route 404ing on the vanished session while the attendance report went + /// on counting it. A deleted session reads NONE, which is falsy, so the + /// gate is written as an explicit `IS NONE` (see + /// [`crate::domain::exam_result::ExamResult::grade`]). + /// + /// Sound to re-send while the store answers "conflict, retry": the gate + /// reads the record a delete writes, so the two contend by design, and the + /// UPSERT cannot legitimately answer "already exists" — its composite id is + /// bijective with the `session_attendance_session_user` unique tuple, so + /// the index entry can only point at the row the id already names. pub async fn mark( session: &CourseSession, user: &UserId, @@ -92,11 +108,43 @@ impl SessionAttendance { status, marked_by: marked_by.clone(), }; - let saved: Option = db - .upsert(attendance.id.record()) - .content(attendance) - .await?; - saved.ok_or_else(|| AppError::Internal("failed to mark session attendance".into())) + let (mut written, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + IF (SELECT VALUE id FROM ONLY $sess) IS NONE { THROW 'session_missing' }; + LET $after = (UPSERT $id CONTENT $row RETURN AFTER); + RETURN $after; + COMMIT TRANSACTION;", + &[ + // `$session` is SurrealDB's own protected variable (the auth + // session): binding that name errors the whole query. + ("sess".into(), session.get_id().record().into_value()), + ("id".into(), attendance.id.record().into_value()), + ("row".into(), attendance.into_value()), + ], + &["session_missing"], + ) + .await?; + // An aborted transaction errors every slot and only the THROW's own + // slot names the marker, so a refusal is read by marker while a lost + // round was already re-sent — never reported as a 500. + if errors + .values() + .any(|error| error.to_string().contains("session_missing")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, + // so its slot follows the statement count instead of a hand-kept one. + let slot = written.num_statements().saturating_sub(2); + written + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to mark session attendance".into())) } pub async fn list_for_session( diff --git a/src/domain/solution.rs b/src/domain/solution.rs index 4cfabf0..e47afc9 100644 --- a/src/domain/solution.rs +++ b/src/domain/solution.rs @@ -10,10 +10,10 @@ use std::collections::HashMap; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE}; use crate::database::Database; +use crate::domain::monotonic_id::next_ulid; use crate::domain::note_file::FileContentType; use crate::domain::page::PagedList; use crate::domain::pool_question::PoolQuestionId; @@ -26,8 +26,11 @@ use crate::validate::validate_required; pub struct SolutionId(RecordId); impl SolutionId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// solutions sort `offered_at ASC, id ASC` and the id *is* the tie-break ([`Solution::list_for_question`]), + /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { - Self(RecordId::new(SOLUTION_TABLE, Ulid::new().to_string())) + Self(RecordId::new(SOLUTION_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -249,6 +252,8 @@ impl Solution { #[cfg(test)] mod tests { + use ulid::Ulid; + use super::*; #[tokio::test] diff --git a/src/domain/term.rs b/src/domain/term.rs index 2c9f130..de527fd 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -7,11 +7,11 @@ //! rule that guards exams/lessons/events deliberately does not apply here. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_CLASS_COUNT_FIELD, TERM_TABLE}; use crate::database::{Database, write_with_retry}; use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; use crate::domain::timestamp::{Timestamp, range_error}; use crate::error::{AppError, ValidationError}; @@ -21,8 +21,12 @@ use crate::validate::validate_required; pub struct TermId(RecordId); impl TermId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// terms sort `starts_at DESC, id DESC` and the id breaks the tie between + /// two terms starting at the same instant, + /// and a random low half sorts arbitrarily inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(TERM_TABLE, Ulid::new().to_string())) + Self(RecordId::new(TERM_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -137,7 +141,7 @@ impl Term { offset: i64, db: &Database, ) -> Result<(Vec, i64), AppError> { - PagedList::new("term", "ORDER BY starts_at DESC") + PagedList::new("term", "ORDER BY starts_at DESC, id DESC") .run(limit, offset, db) .await } @@ -232,6 +236,48 @@ mod tests { assert_eq!(moved.get_ends_at(), at(300)); } + /// Terms are listed newest-first *and* paged by offset, so the sort has to + /// be a total order: `starts_at` alone leaves rows that share an instant in + /// an arbitrary order, and offset paging over an unstable order can hand + /// the same row out twice while skipping another. Pins the `id DESC` + /// tie-break on identical `starts_at` — stored read-back, then page by page. + #[tokio::test] + async fn identical_starts_at_still_pages_each_term_exactly_once() { + let db = crate::database::init_mem().await.unwrap(); + let at = Timestamp::from_millis; + let mut minted = Vec::new(); + for i in 0..12 { + let term = Term::create( + TermName::try_new(&format!("t{i}")).unwrap(), + at(100), + at(200), + &db, + ) + .await + .unwrap(); + minted.push(term.get_id().key().to_string()); + } + // Newest first: the tie-break runs the same way as the primary column. + minted.reverse(); + + let (listed, total) = Term::list_all(None, 0, &db).await.unwrap(); + assert_eq!(total, 12); + let read_back: Vec = listed + .iter() + .map(|row| row.get_id().key().to_string()) + .collect(); + assert_eq!(read_back, minted); + + // The assertion that catches skip/duplicate: walk it in pages of 5. + let mut paged = Vec::new(); + for offset in [0, 5, 10] { + let (page, total) = Term::list_all(Some(5), offset, &db).await.unwrap(); + assert_eq!(total, 12); + paged.extend(page.iter().map(|row| row.get_id().key().to_string())); + } + assert_eq!(paged, minted, "every term exactly once, in list order"); + } + #[tokio::test] async fn name_is_required_and_bounded() { assert!(TermName::try_new("2026 Fall").is_ok()); diff --git a/src/domain/user.rs b/src/domain/user.rs index 6f7d833..56380b9 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -3,11 +3,11 @@ use std::sync::OnceLock; use argon2::password_hash::SaltString; use argon2::{Argon2, PasswordHasher, PasswordVerifier}; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::{DECOY_PASSWORD, USER_TABLE}; use crate::database::Database; use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; @@ -21,8 +21,13 @@ use crate::validate::{validate_password, validate_username}; pub struct UserId(RecordId); impl UserId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// users list `id DESC` (newest first, [`User::list_all`]) and page by + /// offset over that order, and a random low half scrambles rows minted in + /// the same millisecond. Not a secret: the session token is separate + /// (32-byte CSPRNG, `web::auth`), so id order carries no authority. pub fn generate() -> Self { - Self(RecordId::new(USER_TABLE, Ulid::new().to_string())) + Self(RecordId::new(USER_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs index ecde93f..1ac7874 100644 --- a/src/domain/work_entry.rs +++ b/src/domain/work_entry.rs @@ -1,9 +1,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::constant::WORK_ENTRY_TABLE; use crate::database::{Database, transaction_with_retry}; use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -23,8 +23,12 @@ pub(crate) fn out_before_in_error() -> AppError { pub struct WorkEntryId(RecordId); impl WorkEntryId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: + /// the log sorts `check_in DESC, id DESC` and the id breaks the tie between + /// two stints checked in at the same instant. The `open_` key below never + /// ties with itself (one open stint per user), so it needs no ordering. pub fn generate() -> Self { - Self(RecordId::new(WORK_ENTRY_TABLE, Ulid::new().to_string())) + Self(RecordId::new(WORK_ENTRY_TABLE, next_ulid().to_string())) } /// The deterministic id of `user`'s *open* entry. At most one open stint @@ -171,18 +175,24 @@ impl WorkEntry { } /// Every stint of `user`, newest first — the open one (if any) included. - /// Ordered by `check_in`: the open entry's `open_` key doesn't sort with - /// the ULIDs, so id order would misplace it. + /// Ordered by `check_in`, never by id alone: the open entry's `open_` key + /// doesn't sort with the ULIDs, so id order would misplace it. The `id` + /// tie-break behind it only ever separates two *closed* stints sharing a + /// `check_in` — there is one open row per user, so it can never tie with + /// itself — and that is what keeps offset paging from skipping a row. pub async fn list_for_user( user: &UserId, limit: Option, offset: i64, db: &Database, ) -> Result<(Vec, i64), AppError> { - PagedList::new("work_entry WHERE user = $usr", "ORDER BY check_in DESC") - .bind("usr", user.record()) - .run(limit, offset, db) - .await + PagedList::new( + "work_entry WHERE user = $usr", + "ORDER BY check_in DESC, id DESC", + ) + .bind("usr", user.record()) + .run(limit, offset, db) + .await } /// Persist corrected instants (manager fix-ups on closed entries; the web @@ -216,6 +226,8 @@ impl WorkEntry { #[cfg(test)] mod tests { + use ulid::Ulid; + use super::*; use crate::database; diff --git a/src/lib.rs b/src/lib.rs index 3dbd952..69a4c07 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -64,7 +64,7 @@ use crate::state::AppState; (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"), - (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board, since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"), + (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there — taken off the roster, or demoted below `student` — is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion to `parent` also sweeps that account off every board roster it was on, though a board whose *creator* was demoted is left standing — barred to them, unchanged for everyone else. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board, since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) — unlink them first. Read: any authenticated user; edit: manager+"), ), )] diff --git a/src/rate_limit.rs b/src/rate_limit.rs index 54c00a5..a4a6f18 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -16,15 +16,32 @@ //! Requests are keyed by client IP. By default that is the peer address of the //! TCP connection ([`ConnectInfo`]). Behind a reverse proxy every connection //! shows the proxy's address, so set `TRUST_PROXY=true` to key on the -//! **rightmost** `X-Forwarded-For` entry instead — that hop is appended by the -//! nearest proxy and is the only one the client cannot forge. Never enable it -//! when clients can reach the server directly: the header is then entirely -//! attacker-controlled and the limiter is trivially bypassed. +//! **rightmost entry of the last** `X-Forwarded-For` header instead — that hop +//! is appended by the nearest proxy and is the only one the client cannot +//! forge. Both halves matter: a proxy may append its hop as a separate header +//! line rather than into the client's, and reading only the first line would +//! hand the key straight back to the client. Never enable it when clients can +//! reach the server directly: the header is then entirely attacker-controlled +//! and the limiter is trivially bypassed. //! //! Fixed windows admit up to a 2× burst straddling a window boundary. That is //! an accepted trade-off for an implementation simple enough to read in one //! sitting; argon2 keeps each allowed login attempt expensive anyway. //! +//! # Bounding the bucket map +//! +//! One client, one bucket, so the map is only as bounded as the client set — +//! and an IPv6 /64 is not bounded at all. At [`crate::constant::PURGE_AT`] a +//! new key first sweeps out the lapsed windows and then, if that frees +//! nothing, evicts down to three quarters of the cap ([`evict_cheapest`]). +//! Exhausted buckets are exempt from eviction: they are the only ones actually +//! refusing anyone, and freeing one *raises* the limit for a client that had +//! reached it. When every bucket is exhausted there is nothing to evict and +//! the map stays at the cap; the unknown key is then admitted without a bucket +//! rather than refused, which concedes that a new client is unmetered while +//! the map is saturated but keeps an attacker from `429`-ing everyone at once +//! simply by filling it. +//! //! # The shared window //! //! The counters above are per process. [`RateLimiter::share`] also carries them @@ -221,8 +238,27 @@ impl RateLimiter { let now = Instant::now(); let mut buckets = self.buckets.lock().expect("rate limiter mutex poisoned"); - if buckets.len() >= PURGE_AT { + // Only a *new* key can grow the map, so only a new key pays for a sweep + // — a client already in there stays one hash lookup, saturated or not. + // ponytail: while the map is saturated every new key still pays one + // O(n) scan. Ceiling: it takes 10k live exhausted clients to get there + // and the scan is the attacker's own request. Upgrade path: keep the + // earliest `window_start` beside the map and skip the scan until then. + if buckets.len() >= PURGE_AT && !buckets.contains_key(&key) { buckets.retain(|_, b| now.duration_since(b.window_start) < self.window); + // Lapsed buckets alone are no bound: enough distinct clients inside + // one window (one IPv6 /64 is enough) frees nothing, and the map + // would grow while every request paid for the scan. + if buckets.len() >= PURGE_AT { + evict_cheapest(&mut buckets, PURGE_AT - PURGE_AT / 4, self.max); + } + if buckets.len() >= PURGE_AT { + // Every bucket left is exhausted and none may be dropped. Admit + // this unknown key without a bucket rather than refuse it: an + // attacker who can saturate the map must not be able to 429 the + // world, and every client already in the map keeps its counter. + return Ok(()); + } } let bucket = buckets.entry(key).or_insert_with(|| Bucket::opened_at(now)); @@ -243,6 +279,50 @@ impl RateLimiter { } } +/// Drop buckets until at most `target` remain, cheapest first, and **never** a +/// bucket that has spent `max` or more. +/// +/// The exemption is the whole point. An exhausted bucket is the only thing in +/// here actually refusing anyone, and evicting it hands that refusal straight +/// back to whoever earned it. Cheapest-first alone does not protect it: the +/// cutoff is a `<=`, so ties go arbitrarily, and an attacker who drives every +/// flood key to exactly the victim's spend puts the victim inside the tie band +/// (measured: a victim at `max` freed after ~12.5k flood keys). Exhaustion, +/// not rank, is what decides. +/// +/// Among the rest, least-spent-first: those are the throwaway keys a flood is +/// made of, and evicting one gives away only what it had spent. Evicting by +/// age would instead pick out long-running buckets, which is backwards. +/// +/// One pass over the map, and only when a new key arrives at the cap: the +/// target sits a quarter below it, so the sweep is amortised over that many +/// further inserts and the common path stays a single hash lookup. +fn evict_cheapest(buckets: &mut HashMap, target: usize, max: u32) { + let Some(excess) = buckets.len().checked_sub(target).filter(|n| *n > 0) else { + return; + }; + let mut spent: Vec = buckets + .values() + .map(Bucket::spent) + .filter(|spent| *spent < max) + .collect(); + // Nothing but exhausted buckets: the caller decides what to do instead. + let Some(excess) = Some(excess.min(spent.len())).filter(|n| *n > 0) else { + return; + }; + // The `excess`-th smallest spend among the evictable: at least `excess` + // buckets are at or under it, which is what makes the budgeted retain + // below drop exactly `excess`. + let (_, &mut cutoff, _) = spent.select_nth_unstable(excess - 1); + let mut budget = excess; + buckets.retain(|_, b| { + let spent = b.spent(); + let evict = budget > 0 && spent < max && spent <= cutoff; + budget -= usize::from(evict); + !evict + }); +} + /// One bucket's report, taken while the map was locked so the round can run /// its query without holding it. `counted` is the `count` the delta was read /// from — a request admitted mid-round bumps `count` past it and is simply @@ -435,19 +515,23 @@ async fn with_deadline( /// Resolve the client IP a request is billed against. /// -/// With `trust_proxy`, prefer the rightmost `X-Forwarded-For` entry — appended -/// by the nearest (trusted) proxy, unlike the left entries which arrive -/// attacker-controlled. Otherwise (or when the header is missing/unparseable) -/// fall back to the connection's peer address. `oneshot`-driven routers carry -/// no [`ConnectInfo`]; those requests share the unspecified-address bucket. +/// With `trust_proxy`, prefer the rightmost entry of the *last* +/// `X-Forwarded-For` header — appended by the nearest (trusted) proxy, unlike +/// the left entries and the earlier header lines, which arrive +/// attacker-controlled (a proxy that appends its own header line instead of +/// extending the client's leaves the client's line first). Earlier lines are +/// only consulted if the last one is empty or unparseable; if none yield an +/// address (or the header is missing) fall back to the connection's peer +/// address. `oneshot`-driven routers carry no [`ConnectInfo`]; those requests +/// share the unspecified-address bucket. fn client_ip(req: &Request, trust_proxy: bool) -> IpAddr { if trust_proxy && let Some(ip) = req .headers() - .get("x-forwarded-for") - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.rsplit(',').next()) - .and_then(|entry| entry.trim().parse().ok()) + .get_all("x-forwarded-for") + .iter() + .rev() + .find_map(|v| v.to_str().ok()?.rsplit(',').next()?.trim().parse().ok()) { return ip; } @@ -497,6 +581,32 @@ mod tests { ); } + /// A proxy that appends its hop as its own header line instead of + /// extending the client's: the client's line comes first and is entirely + /// forged, so only the last line may be billed. + #[tokio::test] + async fn client_ip_takes_the_last_forwarded_header_line() { + let two_lines = |first: &str, last: &str| { + axum::http::Request::builder() + .uri("/") + .header("x-forwarded-for", first) + .header("x-forwarded-for", last) + .body(Body::empty()) + .unwrap() + }; + + assert_eq!( + client_ip(&two_lines("1.1.1.1, 6.6.6.6", "9.9.9.9"), true), + "9.9.9.9".parse::().unwrap() + ); + // An unusable last line falls back through the earlier ones before it + // gives up on the header entirely. + assert_eq!( + client_ip(&two_lines("1.1.1.1, 6.6.6.6", "not-an-ip"), true), + "6.6.6.6".parse::().unwrap() + ); + } + #[tokio::test] async fn client_ip_ignores_forwarded_header_when_proxy_is_untrusted() { let request = req(Some("1.1.1.1"), Some("10.9.8.7:443")); @@ -634,9 +744,77 @@ mod tests { } assert_eq!(limiter.buckets.lock().unwrap().len(), PURGE_AT); - // All those windows lapse; the next check sweeps them out. + // All those windows lapse; the next *new* client sweeps them out (only + // a key that would grow the map pays for a sweep — 10.x is taken above, + // so the new client has to come from somewhere else). tokio::time::advance(Duration::from_secs(61)).await; - assert!(limiter.check(ip(1)).is_ok()); + let newcomer = IpAddr::V4(Ipv4Addr::new(172, 16, 0, 1)); + assert!(limiter.check(newcomer).is_ok()); assert_eq!(limiter.buckets.lock().unwrap().len(), 1); } + + /// The bound has to hold when *nothing* has lapsed — the sweep above frees + /// nothing then, and one IPv6 /64 supplies all the live keys it takes. The + /// eviction must spend itself on the throwaway keys, never on the + /// exhausted bucket that the flood is trying to buy a fresh window for. + #[tokio::test(start_paused = true)] + async fn live_buckets_are_evicted_so_the_map_stays_bounded() { + let limiter = RateLimiter::per_minute(5, false); + for _ in 0..5 { + assert!(limiter.check(ip(1)).is_ok()); + } + assert!(limiter.check(ip(1)).is_err(), "victim starts exhausted"); + + // Twice the threshold in distinct clients, all inside one window. + for i in 0..2 * PURGE_AT as u32 { + let addr = IpAddr::V4(Ipv4Addr::from(0x0b00_0000 + i)); + assert!(limiter.check(addr).is_ok()); + assert!( + limiter.buckets.lock().unwrap().len() <= PURGE_AT, + "map grew past the cap at client {i}" + ); + } + + assert!( + limiter.check(ip(1)).is_err(), + "the flood must not have bought the exhausted bucket a fresh window" + ); + } + + /// The flood above was cheap to tell apart. This one is not: every flood + /// key is driven to *exactly* the spend of the bucket it is trying to + /// free, so a cheapest-first cutoff of `<=` puts the victim inside the tie + /// band and picks arbitrarily. Nothing that has reached its limit may be + /// evicted, whoever else shares its spend — a limiter that forgets an + /// exhausted bucket fails open, which is worse than the unbounded map. + #[tokio::test(start_paused = true)] + async fn a_flood_at_the_victims_own_spend_frees_nobody() { + const MAX: u32 = 5; + let limiter = RateLimiter::per_minute(MAX, false); + // Every key here is driven to exhaustion, the named victim first. + let keys: Vec = std::iter::once(ip(1)) + .chain((0..PURGE_AT as u32).map(|i| IpAddr::V4(Ipv4Addr::from(0x0b00_0000 + i)))) + .collect(); + for key in &keys { + for _ in 0..MAX { + assert!(limiter.check(*key).is_ok()); + } + } + + assert!( + limiter.buckets.lock().unwrap().len() <= PURGE_AT, + "map grew past the cap" + ); + + // The first `PURGE_AT` keys — the victim among them — filled the map + // before it saturated, so every one of them was metered all the way to + // its limit and every one of them must still be refused. An eviction + // that dropped an exhausted bucket shows up right here, as an admit. + for key in &keys[..PURGE_AT] { + assert!( + limiter.check(*key).is_err(), + "{key} was exhausted and is being served again" + ); + } + } } diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 0ade674..5d3c7eb 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -87,6 +87,18 @@ struct Reschedule { ends_at: i64, } +#[derive(Deserialize, ToSchema)] +struct AcceptReschedule { + /// The proposal being accepted, copied from the booking's + /// `proposed_starts_at`/`proposed_ends_at` as it was read. Not a request to + /// move the meeting: it pins *which* proposal this answer is for, so one the + /// teacher has since replaced answers `409` instead of committing you to a + /// window you never saw. + #[schema(example = 1_900_000_000_000_i64)] + proposed_starts_at: i64, + proposed_ends_at: i64, +} + #[derive(Serialize, ToSchema)] struct SlotResponse { #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] @@ -563,6 +575,12 @@ async fn list_appointments( /// approval is what commits anyone, so a time colliding with another approved /// meeting of the teacher or of the requester is refused (`409`), as is a /// window that has already started — that meeting could never be cancelled. +/// +/// Refused (`409`) too while a counter-proposal stands: the proposed time is +/// the teacher's own, so confirming it here would commit the requester to a +/// time they never agreed to. Answering a proposal is the requester's alone: +/// `PATCH /{id}/reschedule/accept` (which *is* approval, at the proposed time) +/// or `PATCH /{id}/reschedule/decline` (which cancels the booking). #[utoipa::path( patch, path = "/{id}/approve", @@ -574,7 +592,7 @@ async fn list_appointments( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the slot's teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "No longer pending, the time has already started, or it collides with another approved appointment", body = ErrorResponse), + (status = 409, description = "No longer pending, a counter-proposal is standing (only the requester can accept it), the time has already started, or it collides with another approved appointment", body = ErrorResponse), ), )] async fn approve( @@ -731,28 +749,49 @@ async fn reschedule( /// double-booking guard runs again for both sides (`409` if the moved time now /// collides with something else, or has already started — agreeing to a window /// that began would mint a meeting nobody can cancel). +/// +/// The body **names the proposal being accepted** (`proposed_starts_at` / +/// `proposed_ends_at`, copied from the booking as it was read). A teacher may +/// re-propose at any time, and the two calls are minutes apart, so without the +/// pin the teacher would choose which window the requester's click commits +/// them to. A superseded proposal answers `409` — re-read the booking and +/// accept (or decline) the new one. #[utoipa::path( patch, path = "/{id}/reschedule/accept", tag = "appointments", security(("session_cookie" = [])), params(("id" = String, Path, description = "Appointment id")), + request_body = AcceptReschedule, responses( (status = 200, description = "Approved at the proposed time", body = AppointmentResponse), + (status = 400, description = "Missing or unreadable body", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the requester", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "No time has been proposed, the booking is no longer pending, the proposed time has already started, or it collides with another approved appointment", body = ErrorResponse), + (status = 409, description = "No time has been proposed, the proposal has since changed (re-read it), the booking is no longer pending, the proposed time has already started, or it collides with another approved appointment", body = ErrorResponse), ), )] async fn accept_reschedule( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, + Json(req): Json, ) -> Result, AppError> { let id = AppointmentId::from_key(&id); ensure_requester(&id, &user, &st.db).await?; - let appointment = Appointment::accept_proposal(&id, user.get_id(), &st.db).await?; + // Unvalidated on purpose: these are not a time to meet, they are the + // requester's answer to "which proposal?" — the domain compares them to the + // row and refuses anything else, so a past or inverted pair is simply a + // mismatch (409), never a booking. + let appointment = Appointment::accept_proposal( + &id, + user.get_id(), + Timestamp::from_millis(req.proposed_starts_at), + Timestamp::from_millis(req.proposed_ends_at), + &st.db, + ) + .await?; one_appointment(appointment, &st.db).await } diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index 26255e9..0d6f8e6 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -48,12 +48,12 @@ //! - the five frames the REST routes publish, forwarded verbatim: `cleared`, //! `locked`, `closed`, `participants`, `deleted` //! -//! `closed` and `deleted` end the room. `participants` is re-derived against -//! the database and drops this socket if it is no longer on the board — but the -//! notification is only the *prompt* half of that: every stroke, clear and lock -//! re-reads the board and re-checks the roster, so a socket that missed the -//! frame (it lagged, or the roster changed without one) is refused all the -//! same. A frame is never the authority here. +//! `closed` and `deleted` end the room. A frame is never the authority here: +//! every frame is authorized against the database *before* it is delivered, +//! and every stroke, clear and lock re-reads the board and re-checks the role +//! and the roster before it is written. So a caller who lost the right to be +//! here — taken off the roster, or demoted out of whiteboard access — is +//! refused and dropped whether or not any notification reached them. use std::collections::VecDeque; use std::time::Duration; @@ -71,7 +71,7 @@ use crate::domain::board::{Board, BoardId}; use crate::domain::board_stroke::{self, BoardStroke}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; -use crate::domain::user::UserId; +use crate::domain::user::{User, UserId}; use crate::error::AppError; use crate::state::AppState; use crate::web::CurrentUser; @@ -112,9 +112,9 @@ enum ClientMessage { /// and a board that does not exist — or that the caller is not on, or that the /// caller is a `parent` and so barred from the whiteboard outright — is the /// same **404**, because a non-participant must not learn a board exists (the -/// rationale at `src/lib.rs`). Refusing the door is also what stops a parent -/// drawing: no socket, no `stroke` frame, and no per-stroke role read on the -/// hot path. +/// rationale at `src/lib.rs`). Refusing the door keeps a parent out; keeping +/// one out who was demoted *after* the upgrade is [`live_board`]'s job, which +/// every action already re-reads through. pub async fn board_ws( State(st): State, CurrentUser(user): CurrentUser, @@ -191,11 +191,24 @@ async fn room(mut socket: WebSocket, st: AppState, board: BoardId, user: UserId) type Step = Result<(), RoomClosed>; -/// The board as it stands right now, for a caller who must still be on it. -/// Every action re-reads through here: the roster, the lock and the epoch are -/// all live facts, and a frame this socket may never have seen is not an -/// authority over any of them. +/// The board as it stands right now, for a caller who must still be on it and +/// who must still hold a role the whiteboard is open to. Every action re-reads +/// through here: the role, the roster, the lock and the epoch are all live +/// facts, and a frame this socket may never have seen is not an authority over +/// any of them. +/// +/// The role is re-read for the same reason the roster is: the upgrade door's +/// bar (`board_ws`, mirroring [`super::boards`]'s `board_for`) is checked once, +/// nothing publishes a frame on a role change, and a demotion to `parent` — the +/// role barred from the whiteboard outright — must not leave an open socket +/// still committing strokes. async fn live_board(board: &BoardId, user: &UserId, db: &Database) -> Result { + let barred = User::read(user, db) + .await? + .is_none_or(|caller| !caller.get_role().at_least(Role::Student)); + if barred { + return Err(AppError::Forbidden("your role can no longer use boards")); + } let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?; if !board.is_participant(user) { return Err(AppError::Forbidden("you are no longer on this board")); @@ -268,6 +281,29 @@ async fn forward( mine.pop_front(); return Ok(()); } + // Authorize *before* the frame is handed over, never after. This used to + // run only for the `participants` frame, so a caller who lost the right to + // read — a roster removal that published nothing, or a demotion to + // `parent`, the role with no whiteboard access at all — was served every + // mark, clear and lock for up to [`BOARD_WS_TICK_SECS`] before the state + // tick noticed. Re-derived against the database, never read off the frame: + // the frame is the prompt, the row is the authority. + // + // ponytail: that is one `live_board` (two reads) per forwarded frame, paid + // by every listening socket, where the fan-out used to be read-free — a + // busy board now multiplies its database traffic by the size of the room. + // The drawer's own echo is dropped above without paying it, which is the + // only relief. Upgrade path: give [`crate::state::BoardHub`] a generation + // counter bumped by every role/roster write, and re-read only when this + // socket's copy is stale. + if let Err(err) = live_board(board, user, db).await { + let refusal = match err { + AppError::NotFound => json!({ "type": "deleted" }), + err => error_frame(&err, None), + }; + let _ = send(socket, refusal).await; + return Err(RoomClosed); + } socket .send(Message::Text(frame.to_string().into())) .await @@ -276,15 +312,6 @@ async fn forward( match kind.as_deref() { // The board ended. Nothing left to serve either way. Some("closed" | "deleted") => Err(RoomClosed), - // Re-derived against the database rather than read off the frame: the - // frame is the prompt, the row is the authority. - Some("participants") => match live_board(board, user, db).await { - Ok(_) => Ok(()), - Err(err) => { - let _ = send(socket, error_frame(&err, None)).await; - Err(RoomClosed) - } - }, _ => Ok(()), } } @@ -627,6 +654,68 @@ mod tests { ); } + /// The upgrade door's role bar has to hold for the *life* of the socket. + /// Nothing publishes a frame on a role change and the state tick used not + /// to look, so a student demoted to `parent` — the one role the whiteboard + /// is closed to outright — kept committing strokes on the socket they + /// already held. Driven at [`live_board`] because that is where every + /// stroke, clear, lock, join and tick funnels through; a real upgrade + /// cannot be driven from the `oneshot` harness the suites use. + #[tokio::test] + async fn a_demotion_bars_the_open_socket_from_every_write() { + use crate::domain::board::BoardTitle; + use crate::domain::user::{Password, Username}; + + let db = crate::database::init_mem().await.unwrap(); + let password = Password::try_new("secret1").unwrap(); + let creator = User::create( + Username::try_new("ogretmen").unwrap(), + password.hash_async().await.unwrap(), + &db, + ) + .await + .unwrap(); + let mate = User::create( + Username::try_new("ogrenci").unwrap(), + password.hash_async().await.unwrap(), + &db, + ) + .await + .unwrap(); + let mate_id = mate.get_id().clone(); + let board = Board::create( + creator.get_id(), + BoardTitle::try_new("Tahta").unwrap(), + vec![mate_id.clone()], + &db, + ) + .await + .unwrap(); + + // A student participant draws. + assert!( + live_board(board.get_id(), &mate_id, &db).await.is_ok(), + "a student on the board must pass" + ); + + // Demoted while the socket is open: refused from here on, and with the + // frame a denied write already uses — no new frame type. + mate.set_role(Role::Parent, &db).await.unwrap(); + let err = live_board(board.get_id(), &mate_id, &db).await.unwrap_err(); + assert!( + matches!(err, AppError::Forbidden(_)), + "a parent must be refused" + ); + assert_eq!(error_frame(&err, None)["code"], "forbidden"); + + // Nobody else is affected. + assert!( + live_board(board.get_id(), creator.get_id(), &db) + .await + .is_ok() + ); + } + /// Omitted stays omitted, never `null`. #[test] fn client_seq_rides_along_only_when_it_was_sent() { diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index fcec303..41c37a0 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -401,7 +401,8 @@ async fn send_message( return Ok(unavailable("no AI service is connected right now")); } - ChatbotMessage::append_user(thread.get_id(), user.get_id(), content, &st.db).await?; + let prompt = + ChatbotMessage::append_user(thread.get_id(), user.get_id(), content, &st.db).await?; let answer = ChatbotMessage::append_pending_assistant(thread.get_id(), user.get_id(), &st.db).await?; // Never fatal: both rows are already written, and failing here would strand @@ -420,9 +421,14 @@ async fn send_message( // timeout that guards every handler, and the POST must return now. The // settings snapshot goes with it, so the whole turn is judged by the policy // that was live when it was accepted. + // The prompt travels by id, not by write order: two POSTs on one thread + // interleave across the two creates above, and picking "the newest user row + // before this answer" out of the thread then answers the *other* request's + // question twice. tokio::spawn(answer_turn( bridge, st.db.clone(), + prompt.get_id().clone(), answer, settings.get_chatbot_history_turns().max(0) as usize, reply_cap, @@ -462,21 +468,21 @@ fn unavailable(message: &str) -> Response { async fn answer_turn( bridge: AiBridge, db: Database, + prompt_id: ChatbotMessageId, answer: ChatbotMessage, history_turns: usize, reply_cap: usize, ) { let answer_id = answer.get_id().clone(); let thread = answer.get_thread_id().clone(); - // The question this reserved row was written next to, read back from the - // thread — the prompt is already stored, so passing it along would only be - // a second copy of the same string. - let prompt = match answer.prompt_for(&db).await { + // This request's own question, read back by id — the text is already + // stored, so carrying the id rather than the string keeps the prompt and + // its answer paired however two POSTs on one thread interleave. + let prompt = match ChatbotMessage::prompt_of(&prompt_id, &db).await { Ok(Some(prompt)) => prompt, Ok(None) => { - // A reserved answer with no question before it. Only reachable if - // the user row was deleted out from under it; there is nothing to - // ask, so settle rather than re-claim it every reclaim horizon. + // The prompt row is gone — only reachable if the thread was deleted + // out from under this task. There is nothing to ask, so settle. tracing::warn!("chat answer {} has no prompt to send", answer_id.key()); let _ = ChatbotMessage::fail(&answer_id, "internal", &db).await; return; diff --git a/src/web/exams/review.rs b/src/web/exams/review.rs index 3296512..febec96 100644 --- a/src/web/exams/review.rs +++ b/src/web/exams/review.rs @@ -170,8 +170,15 @@ pub(crate) async fn student_marks_history( // marked this student (an ExamResult row proves it). /// The exam plus the per-student review gate the three self-review reads share. -/// 404 if the exam is missing or still a draft, 403 if review is off for it, and -/// 404 until the caller has a mark on it (nothing to review yet). +/// 404 if the exam is missing or still a draft, 403 if review is off for it, +/// 404 until the caller has a mark on it (nothing to review yet), and 409 while +/// the caller's latest sitting is still writable. +/// +/// That last check is the one a mark alone can't make: the mark lookup reads the +/// *latest* sitting's mark, so a mark left at seq 1 satisfies it forever — a +/// student who starts a retake would otherwise read the answer key and their own +/// correctness flags while still writing seq 2. Only `InProgress` is refused; +/// an expired or submitted sitting reviews normally. pub(crate) async fn reviewable_exam( st: &AppState, user: &User, @@ -189,12 +196,21 @@ pub(crate) async fn reviewable_exam( ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; + if let Some(attempt) = + ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db).await? + && attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress + { + return Err(AppError::Conflict( + "finish your sitting before reviewing this exam", + )); + } Ok(exam) } /// The caller's own sitting numbers at an exam — every seq that carries answers /// or a mark, ascending. Own-scoped review view; opens once the teacher enables -/// review and has marked the caller. +/// review and has marked the caller, and closes again (409) while the caller has +/// a sitting in progress. #[utoipa::path( get, path = "/{id}/review/attempts", @@ -206,6 +222,7 @@ pub(crate) async fn reviewable_exam( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), + (status = 409, description = "The caller's latest sitting is still in progress", body = ErrorResponse), ), )] pub(crate) async fn review_attempts( @@ -227,7 +244,8 @@ pub(crate) async fn review_attempts( /// The exam's full question list, `correct` choice ids included — the answer key /// the caller reviews their own sheet against. Same review gate as the other /// self-review reads; revealing `correct` is the point (the gate already proves -/// the caller was marked). Paged via `?limit=&offset=`. +/// the caller was marked and has no sitting still open). Paged via +/// `?limit=&offset=`. #[utoipa::path( get, path = "/{id}/review/questions", @@ -240,6 +258,7 @@ pub(crate) async fn review_attempts( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), + (status = 409, description = "The caller's latest sitting is still in progress", body = ErrorResponse), ), )] pub(crate) async fn review_questions( @@ -255,7 +274,8 @@ pub(crate) async fn review_questions( /// One of the caller's own sittings, judged — the `seq`th attempt's answers, /// drawing refs, correctness flags, and auto-score suggestion. Own-scoped -/// review view. +/// review view; 409 while the caller has a sitting in progress, so a retake +/// can't read its own correctness off an earlier seq. #[utoipa::path( get, path = "/{id}/review/attempts/{seq}/answers", @@ -270,6 +290,7 @@ pub(crate) async fn review_questions( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), + (status = 409, description = "The caller's latest sitting is still in progress", body = ErrorResponse), ), )] pub(crate) async fn review_attempt_answers( @@ -282,7 +303,8 @@ pub(crate) async fn review_attempt_answers( } /// The caller's own drawn-answer bytes for one of their sittings — the -/// seq-scoped, own-scoped mirror of the grader's drawing read. +/// seq-scoped, own-scoped mirror of the grader's drawing read. Same 409 while a +/// sitting is still open. #[utoipa::path( get, path = "/{id}/review/attempts/{seq}/answers/{qid}/image", @@ -298,6 +320,7 @@ pub(crate) async fn review_attempt_answers( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), (status = 404, description = "No such exam/question/drawing, a draft, or the caller has no mark on it", body = ErrorResponse), + (status = 409, description = "The caller's latest sitting is still in progress", body = ErrorResponse), ), )] pub(crate) async fn review_attempt_answer_image( diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 63e4236..49dfe7d 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -392,8 +392,8 @@ async fn list_roll_call( } /// Remove a user's roll-call row from a session. Same rights as marking: -/// session teacher or course manager for students, manager+ for the session -/// teacher's own row. +/// session teacher or course manager for students, manager+ for a staff row +/// (any target holding teacher or higher). #[utoipa::path( delete, path = "/{id}/attendance/{user}", @@ -406,7 +406,7 @@ async fn list_roll_call( responses( (status = 204, description = "Removed"), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the session teacher or a course manager; or removing the teacher's row without manager+", body = ErrorResponse), + (status = 403, description = "Not the session teacher or a course manager; or removing a staff row without manager+", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] @@ -422,9 +422,18 @@ async fn remove_roll_call( )); } let target = UserId::from_key(&target); - if session.is_teacher(&target) && !user.get_role().at_least(Role::Manager) { + // A staff row is management's to remove, keyed on the *target's live role* + // rather than on `is_teacher`: reassigning a session's teacher used to hand + // the incoming teacher — an ordinary one — the outgoing teacher's staff row + // to delete without the manager+ this guard exists to require. A target + // whose user row is gone can only be a student's stale row (marking checks + // the role at write time), so it stays the session teacher's to clear. + let staff_row = User::read(&target, &st.db) + .await? + .is_some_and(|target_user| target_user.get_role().at_least(Role::Teacher)); + if staff_row && !user.get_role().at_least(Role::Manager) { return Err(AppError::Forbidden( - "removing the session teacher's row requires manager role or higher", + "removing a staff roll-call row requires manager role or higher", )); } let removed = SessionAttendance::remove(session.get_id(), &target, &st.db).await?; diff --git a/src/web/users.rs b/src/web/users.rs index 508e5b2..829667b 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -2,16 +2,19 @@ use axum::Json; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; +use serde_json::json; use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; +use crate::domain::board::Board; use crate::domain::class_pump; use crate::domain::course::Course; use crate::domain::parent_link::ParentLink; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; +use crate::domain::registration::Registration; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -362,6 +365,10 @@ async fn update_user_preferences( /// Setting any non-`student` role also drops the user's course enrollments — /// only students enroll, so a promoted user leaves every roster. Demoting below /// `teacher` drops their course teaching assignments for the mirror reason. +/// Demoting to `parent` additionally gives back the seats they hold on +/// still-open event signup lists: a parent can no longer free them, and nobody +/// else may. Seats on lists that have already closed stay as they are — that +/// roster is history. #[utoipa::path( patch, path = "/{id}/role", @@ -406,6 +413,39 @@ async fn set_role( class_pump::sweep_non_student(&target, &st.db).await?; ParentLink::delete_where_student(&target, &st.db).await?; } + // Event signups are swept for a `parent` only — not for every non-student. + // Staff free their own seats by hand (`DELETE /events/{id}/register/{me}` + // allows the self case), so a promotion strands nothing and those signups + // are the teacher's to keep; a parent can reach no such door, and nobody + // else may free a non-student's seat, so theirs is the seat that would + // stay claimed forever. Frozen lists are left alone — see the sweep. + if role == Role::Parent { + Registration::sweep_for_parent(&target, &st.db).await?; + // Whiteboards: the role is barred from them outright, so a demoted user + // comes off every roster they are listed on — otherwise they stay a + // participant forever and their stale id 400s the creator's next roster + // PATCH (`resolve_participants` refuses a below-student id). Nothing is + // deleted, not even a board this empties: their own boards keep every + // stroke and stay readable to the rest of the room, they simply have a + // creator who can no longer use them. Each affected room is prompted + // with the same `participants` frame the roster PATCH publishes — the + // room re-reads the database before it acts on it. + for board in Board::drop_participant_everywhere(&target, &st.db).await? { + st.board_hub.publish( + board.get_id().key(), + json!({ + "type": "participants", + "creator": board.get_creator().key(), + "participants": board + .get_participants() + .iter() + .map(|user| user.key()) + .collect::>(), + }) + .to_string(), + ); + } + } if role != Role::Parent { ParentLink::delete_where_parent(&target, &st.db).await?; } diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index fab67e7..f7d2080 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -129,6 +129,10 @@ enum Behaviour { SlowEcho(Duration), /// Answer a chatbot turn with a fixed reply text (`{"text": ...}`). Reply(String), + /// Answer a chatbot turn with `cevap::`. The reply + /// carries the question inside it, so an answer stored against the wrong + /// prompt is visible in the row rather than merely suspected. + EchoPrompt, /// Answer with a handled failure. Fail { code: String, message: String }, /// Accept the stream and never answer, holding it open. @@ -184,6 +188,15 @@ fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc { + let asked = request.payload["message"] + .as_str() + .unwrap_or(""); + Some(Response::Ok { + id: request.id.clone(), + payload: json!({ "text": format!("cevap::{asked}") }), + }) + } Behaviour::Fail { code, message } => Some(Response::Err { id: request.id.clone(), code, @@ -1164,6 +1177,99 @@ async fn a_blank_chat_answer_fails_as_empty_reply() { assert_eq!(turn["error_code"], "empty_reply"); } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn two_racing_turns_on_one_thread_each_answer_their_own_prompt() { + // Two `POST .../messages` genuinely in flight on ONE thread. Their two + // creates interleave, so the rows land `userA, userB, asstA, asstB` — and + // any rule that resolves an answer's question by write order ("the newest + // user row before this answer") then hands *both* answers prompt B and + // never answers prompt A at all. The prompt travels by id precisely so + // that ordering cannot decide it. + // + // The service echoes the prompt it was given back inside its reply, so a + // crossed pair is legible in the stored row rather than inferred: the + // answer to "soru A" would read `cevap::soru B`. + // + // The interleave is scheduled, not forced — nothing in the handler can be + // held open between its two creates. So the round is replayed on a fresh + // user/thread until the row order proves it happened, and a run that never + // interleaves fails rather than passing vacuously. + const ROUNDS: usize = 60; + const ENOUGH: usize = 3; + let bridge = bridge_with_timeout(Duration::from_secs(20)).await; + let mut chatty = hello("tutor", &[AI_CHAT_CAPABILITY]); + chatty.max_concurrent = Some(8); + let _service = connect_service(&bridge, chatty, Behaviour::EchoPrompt).await; + await_workers(&bridge, 1).await; + let (app, _db) = chat_app(&bridge).await; + + let mut interleaved = 0usize; + for round in 0..ROUNDS { + let (cookie, thread) = chat_user(&app, &format!("ali{round}")).await; + let asks = ["soru A", "soru B"].map(|text| { + let (app, cookie, thread) = (app.clone(), cookie.clone(), thread.clone()); + tokio::spawn(async move { ask(&app, &cookie, &thread, text).await }) + }); + let mut mids = Vec::new(); + for handle in asks { + mids.push(handle.await.expect("the POST task did not panic")); + } + + // Both prompts appended before either answer row: the interleave the + // bug needed. Ids are minted in write order, so the list is that order. + let rows = thread_rows(&app, &cookie, &thread).await; + let roles: Vec = rows + .iter() + .map(|row| row["role"].as_str().expect("role").to_string()) + .collect(); + assert_eq!(roles.len(), 4, "two turns are four rows: {roles:?}"); + if roles == ["user", "user", "assistant", "assistant"] { + interleaved += 1; + } + + for (mid, asked) in mids.iter().zip(["soru A", "soru B"]) { + let turn = settled(&app, &cookie, &thread, mid).await; + assert_eq!(turn["status"], "complete", "round {round}: {turn}"); + assert_eq!( + turn["content"], + format!("cevap::{asked}"), + "round {round}, rows {roles:?}: this answer was paired with the other request's prompt", + ); + } + + // The other half of the bug: a prompt nothing ever answered left its + // reserved row spinning. Nothing in the thread may stay `pending`. + for row in thread_rows(&app, &cookie, &thread).await { + assert_ne!(row["status"], "pending", "round {round}: {row}"); + } + + // A few proven races are the point; the rest of the budget only exists + // for a machine that schedules them rarely. + if interleaved == ENOUGH { + break; + } + } + assert!( + interleaved > 0, + "the two POSTs never interleaved in {ROUNDS} rounds — this run proved nothing \ + about prompt pairing; widen the race rather than trusting the pass", + ); +} + +/// Every row of a thread, oldest first. +async fn thread_rows(app: &Router, cookie: &str, thread: &str) -> Vec { + let res = common::send( + app, + "GET", + &format!("/chatbot/threads/{thread}/messages"), + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + common::items(&res.body).clone() +} + // ------------------------------------------------------------- boot wiring -- // // `ai::start_bridge` is the seam between deployment config and the listener. diff --git a/tests/e2e.rs b/tests/e2e.rs index ea22df2..c67513e 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -2620,8 +2620,9 @@ async fn a_parent_cannot_enter_the_room_or_draw() { /// Test 7 — a participant dropped mid-session stops drawing. Twice over: once /// with the roster frame deliberately withheld (the socket's own gate is what -/// actually protects the board), and once through the frame the REST route -/// fans out. +/// actually protects the board), and once through the REST route's fan-out — +/// which the removed socket never receives, because the authorization in front +/// of every delivery refuses it first. #[tokio::test] async fn a_removed_participant_can_no_longer_draw() { let room = board_room_fixture().await; @@ -2683,13 +2684,27 @@ async fn a_removed_participant_can_no_longer_draw() { .await .unwrap(); assert_eq!(res.status(), StatusCode::OK); - let roster = board_frame_of_type(&mut veli, "participants").await; - assert_eq!(roster["participants"].as_array().unwrap().len(), 0); - // The room drops the socket rather than leaving it open and mute. + // The removed socket is *not* handed the new roster: authorization runs in + // front of every delivery now, so what reaches it is its own refusal and + // not one more fact about a board it is no longer on. + let refusal = board_frame_of_type(&mut veli, "error").await; + assert_eq!(refusal["code"], "forbidden", "{refusal}"); + assert_eq!( + refusal["message"], "you are no longer on this board", + "a roster removal must still explain itself — and say something other \ + than the role bar's refusal, or a client cannot tell them apart" + ); + // And the room drops the socket rather than leaving it open and mute. loop { match ws_next_frame(&mut veli).await { None => break, - Some(frame) => assert_ne!(frame["type"], "saved", "a dropped socket must not save"), + Some(frame) => { + assert_ne!(frame["type"], "saved", "a dropped socket must not save"); + assert_ne!( + frame["type"], "participants", + "a removed socket is told it is out, never who is in" + ); + } } } } @@ -3146,3 +3161,62 @@ async fn a_class_seats_its_roster_and_gives_the_seat_back() { .unwrap(); assert_eq!(roster["total"], 0, "and off the teacher's roster: {roster}"); } + +/// The role bar has to close READS, not only writes. `forward` used to hand the +/// frame to the socket first and authorize afterwards — and only on a +/// `participants` frame or the 15-second state tick — so a participant demoted +/// to `parent`, the role with no whiteboard access at all, kept being served +/// every mark drawn on a live canvas until the tick caught up. Driven over a +/// real socket, because the leak lives in the fan-out and nowhere else. +/// +/// The role is moved straight in the database, which is both the school's +/// documented bootstrap and the harshest case: no `participants` frame is +/// published to prompt the room, so only the authorization in front of the send +/// can refuse it. +#[tokio::test] +async fn a_demoted_participant_stops_reading_the_canvas_at_once() { + let room = board_room_fixture().await; + let (base, board) = (&room.base, &room.board_id); + let mut ali = board_open(base, board, Some(&room.creator_cookie)) + .await + .expect("creator upgrade"); + let mut veli = board_open(base, board, Some(&room.veli_cookie)) + .await + .expect("participant upgrade"); + board_join(&mut veli, None, None).await; + + // Still a student: the fan-out reaches them. + board_draw(&mut ali, "{\"p\":[1,2]}").await; + let fanned = board_frame_of_type(&mut veli, "stroke").await; + assert_eq!(fanned["payload"], "{\"p\":[1,2]}"); + + promote(&room.db, "veli", "parent").await; + board_draw(&mut ali, "{\"p\":[3,4]}").await; + + // The next thing that socket hears is its refusal, and the room ends. It + // must never be the mark: `parent` has no whiteboard access whatsoever. + let mut refused = false; + while let Some(frame) = ws_next_frame(&mut veli).await { + assert_ne!( + frame["type"], "stroke", + "a demoted participant read live canvas content: {frame}" + ); + if frame["type"] == "error" { + assert_eq!(frame["code"], "forbidden", "{frame}"); + // Its own words, distinct from a roster removal's: the client can + // tell "you were taken off this board" from "your account may no + // longer use boards at all". + assert_eq!(frame["message"], "your role can no longer use boards"); + refused = true; + } + } + assert!(refused, "the socket must be told why it was dropped"); + + // Nothing was destroyed by the refusal, and the room carries on for the + // people still entitled to it. + assert_eq!( + stored_payloads(&room.db, board, 0).await, + vec!["{\"p\":[1,2]}".to_string(), "{\"p\":[3,4]}".to_string()], + ); + board_draw(&mut ali, "{\"p\":[5,6]}").await; +} diff --git a/tests/integration.rs b/tests/integration.rs index 02bc0b3..50d82e5 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -16741,6 +16741,26 @@ async fn propose( .await } +/// Accept the standing counter-proposal on `id`, naming the window the +/// requester read — the accept pins *which* proposal it answers, so the body +/// is required (a bodyless PATCH is a `415`, not a `400`). +async fn accept_reschedule( + app: &axum::Router, + cookie: &str, + id: &str, + starts_at: i64, + ends_at: i64, +) -> common::Res { + send( + app, + "PATCH", + &format!("/appointments/{id}/reschedule/accept"), + Some(cookie), + Some(json!({ "proposed_starts_at": starts_at, "proposed_ends_at": ends_at })), + ) + .await +} + #[tokio::test] async fn appointment_book_and_approve_holds_the_slot() { let (app, db) = app_and_db().await; @@ -16879,7 +16899,14 @@ async fn approval_refuses_a_teacher_double_booking() { ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let res = decide(&app, &ayse, &two, "reschedule/accept").await; + let res = accept_reschedule( + &app, + &ayse, + &two, + now + HOUR_MS + 600_000, + now + 2 * HOUR_MS + 600_000, + ) + .await; assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); // Refused, not half-applied: it is still pending and still decidable. let res = decide(&app, &ali, &two, "reject").await; @@ -16965,13 +16992,14 @@ async fn reschedule_returns_to_pending_until_the_requester_accepts() { // The effective window already reads as the proposed one. assert_eq!(res.body["starts_at"], now + 3 * HOUR_MS); - // Only the requester may answer it. - let res = decide(&app, &ayse, &booking, "reschedule/accept").await; + // Only the requester may answer it. A valid pin still 403s for the wrong + // caller: `ensure_requester` runs ahead of the domain either way. + let res = accept_reschedule(&app, &ayse, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); - let res = decide(&app, &ali, &booking, "reschedule/accept").await; + let res = accept_reschedule(&app, &ali, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); - let res = decide(&app, &veli, &booking, "reschedule/accept").await; + let res = accept_reschedule(&app, &veli, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(res.body["status"], "approved"); assert_eq!(res.body["starts_at"], now + 3 * HOUR_MS); @@ -17007,7 +17035,7 @@ async fn a_started_proposal_is_refused() { .status, StatusCode::OK ); - let res = decide(&app, &veli, &booking, "reschedule/accept").await; + let res = accept_reschedule(&app, &veli, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(res.body["status"], "approved"); } @@ -17115,7 +17143,7 @@ async fn accepting_a_reschedule_re_runs_the_overlap_guard() { .status, StatusCode::OK ); - let res = decide(&app, &veli, &booking, "reschedule/accept").await; + let res = accept_reschedule(&app, &veli, &booking, now + 5 * HOUR_MS, now + 6 * HOUR_MS).await; assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); assert_eq!( send(&app, "GET", "/appointments", Some(&veli), None) @@ -18000,6 +18028,15 @@ async fn self_review_returns_own_seqs_and_per_sitting_answers() { Some(json!({ "mark": 90, "user_id": student_id })), ) .await; + // Review refuses while the sitting is still writable, so submit it first. + send( + &app, + "POST", + &format!("/exams/{exam}/attempt/finish"), + Some(&student), + None, + ) + .await; // Own seqs, ascending. let res = send( @@ -18118,6 +18155,15 @@ async fn self_review_is_own_scoped_between_students() { Some(json!({ "mark": mark, "user_id": id })), ) .await; + // Review refuses while the sitting is still writable. + send( + &app, + "POST", + &format!("/exams/{exam}/attempt/finish"), + Some(who), + None, + ) + .await; } // Alice's token sees only Alice's data — one seq, her own answer. diff --git a/tests/persistence.rs b/tests/persistence.rs index db0f177..fe5d87b 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -684,7 +684,10 @@ async fn appointments_survive_remigration() { "PATCH", &format!("/appointments/{appointment}/reschedule/accept"), Some(&student), - None, + Some(json!({ + "proposed_starts_at": PROPOSED_START, + "proposed_ends_at": PROPOSED_END, + })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index 9884b81..f3a8542 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -224,6 +224,38 @@ async fn only_the_rightmost_forwarded_hop_counts() { ); } +/// A proxy that appends its hop as a *separate* `X-Forwarded-For` line leaves +/// the client's forged line first. Billing that first line would mint a bucket +/// per attempt and the credential tier would never fire, so the last line — +/// the only one the client cannot write — is what keys the request. +#[tokio::test] +async fn only_the_last_forwarded_header_line_counts() { + let app = app_with(auth_only(2)).await; + + let attempt = |forged: &'static str| { + let app = app.clone(); + async move { + let request = Request::builder() + .method("POST") + .uri("/auth/login") + .header("x-forwarded-for", forged) + .header("x-forwarded-for", "9.9.9.9") + .header("content-type", "application/json") + .body(Body::from(bad_login().unwrap().to_string())) + .unwrap(); + app.oneshot(request).await.unwrap().status() + } + }; + + assert_eq!(attempt("1.1.1.1").await, StatusCode::UNAUTHORIZED); + assert_eq!(attempt("2.2.2.2").await, StatusCode::UNAUTHORIZED); + assert_eq!( + attempt("3.3.3.3").await, + StatusCode::TOO_MANY_REQUESTS, + "a forged first line must not mint a fresh bucket per attempt" + ); +} + #[tokio::test] async fn ipv6_clients_are_keyed_too() { let app = app_with(auth_only(1)).await; diff --git a/tests/regress_appointments.rs b/tests/regress_appointments.rs new file mode 100644 index 0000000..1c5b639 --- /dev/null +++ b/tests/regress_appointments.rs @@ -0,0 +1,292 @@ +//! Regressions for two defects found in the 2026-08-02 sweep: +//! +//! - a teacher could confirm their **own** counter-proposal through +//! `PATCH /appointments/{id}/approve`, moving a meeting the requester had +//! already agreed to onto a time only the teacher ever named; +//! - a chatbot answer resolved its question by *write order*, so two POSTs on +//! one thread interleaving across their two row creates made both answers +//! reply to the second prompt and left the first unanswered. +//! +//! The second is a true race, so the reachable half is driven: the row order +//! the interleave produces is written straight into the store, and the +//! assertion is on what the store then pairs. + +mod common; + +use axum::http::StatusCode; +use common::{app_and_db, id_of, login, login_as, me_id, send}; +use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage}; +use hezarfen_backend::domain::chatbot_thread::ChatbotThread; +use hezarfen_backend::domain::timestamp::Timestamp; +use hezarfen_backend::domain::user::UserId; +use serde_json::json; + +const HOUR_MS: i64 = 3_600_000; + +/// `PATCH /appointments/{id}/{action}`, bodyless. +async fn decide(app: &axum::Router, cookie: &str, id: &str, action: &str) -> common::Res { + send( + app, + "PATCH", + &format!("/appointments/{id}/{action}"), + Some(cookie), + None, + ) + .await +} + +/// `PATCH /appointments/{id}/reschedule/accept`, naming the proposal accepted. +async fn accept( + app: &axum::Router, + cookie: &str, + id: &str, + starts_at: i64, + ends_at: i64, +) -> common::Res { + send( + app, + "PATCH", + &format!("/appointments/{id}/reschedule/accept"), + Some(cookie), + Some(json!({ "proposed_starts_at": starts_at, "proposed_ends_at": ends_at })), + ) + .await +} + +/// `PATCH /appointments/{id}/reschedule` — the teacher counter-proposes. +async fn propose( + app: &axum::Router, + cookie: &str, + id: &str, + starts_at: i64, + ends_at: i64, +) -> common::Res { + send( + app, + "PATCH", + &format!("/appointments/{id}/reschedule"), + Some(cookie), + Some(json!({ "starts_at": starts_at, "ends_at": ends_at })), + ) + .await +} + +/// Publish one slot as `cookie` and book it as `requester`; returns the +/// booking id. +async fn booked( + app: &axum::Router, + teacher: &str, + requester: &str, + starts_at: i64, + ends_at: i64, +) -> String { + let res = send( + app, + "POST", + "/appointments/slots", + Some(teacher), + Some(json!({ "starts_at": starts_at, "ends_at": ends_at })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "publish: {}", res.body); + let slot = res.body[0]["id"].as_str().expect("slot id").to_string(); + + let res = send( + app, + "POST", + "/appointments", + Some(requester), + Some(json!({ "slot": slot, "reason": "görüşmek istiyorum" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "book: {}", res.body); + id_of(&res.body) +} + +/// A confirmed meeting may only move if the person who asked for it says so. +/// The teacher's own approval used to be enough: `reschedule` puts the booking +/// back to `pending` with the proposal on the row, and `approve` then read the +/// *effective* window — the proposal's — without ever asking whether one was +/// standing. That committed the requester to a time they never saw, straight +/// past the requester-only `reschedule/accept` gate. +#[tokio::test] +async fn a_teacher_cannot_confirm_their_own_counter_proposal() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let veli = login(&app, "veli").await; + let now = Timestamp::now().as_millis(); + let (slot_starts_at, slot_ends_at) = (now + HOUR_MS, now + 2 * HOUR_MS); + let (moved_starts_at, moved_ends_at) = (now + 3 * HOUR_MS, now + 4 * HOUR_MS); + let booking = booked(&app, &ali, &veli, slot_starts_at, slot_ends_at).await; + + // Agreed: the meeting is committed at the slot's own window. + let res = decide(&app, &ali, &booking, "approve").await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "approved"); + assert_eq!(res.body["starts_at"], slot_starts_at); + + // The teacher counter-proposes: back to pending, nothing committed yet. + let res = propose(&app, &ali, &booking, moved_starts_at, moved_ends_at).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "pending"); + assert_eq!(res.body["proposed_starts_at"], moved_starts_at); + + // And now approves their own proposal. This is the defect: it used to + // answer 200 and commit the meeting at the moved time. + let res = decide(&app, &ali, &booking, "approve").await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert!( + res.body["error"] + .as_str() + .expect("error text") + .contains("counter-proposal"), + "{}", + res.body + ); + + // Refused, not half-applied: still pending, the proposal still standing and + // still unanswered. + let res = send(&app, "GET", "/appointments", Some(&veli), None).await; + let row = &common::items(&res.body)[0]; + assert_eq!(row["id"], booking.as_str()); + assert_eq!(row["status"], "pending"); + assert_eq!(row["proposed_starts_at"], moved_starts_at); + assert!(row["decided_by"].is_null(), "nothing was decided"); + + // The requester's own accept is still the way through, and it commits the + // proposed time — the gate refuses the teacher, not the move. + let res = accept(&app, &veli, &booking, moved_starts_at, moved_ends_at).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "approved"); + assert_eq!(res.body["starts_at"], moved_starts_at); + assert_eq!(res.body["ends_at"], moved_ends_at); +} + +/// The other half of the same invariant: the requester must be committed to the +/// time *they saw*. `propose` takes no lock and the requester answers minutes +/// later, so a teacher who re-proposes in between used to choose which window +/// the accept landed on — the click said 10:00 and the row said 23:00. The +/// accept names the proposal it answers, so a superseded one is refused. +#[tokio::test] +async fn accepting_a_superseded_proposal_is_refused() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let veli = login(&app, "veli").await; + let now = Timestamp::now().as_millis(); + let booking = booked(&app, &ali, &veli, now + HOUR_MS, now + 2 * HOUR_MS).await; + + // The proposal the requester reads and agrees to. + let (seen_starts_at, seen_ends_at) = (now + 3 * HOUR_MS, now + 4 * HOUR_MS); + let res = propose(&app, &ali, &booking, seen_starts_at, seen_ends_at).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send(&app, "GET", "/appointments", Some(&veli), None).await; + assert_eq!( + common::items(&res.body)[0]["proposed_starts_at"], + seen_starts_at + ); + + // The teacher swaps it out while the requester is deciding. + let (swapped_starts_at, swapped_ends_at) = (now + 23 * HOUR_MS, now + 24 * HOUR_MS); + let res = propose(&app, &ali, &booking, swapped_starts_at, swapped_ends_at).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The click, carrying what they saw. It used to approve at the swapped time. + let res = accept(&app, &veli, &booking, seen_starts_at, seen_ends_at).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert!( + res.body["error"] + .as_str() + .expect("error text") + .contains("proposed time has changed"), + "{}", + res.body + ); + + // Nothing was committed, at either time. + let res = send(&app, "GET", "/appointments", Some(&veli), None).await; + let row = &common::items(&res.body)[0]; + assert_eq!(row["status"], "pending"); + assert_eq!(row["proposed_starts_at"], swapped_starts_at); + assert!(row["decided_by"].is_null()); + + // Re-reading and accepting what actually stands still works — the pin + // refuses a stale answer, not the move. + let res = accept(&app, &veli, &booking, swapped_starts_at, swapped_ends_at).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "approved"); + assert_eq!(res.body["starts_at"], swapped_starts_at); + assert_eq!(res.body["ends_at"], swapped_ends_at); +} + +/// An answer belongs to the question of *its own* POST. Two POSTs on one thread +/// interleave across `append_user` / `append_pending_assistant`, so the rows +/// land `userA, userB, asstA, asstB` — and "the newest user row written before +/// this answer", the rule that used to pair them, resolves asstA to prompt B. +/// Both answers then reply to B and A is never answered. The pairing is carried +/// by id now, so write order cannot decide it. +#[tokio::test] +async fn an_answer_resolves_its_own_prompt_across_an_interleave() { + let (app, db) = app_and_db().await; + let cookie = login(&app, "veli").await; + let owner = UserId::from_key(&me_id(&app, &cookie).await); + let thread = ChatbotThread::create_capped(&owner, None, &db) + .await + .expect("create thread"); + let id = thread.get_id().clone(); + let say = |text: &str| ChatContent::try_new(text).expect("content"); + + // Exactly the order the interleave produces. + let prompt_a = ChatbotMessage::append_user(&id, &owner, say("soru A"), &db) + .await + .expect("prompt A"); + let prompt_b = ChatbotMessage::append_user(&id, &owner, say("soru B"), &db) + .await + .expect("prompt B"); + let answer_a = ChatbotMessage::append_pending_assistant(&id, &owner, &db) + .await + .expect("answer A"); + let answer_b = ChatbotMessage::append_pending_assistant(&id, &owner, &db) + .await + .expect("answer B"); + + // The interleave is real: by write order the newest user row before *both* + // answers is B, which is what used to be handed to both of them. + let (stored, _) = ChatbotMessage::list_for_thread(&id, None, 0, &db) + .await + .expect("thread"); + let texts: Vec<&str> = stored + .iter() + .map(|message| message.get_content().as_str()) + .collect(); + assert_eq!(texts, ["soru A", "soru B", "", ""], "the racing row order"); + + // Identity decides instead, so each answer keeps its own question — the id + // the answering task carries is the prompt of its own POST. + let carried_a = ChatbotMessage::prompt_of(prompt_a.get_id(), &db) + .await + .expect("read A") + .expect("prompt A exists"); + let carried_b = ChatbotMessage::prompt_of(prompt_b.get_id(), &db) + .await + .expect("read B") + .expect("prompt B exists"); + assert_eq!(carried_a.get_content().as_str(), "soru A"); + assert_eq!(carried_b.get_content().as_str(), "soru B"); + + // And the answers each settle with the reply to their own question — the + // stored state, not just what a lookup returned. + ChatbotMessage::complete(answer_a.get_id(), say("cevap A"), false, &db) + .await + .expect("settle A"); + ChatbotMessage::complete(answer_b.get_id(), say("cevap B"), false, &db) + .await + .expect("settle B"); + let (stored, _) = ChatbotMessage::list_for_thread(&id, None, 0, &db) + .await + .expect("thread"); + let texts: Vec<&str> = stored + .iter() + .map(|message| message.get_content().as_str()) + .collect(); + assert_eq!(texts, ["soru A", "soru B", "cevap A", "cevap B"]); +} diff --git a/tests/regress_attendance.rs b/tests/regress_attendance.rs new file mode 100644 index 0000000..e08d497 --- /dev/null +++ b/tests/regress_attendance.rs @@ -0,0 +1,204 @@ +//! Regressions for the two roll-call defects found in the 2026-08-02 sweep: +//! the staff-row gate keyed on the session's *current* teacher, and the +//! roll-call write that could land on an already-deleted session. +//! +//! The orphan half is a true race, so it is driven at the domain layer instead +//! of over HTTP: the handler's session snapshot is taken first, the session is +//! then deleted, and the mark is sent with that stale snapshot — exactly the +//! state the racing request holds. The assertion is on what the store holds +//! afterwards, never on the call's own answer. + +mod common; + +use axum::http::StatusCode; +use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send}; +use hezarfen_backend::domain::attendance::AttendanceStatus; +use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId}; +use hezarfen_backend::domain::session_attendance::SessionAttendance; +use hezarfen_backend::domain::settings::Settings; +use hezarfen_backend::domain::timestamp::Timestamp; +use hezarfen_backend::domain::user::UserId; +use hezarfen_backend::error::AppError; +use serde_json::json; + +fn soon() -> i64 { + Timestamp::now().as_millis() + 3_600_000 +} + +/// A staff roll-call row is management's to write *and* to remove. The removal +/// gate used to ask "is the target the session's teacher?", which a teacher +/// reassignment falsifies: once the session moved to T2, the row T1 holds is no +/// longer the *current* teacher's, so T2 — an ordinary teacher — could delete +/// the staff row the manager+ requirement exists to protect. The gate now asks +/// the target's live role instead, which a reassignment cannot change. +#[tokio::test] +async fn reassigning_the_teacher_does_not_unlock_the_old_teachers_staff_row() { + let (app, db) = app_and_db().await; + let boss = login_as(&app, &db, "mudur", "manager").await; + let t1 = login_as(&app, &db, "hoca", "teacher").await; + let t2 = login_as(&app, &db, "yeni", "teacher").await; + let ali = login(&app, "ali").await; + let t1_id = me_id(&app, &t1).await; + let t2_id = me_id(&app, &t2).await; + let ali_id = me_id(&app, &ali).await; + + let course = create_course(&app, &boss, "algebra").await; + enroll(&app, &boss, &course, &ali_id).await; + let res = send( + &app, + "POST", + &format!("/courses/{course}/sessions"), + Some(&boss), + Some(json!({ "starts_at": soon(), "teacher_id": t1_id })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let session = common::id_of(&res.body); + let mark_uri = format!("/sessions/{session}/attendance"); + + // Management records the staff presence of the then-teacher. + let res = send( + &app, + "POST", + &mark_uri, + Some(&boss), + Some(json!({ "status": "present", "user_id": t1_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The lesson is handed to another ordinary teacher. + let res = send( + &app, + "PATCH", + &format!("/sessions/{session}"), + Some(&boss), + Some(json!({ "teacher_id": t2_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Who may not then wipe the outgoing teacher's staff row. + let res = send( + &app, + "DELETE", + &format!("{mark_uri}/{t1_id}"), + Some(&t2), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // The row is still there, and a manager still clears it. + let rows = SessionAttendance::list_for_user(&UserId::from_key(&t1_id), &db) + .await + .unwrap(); + assert_eq!(rows.len(), 1, "the staff row survived the refused delete"); + let res = send( + &app, + "DELETE", + &format!("{mark_uri}/{t1_id}"), + Some(&boss), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + // And the ordinary case is untouched: the session's teacher clears a + // student's row without management. + let res = send( + &app, + "POST", + &mark_uri, + Some(&t2), + Some(json!({ "status": "present", "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("{mark_uri}/{ali_id}"), + Some(&t2), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); +} + +/// No attendance row may outlive its session. Marking held a session snapshot +/// read four round trips before the write, so a delete landing in that gap left +/// a roll-call row pointing at a session that no longer existed — and that row +/// was unremovable, its only delete route 404ing on the vanished session while +/// `GET /attendance/{user}` counted it forever. The existence gate now rides +/// inside the write itself. +#[tokio::test] +async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { + let (app, db) = app_and_db().await; + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + let hoca_id = me_id(&app, &hoca).await; + let ali_ref = UserId::from_key(&ali_id); + + let course = create_course(&app, &hoca, "algebra").await; + enroll(&app, &hoca, &course, &ali_id).await; + let session = create_session(&app, &hoca, &course, soon()).await; + let res = send( + &app, + "POST", + &format!("/sessions/{session}/attendance"), + Some(&hoca), + Some(json!({ "status": "present", "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The snapshot the racing request is holding, taken while the session lives. + let snapshot = CourseSession::read(&CourseSessionId::from_key(&session), &db) + .await + .unwrap() + .expect("session exists"); + + // The delete lands first — and its cascade still takes the existing row. + let res = send( + &app, + "DELETE", + &format!("/sessions/{session}"), + Some(&hoca), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + assert!( + SessionAttendance::list_for_user(&ali_ref, &db) + .await + .unwrap() + .is_empty(), + "the delete cascade removed the roll-call row" + ); + + // Then the mark arrives, still believing in its snapshot. + let school = Settings::load(&db).await.unwrap(); + let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap(); + let marked = SessionAttendance::mark( + &snapshot, + &ali_ref, + status, + &UserId::from_key(&hoca_id), + &db, + ) + .await; + assert!( + matches!(marked, Err(AppError::NotFound)), + "a mark on a deleted session is a 404" + ); + // The stored state is the assertion — the return value is not trusted. + assert!( + SessionAttendance::list_for_user(&ali_ref, &db) + .await + .unwrap() + .is_empty(), + "no orphan row was written" + ); +} diff --git a/tests/regress_review.rs b/tests/regress_review.rs new file mode 100644 index 0000000..0c5122e --- /dev/null +++ b/tests/regress_review.rs @@ -0,0 +1,111 @@ +//! Regression for the self-review answer-key leak found in the 2026-08-02 +//! sweep: the review gate proved "the caller has a mark" by reading their +//! *latest* mark, so a mark left at seq 1 satisfied it forever. A student who +//! started a retake could read the answer key — and their own `is_correct` / +//! `auto_score` flags — on the sheet they were still writing. +//! +//! The gate now refuses (409) while the caller's latest sitting is in progress. +//! Deterministic: the retake is started over HTTP, no clock or race involved. + +mod common; + +use axum::http::StatusCode; +use common::{ + app_and_db, create_course, create_exam_with, create_subject, enroll, id_of, login, login_as, + me_id, send, +}; +use serde_json::json; + +/// A student mid-retake must not be able to read the answer key or the +/// correctness flags on any of their own sittings — but the same reads must +/// still work before the retake starts and again once it is submitted. +#[tokio::test] +async fn a_retake_in_progress_closes_the_students_own_review_reads() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "rev_race_t", "teacher").await; + let student = login(&app, "rev_race_s").await; + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "biology").await; + let subject = create_subject(&app, &teacher, &course, "cells").await; + enroll(&app, &teacher, &course, &student_id).await; + let res = create_exam_with( + &app, + &teacher, + &course, + json!({ + "title": "cell quiz", "kind": "quiz", "mode": "open", + "max_attempts": 2, "allow_review": true, + }), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let exam = id_of(&res.body); + + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions"), + Some(&teacher), + Some(json!({ + "text": "Name an organelle.", "kind": "text", "points": 10, + "subject_id": subject, + })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let question = id_of(&res.body); + + let attempt_uri = format!("/exams/{exam}/attempt"); + let finish_uri = format!("/exams/{exam}/attempt/finish"); + let key_uri = format!("/exams/{exam}/review/questions"); + let sheet_uri = format!("/exams/{exam}/review/attempts/1/answers"); + + // Seq 1: sit, answer, grade, finish. + let res = send(&app, "POST", &attempt_uri, Some(&student), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + send( + &app, + "POST", + &format!("/exams/{exam}/attempt/answers"), + Some(&student), + Some(json!({ "question_id": question, "text": "mitochondria" })), + ) + .await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(json!({ "mark": 40, "user_id": student_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send(&app, "POST", &finish_uri, Some(&student), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Post-finish review: unchanged, this is the behaviour being preserved. + let res = send(&app, "GET", &key_uri, Some(&student), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["items"][0]["id"], question); + + // Seq 2: the retake starts and is still writable. + let res = send(&app, "POST", &attempt_uri, Some(&student), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["attempt"], 2, "{}", res.body); + assert_eq!(res.body["status"], "in_progress", "{}", res.body); + + // The leak: neither the answer key nor a judged sheet may be readable now. + for uri in [&key_uri, &sheet_uri] { + let res = send(&app, "GET", uri, Some(&student), None).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{uri}: {}", res.body); + } + + // Submitting the retake reopens review. + let res = send(&app, "POST", &finish_uri, Some(&student), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + for uri in [&key_uri, &sheet_uri] { + let res = send(&app, "GET", uri, Some(&student), None).await; + assert_eq!(res.status, StatusCode::OK, "{uri}: {}", res.body); + } +} diff --git a/tests/regress_roles.rs b/tests/regress_roles.rs new file mode 100644 index 0000000..cf939cb --- /dev/null +++ b/tests/regress_roles.rs @@ -0,0 +1,478 @@ +//! Regressions for the role sweep and the parent-delete cascades found in the +//! 2026-08-02 sweep: an event seat a demotion left claimed forever, and the +//! two-query deletes that could orphan a child row. +//! +//! Every assertion re-reads the *store*. The in-memory engine forges wins under +//! concurrency (src/domain/cap.rs), so nothing below is judged on a response +//! body or asked who won a race — the cascade tests drive the reachable half +//! and pin what the store holds once the transaction is done. + +mod common; + +use axum::http::StatusCode; +use common::{app_and_db, id_of, login, login_as, me_id, send}; +use hezarfen_backend::database::Database; +use serde_json::json; + +/// One counter, re-read out of the store — never off a response body. +async fn counter(sql: &str, db: &Database) -> i64 { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) +} + +/// How many rows `sql` selects ids for. +async fn rows(sql: &str, db: &Database) -> i64 { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result + .take::>(0) + .unwrap() + .len() as i64 +} + +/// Put `user` on `event`'s signup list as `cookie`. +async fn seat(app: &axum::Router, cookie: &str, event: &str, user: &str) -> common::Res { + send( + app, + "POST", + &format!("/events/{event}/register"), + Some(cookie), + Some(json!({ "user_id": user })), + ) + .await +} + +/// A one-seat signup list. +async fn capped_event(app: &axum::Router, teacher: &str, capacity: Option) -> String { + let audience = match capacity { + Some(capacity) => json!({ "kind": "registration", "capacity": capacity }), + None => json!({ "kind": "registration" }), + }; + let res = send( + app, + "POST", + "/events", + Some(teacher), + Some(json!({ "title": "Gezi", "audience": audience })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + id_of(&res.body) +} + +/// Free `user`'s seat on `event` as `cookie`. +async fn free_seat(app: &axum::Router, cookie: &str, event: &str, user: &str) -> common::Res { + send( + app, + "DELETE", + &format!("/events/{event}/register/{user}"), + Some(cookie), + None, + ) + .await +} + +/// Push an event's start into the past, which is how its signup list freezes. +/// The API refuses to *schedule* one there (60s grace), so the row is aged in +/// the store — the state a real event reaches by the clock simply running on. +async fn age_event(event: &str, db: &Database) { + db.query("UPDATE type::record('event', $key) SET starts_at = 1") + .bind(("key", event.to_string())) + .await + .unwrap() + .check() + .unwrap(); +} + +/// The role sweep dropped enrollments, class memberships, parent links and +/// course staffing — but not signups. A `parent`'s seat is the one that is +/// genuinely *unfreeable*: they cannot reach `DELETE /events/{id}/register/…` +/// (teacher+ only) and no one else may free a non-student's seat, so a +/// capacity-1 event answered "full" forever and the stale holder stayed on the +/// roster (a registration audience resolves on the row's mere existence). +#[tokio::test] +async fn a_demotion_frees_the_event_seat_nothing_else_could_free() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen", "teacher").await; + let admin = login_as(&app, &db, "yonetici", "admin").await; + let ali = login(&app, "ali").await; + let veli = login(&app, "veli").await; + let ali_id = me_id(&app, &ali).await; + let veli_id = me_id(&app, &veli).await; + + let event = capped_event(&app, &teacher, Some(1)).await; + let res = seat(&app, &teacher, &event, &ali_id).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + 1 + ); + + let res = send( + &app, + "PATCH", + &format!("/users/{ali_id}/role"), + Some(&admin), + Some(json!({ "role": "parent" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The row goes and the seat comes back with it — one is worthless without + // the other. + assert_eq!( + rows("SELECT VALUE id FROM registration", &db).await, + 0, + "a non-student may hold no signup row" + ); + assert_eq!( + counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + 0, + "the seat must be handed back, or the event is full forever" + ); + + // And the freed seat is really usable. + let res = seat(&app, &teacher, &event, &veli_id).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/events/{event}/roster"), + Some(&teacher), + None, + ) + .await; + assert_eq!(common::total(&res.body), 1, "{}", res.body); +} + +/// The mirror ruling: a *promotion* strands nothing, because staff free their +/// own seats by hand. Sweeping there destroyed a signup a teacher is entitled +/// to keep — and irreversibly, since re-demoting restores nothing. The seat +/// stays, and the promoted teacher can still give it back themselves. +#[tokio::test] +async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen", "teacher").await; + let admin = login_as(&app, &db, "yonetici", "admin").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + + let event = capped_event(&app, &teacher, Some(1)).await; + assert_eq!( + seat(&app, &teacher, &event, &ali_id).await.status, + StatusCode::OK + ); + + let res = send( + &app, + "PATCH", + &format!("/users/{ali_id}/role"), + Some(&admin), + Some(json!({ "role": "teacher" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + assert_eq!( + rows("SELECT VALUE id FROM registration", &db).await, + 1, + "a promotion must not destroy a signup its holder can still free" + ); + assert_eq!( + counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + 1, + "…and the seat it holds stays claimed with it" + ); + + // Which is the whole justification: the seat is still theirs to free. + let promoted = send( + &app, + "POST", + "/auth/login", + None, + Some(json!({ + "username": "ali", "password": "secret1" + })), + ) + .await + .cookie + .expect("re-login"); + let res = free_seat(&app, &promoted, &event, &ali_id).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + assert_eq!(rows("SELECT VALUE id FROM registration", &db).await, 0); + assert_eq!( + counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + 0 + ); +} + +/// A signup list freezes when its event starts, and from then on it is +/// historical record: `register` and `unregister` both answer 409. The sweep +/// obeys the same freeze — rewriting a closed roster behind its back is +/// irrecoverable, since re-registering is refused too. +#[tokio::test] +async fn a_demotion_leaves_a_frozen_signup_list_exactly_as_it_stands() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen", "teacher").await; + let admin = login_as(&app, &db, "yonetici", "admin").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + + let event = capped_event(&app, &teacher, Some(1)).await; + assert_eq!( + seat(&app, &teacher, &event, &ali_id).await.status, + StatusCode::OK + ); + age_event(&event, &db).await; + + // The freeze bites for the route… + let res = free_seat(&app, &teacher, &event, &ali_id).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // …so it must bite for the sweep as well. + let res = send( + &app, + "PATCH", + &format!("/users/{ali_id}/role"), + Some(&admin), + Some(json!({ "role": "parent" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + assert_eq!( + rows("SELECT VALUE id FROM registration", &db).await, + 1, + "a closed roster must not be rewritten by a role change" + ); + assert_eq!( + counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + 1, + "…and its seat stays claimed with it — the row is the seat" + ); +} + +/// An orphan signup — its event record gone — has no seat to give back and no +/// list that can freeze, and `unregister` answers 404 on the missing event. So +/// the sweep must *delete* it rather than skip it: skipped, it is the exact +/// unremovable row the sweep exists to prevent. (Low reach — `Event::delete` +/// cascades in one transaction — but this is the class, not a coincidence.) +#[tokio::test] +async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen", "teacher").await; + let admin = login_as(&app, &db, "yonetici", "admin").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + + let live = capped_event(&app, &teacher, None).await; + let doomed = capped_event(&app, &teacher, None).await; + assert_eq!( + seat(&app, &teacher, &live, &ali_id).await.status, + StatusCode::OK + ); + assert_eq!( + seat(&app, &teacher, &doomed, &ali_id).await.status, + StatusCode::OK + ); + + // The state a delete that raced a register used to leave: the row outlives + // its event. Written straight into the store, since the cascade now makes + // it unreachable through the API. + db.query("DELETE type::record('event', $key)") + .bind(("key", doomed.clone())) + .await + .unwrap() + .check() + .unwrap(); + + let res = send( + &app, + "PATCH", + &format!("/users/{ali_id}/role"), + Some(&admin), + Some(json!({ "role": "parent" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + assert_eq!( + rows("SELECT VALUE id FROM registration", &db).await, + 0, + "an orphan signup must go with the rest — nothing else can ever remove it" + ); + assert_eq!( + counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + 0, + "and the surviving event still gets its seat back" + ); +} + +/// How many boards list `user` as a participant, read out of the store. +async fn boards_listing(user: &str, db: &Database) -> i64 { + let mut result = db + .query("SELECT VALUE id FROM board WHERE type::record('user', $u) IN participants") + .bind(("u", user.to_string())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .len() as i64 +} + +/// A `parent` is barred from the whiteboard outright, and invites already +/// refuse the role — but `set_role` never touched a roster, so a demotion left +/// the user listed forever: still fanned every stroke, and a stale id that 400s +/// the creator's next roster PATCH. The sweep drops them from every list and +/// **deletes nothing** — not a board, not a stroke, not even the board they +/// created, whose room carries on for everyone else with a creator who can no +/// longer use it (a role change must not destroy other people's work; there is +/// no way to hand a board over, so closing or deleting it would be the role +/// change silently ending a live session). +#[tokio::test] +async fn a_demotion_to_parent_leaves_every_board_roster_and_deletes_nothing() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "yonetici", "admin").await; + let ali = login(&app, "ali").await; + let veli = login(&app, "veli").await; + let ali_id = me_id(&app, &ali).await; + let veli_id = me_id(&app, &veli).await; + + // One board veli was invited to, one board veli created. + let guest = send( + &app, + "POST", + "/boards", + Some(&ali), + Some(json!({ "title": "Geometri", "participants": [veli_id] })), + ) + .await; + assert_eq!(guest.status, StatusCode::CREATED, "{}", guest.body); + let own = send( + &app, + "POST", + "/boards", + Some(&veli), + Some(json!({ "title": "Cebir", "participants": [ali_id] })), + ) + .await; + assert_eq!(own.status, StatusCode::CREATED, "{}", own.body); + let own_id = id_of(&own.body); + assert_eq!(boards_listing(&veli_id, &db).await, 1); + + let res = send( + &app, + "PATCH", + &format!("/users/{veli_id}/role"), + Some(&admin), + Some(json!({ "role": "parent" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + assert_eq!( + boards_listing(&veli_id, &db).await, + 0, + "a parent may appear on no board roster" + ); + // Nothing was destroyed, and the board they created is untouched beyond + // that: same creator, and its other participant still on it. + assert_eq!(rows("SELECT VALUE id FROM board", &db).await, 2); + let res = send(&app, "GET", &format!("/boards/{own_id}"), Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["creator"], veli_id); + assert_eq!(res.body["participants"], json!([ali_id])); + + // And the demoted creator is barred from their own board, by role alone. + let res = send(&app, "GET", &format!("/boards/{own_id}"), Some(&veli), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); +} + +/// The cascade and the parent row now commit together. Run as two queries, a +/// register or a mark landing in between outlived its event — an orphan keyed +/// on a row that no longer exists, so no read path could reach it and no delete +/// could reclaim it. The state is asserted against the store, not the 204. +#[tokio::test] +async fn deleting_an_event_takes_its_children_with_it() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen", "teacher").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + + let event = capped_event(&app, &teacher, None).await; + let res = seat(&app, &teacher, &event, &ali_id).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/events/{event}/attendance"), + Some(&teacher), + Some(json!({ "user_id": ali_id, "status": "present" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(rows("SELECT VALUE id FROM attendance", &db).await, 1); + + let res = send( + &app, + "DELETE", + &format!("/events/{event}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + assert_eq!(rows("SELECT VALUE id FROM event", &db).await, 0); + assert_eq!( + rows("SELECT VALUE id FROM attendance", &db).await, + 0, + "no mark may outlive its event" + ); + assert_eq!( + rows("SELECT VALUE id FROM registration", &db).await, + 0, + "no signup may outlive its event" + ); +} + +/// The note half of the same defect: the attachment rows and the note commit +/// together, so an upload can no longer leave a `note_file` pointing at a note +/// that is gone (its *blob* is a known, documented leak — see `Note::delete`). +#[tokio::test] +async fn deleting_a_note_takes_its_attachment_rows_with_it() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; + + let res = send( + &app, + "POST", + "/notes", + Some(&ali), + Some(json!({ "title": "Plan", "content": "yarın" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let note = id_of(&res.body); + + let up = common::upload_file(&app, &ali, ¬e, "plan.txt", "text/plain", b"merhaba").await; + assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); + assert_eq!(rows("SELECT VALUE id FROM note_file", &db).await, 1); + + let res = send(&app, "DELETE", &format!("/notes/{note}"), Some(&ali), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + assert_eq!(rows("SELECT VALUE id FROM note", &db).await, 0); + assert_eq!( + rows("SELECT VALUE id FROM note_file", &db).await, + 0, + "no attachment row may outlive its note" + ); +}