diff --git a/README.md b/README.md index b2144e2..a4cd280 100644 --- a/README.md +++ b/README.md @@ -34,13 +34,19 @@ plus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`): an assigned teacher manages everything inside the course — exams, sessions, subjects, roster, grading — but can't delete it or change who else teaches it, and a demotion below `teacher` sweeps their assignments away. Students are -grouped into **classes** (*şube* — 9-A, 10-B) when a school teaches that way: -a class is bulk enrollment and not a second kind of membership — attaching a +grouped into a **class section** (*şube* — 9-A, 10-B) when a school teaches +that way: it is bulk enrollment, not a second kind of membership — attaching a course to it enrolls the whole roster, adding a member enrolls them into every course already attached, and what lands are ordinary enrollment rows tagged -with the class that pumped them (untagged = placed by hand, and hand-placed +with the section that pumped them (untagged = placed by hand, and hand-placed rows are never adopted and never swept). A course without room for everyone -refuses the whole operation, naming it (see "Classes (şube)"). Students read a per-course weighted average and +refuses the whole operation, naming it (see "Class sections (şube)"). A section +may also +name a **homeroom teacher** (*sınıf öğretmeni*, `teacher_id` — any teacher+ +account, cleared automatically when that account is demoted), and while every +other class read is teacher+, a student reads their own section at +`GET /classes/me` (staff and a linked parent read anyone's at +`GET /classes/user/{user}`). Students read a per-course weighted average and an overall average from their mark report — each exam weighted by its **kind** (midterms can count double, orals once: weights are set per kind in settings, not per exam). Exams run **sync** (one @@ -528,7 +534,7 @@ history, and re-registering is refused. | Delete a course | teacher | Only the **creator**, or a `manager`+ — an assigned teacher runs the course but doesn't own it | | 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`) | | View a course's roster, an exam's result list / statistics | teacher | Course-management rights | -| 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` | +| Create / edit / delete a **class section** (şube); add or remove its members | manager | Reading classes, their rosters and their course lists is teacher+ — except `GET /classes/me`, which any authenticated user reads for themselves, and `GET /classes/user/{user}`, open to teacher+ and a linked parent; a member must be a `student`, a `teacher_id` must be teacher+ | | 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 | | 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 | | Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself | @@ -598,7 +604,11 @@ call, so a course's own creator cannot hand rights to their peers; only manager+ may touch the list. Every course response carries its `teachers` array alongside `creator`, and a user demoted below `teacher` is swept off every course they were assigned to (the mirror of promotion dropping -enrollments). +enrollments). That sweep runs once, so an assignment landing in the same +instant would survive it: the assign call therefore re-reads the account's live +role **after** its write and answers `409` — dropping the assignment again — if +it has since fallen below `teacher`. Same guard, same wording, as a class's +homeroom teacher. Course data is walled per course. A course, its exams, its sessions, and its subjects are @@ -705,15 +715,17 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) | | 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) | | 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) | -| POST | `/courses/{id}/teachers` | manager | `{user_id}` — assign a **teacher+** to run the course (idempotent; returns the course) | +| POST | `/courses/{id}/teachers` | manager | `{user_id}` — assign a **teacher+** to run the course (idempotent; returns the course; `409` + undo if that account is demoted mid-request) | | DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) | | 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 | | 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 | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | -| POST | `/classes` | manager | `{name, grade?, term_id?}` — create a class (şube); `grade` is a free-text year label | +| POST | `/classes` | manager | `{name, grade?, term_id?, teacher_id?}` — create a class section (şube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (sınıf öğretmeni, teacher+; `409` + full rollback if that account is demoted mid-request) | | GET | `/classes` | teacher | List classes, newest first · paged | +| GET | `/classes/me` | any | The caller's own classes, newest membership first · paged; `creator` is `null` below teacher+ | +| GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) · paged; `creator` is `null` below teacher+ | | GET | `/classes/{id}` | teacher | Get one class | -| 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) | +| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_id`; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) | | DELETE | `/classes/{id}` | manager | Delete a class — `409` while it still holds students or courses | | 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`) | | GET | `/classes/{id}/members` | teacher | List the class roster, newest added first · paged | @@ -2266,10 +2278,10 @@ for every course the user has roll-call rows in — attendance is a historical record, so unenrolling hides marks from the marks report but never hides an absence. -## Classes (şube) +## Class sections (şube) -A **class** is the group a school actually teaches in — 9-A, 10-B — and here -it is a bulk-enrollment tool rather than a second kind of membership. A class +A **class section** is the group a school actually teaches in — 9-A, 10-B — and +here it is a bulk-enrollment tool rather than a second kind of membership. Its row carries a name, an optional free-text `grade` label in the school's own vocabulary (`"9"`, `"Lise 2"`; `""` means no grade, exactly like omitting it) and an optional `term_id`; nothing else about a course changes because a class @@ -2277,6 +2289,26 @@ exists. Schools that run electives or a college-style timetable simply never create one — individual enrollment is untouched, and classes are a convenience. +**The homeroom teacher.** A class may also name one — the *sınıf öğretmeni* — +with `teacher_id` on create or `PATCH`, and it rides back out as a `teacher` +person block (`null` when there is none, exactly like `grade`; both `null` and +`""` clear it). The account must exist and hold **teacher, manager or admin** +(anything else is a `400` naming `teacher_id`, the same shape a non-student +member gets). It is a label and nothing more: it grants no rights over the +class, is not counted, and is not a second teacher assignment — courses keep +their own `teachers` list. A role change that takes the account below `teacher` +clears the column on **every** class it held, in the same sweep that drops +their course assignments, so no section ever lists a demoted account. + +That sweep runs once, over the rows that exist when it runs — so a demotion +that lands *between* a request's role check and its write would sweep nothing +and leave the assignment standing forever. Both writers close it from the other +end: `POST /classes`, `PATCH /classes/{id}` and `POST /courses/{id}/teachers` +re-read the account's live role **after** their write and answer `409` if it +has since dropped below `teacher`, taking the assignment back (a create is +rolled back whole — no half-made class is left behind). Whichever side is +second catches it; the ordinary path costs one extra read and no extra write. + **The pump.** A class holds **members** (students) and **attached courses**, and owes the product of the two: every member enrolled in every attached course. So both writes push the same way — attaching a course @@ -2371,6 +2403,24 @@ when the student was *added* or the course *attached*, not the student's or the course's own id, which is what a link row keyed on the pair would otherwise sort by. Rows written before that stamp existed carry none, and sort last. +**Except your own section.** Every route above is staff-only, which left a student +with no way to learn which class they are in. Two reads fix that, both paged +and both returning the same class objects: `GET /classes/me` is the caller's +own memberships (**any authenticated role** — staff, who are never members, +simply get an empty page), and `GET /classes/user/{user}` is somebody else's, +gated exactly like the per-student reports — **teacher+, or a parent linked to +that student**; anyone else gets a `403` that leaks no existence, and a user +who does not exist is a `404`. Ordering is by when the membership was added, +newest first, and `total` counts the memberships the window was cut from. + +Both of them hide one field: **`creator` is `null` below teacher+**. A class is +created by manager+ only, so shipping the creator to a student (or to their +linked parent) would hand out an office account's username and real name — an +identity `GET /users` (admin-only) and `/users/search` (teacher+) both withhold. +The homeroom teacher is *not* hidden: naming them is the point of the read. On +every staff-facing route (`GET /classes`, `/classes/{id}`, and the create/edit +responses) `creator` is populated exactly as before. + **Codes.** Adding a member or attaching a course answers `201`; a repeat is a `409` ("the student is already in this class", "the course is already on this class"). An id in the **body** that names nothing — an unknown `user_id` or @@ -3077,7 +3127,7 @@ src/ work_entry.rs WorkEntryId · WorkEntry (staff stint; one open per user by construction) enrollment.rs EnrollmentId · Enrollment (one row per course+user; `source` names the class that pumped it, absent when hand-placed) - class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube; + class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a class section; deletable only with no members and no attached courses) class_member.rs ClassMember (one student in a class; adding them enrolls them into every course the class holds) diff --git a/history.txt b/history.txt index 747c6e8..e253468 100644 --- a/history.txt +++ b/history.txt @@ -1,48 +1,24 @@ #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 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\\") |"}]; +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 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"}]; +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 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; +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 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"}]; +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; @@ -51,51 +27,75 @@ INSERT INTO endpoint [{"id": "health", "routes": "| GET | `/health` 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 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"}]; +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 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\\") |"}]; +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; 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 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"}]; +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\\n **Known limit, accepted:** that gate is *per exam*. Instantiating one question\\n bank template into two exams copies its `correct` verbatim into both (the bank\\n is a copy-into-exam model, not a link), so a student sitting exam A can read\\n the same question's answer off exam B if B is graded and has review on. The\\n narrower gate cannot see it, and widening review to \\"no in-progress sitting on\\n *any* exam\\" would close review far too broadly, since `open`-mode sittings\\n never expire on their own. Teachers reusing one template across a live exam\\n and a reviewable one should expect that overlap.\\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": "fbf66230f9dc6a1af2045b516005fa1cac49cf9d070fb9bbf1341a5fa4ad2ece"}]; 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\\") |"}]; +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 sha256 FROM meta:readme; +SELECT id, title FROM doc; +SELECT body FROM doc:`classes-ube`; +SELECT routes FROM endpoint:classes; 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 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"}]; +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)\\"). A class may also\\nname a **homeroom teacher** (*sınıf öğretmeni*, `teacher_id` — any teacher+\\naccount, cleared automatically when that account is demoted), and while every\\nother class read is teacher+, a student reads their own şube at\\n`GET /classes/me` (staff and a linked parent read anyone's at\\n`GET /classes/user/{user}`). 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\\n **Known limit, accepted:** that gate is *per exam*. Instantiating one question\\n bank template into two exams copies its `correct` verbatim into both (the bank\\n is a copy-into-exam model, not a link), so a student sitting exam A can read\\n the same question's answer off exam B if B is graded and has review on. The\\n narrower gate cannot see it, and widening review to \\"no in-progress sitting on\\n *any* exam\\" would close review far too broadly, since `open`-mode sittings\\n never expire on their own. Teachers reusing one template across a live exam\\n and a reviewable one should expect that overlap.\\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": "4f1dbf614333f879e6a6c2722692cc4265a2b72f2939c2782165f1c6467c300c"}]; 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\\") |"}]; +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; 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"}]; +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)\\"). A class may also\\nname a **homeroom teacher** (*sınıf öğretmeni*, `teacher_id` — any teacher+\\naccount, cleared automatically when that account is demoted), and while every\\nother class read is teacher+, a student reads their own şube at\\n`GET /classes/me` (staff and a linked parent read anyone's at\\n`GET /classes/user/{user}`). 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?, teacher_id?}` — create a class (şube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (sınıf öğretmeni, teacher+) |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/me` | any | The caller's own classes, newest membership first · paged |\\n| GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_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\\n **Known limit, accepted:** that gate is *per exam*. Instantiating one question\\n bank template into two exams copies its `correct` verbatim into both (the bank\\n is a copy-into-exam model, not a link), so a student sitting exam A can read\\n the same question's answer off exam B if B is graded and has review on. The\\n narrower gate cannot see it, and widening review to \\"no in-progress sitting on\\n *any* exam\\" would close review far too broadly, since `open`-mode sittings\\n never expire on their own. Teachers reusing one template across a live exam\\n and a reviewable one should expect that overlap.\\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": "e4d95a5c21a0640b06ea896a52402679de073cbf499f9ac2810d91ff32c1a1e3"}]; 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\\") |"}]; +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?, teacher_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (s\\u0131n\\u0131f \\u00f6\\u011fretmeni, teacher+) |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/me` | any | The caller's own classes, newest membership first \\u00b7 paged |\\n| GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_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 (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"}]; +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)\\"). A class may also\\nname a **homeroom teacher** (*sınıf öğretmeni*, `teacher_id` — any teacher+\\naccount, cleared automatically when that account is demoted), and while every\\nother class read is teacher+, a student reads their own şube at\\n`GET /classes/me` (staff and a linked parent read anyone's at\\n`GET /classes/user/{user}`). 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?, teacher_id?}` — create a class (şube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (sınıf öğretmeni, teacher+) |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/me` | any | The caller's own classes, newest membership first · paged |\\n| GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_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\\n **Known limit, accepted:** that gate is *per exam*. Instantiating one question\\n bank template into two exams copies its `correct` verbatim into both (the bank\\n is a copy-into-exam model, not a link), so a student sitting exam A can read\\n the same question's answer off exam B if B is graded and has review on. The\\n narrower gate cannot see it, and widening review to \\"no in-progress sitting on\\n *any* exam\\" would close review far too broadly, since `open`-mode sittings\\n never expire on their own. Teachers reusing one template across a live exam\\n and a reviewable one should expect that overlap.\\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 homeroom teacher.** A class may also name one — the *sınıf öğretmeni* —\\nwith `teacher_id` on create or `PATCH`, and it rides back out as a `teacher`\\nperson block (`null` when there is none, exactly like `grade`; both `null` and\\n`\\"\\"` clear it). The account must exist and hold **teacher, manager or admin**\\n(anything else is a `400` naming `teacher_id`, the same shape a non-student\\nmember gets). It is a label and nothing more: it grants no rights over the\\nclass, is not counted, and is not a second teacher assignment — courses keep\\ntheir own `teachers` list. A role change that takes the account below `teacher`\\nclears the column on **every** class it held, in the same sweep that drops\\ntheir course assignments, so no şube ever lists a demoted account.\\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": "cd344b8db59bf4c7abb302435d44bc1a04412e10431d98c829ed80ee48b8ceae"}]; 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), 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\\") |"}]; +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?, teacher_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (s\\u0131n\\u0131f \\u00f6\\u011fretmeni, teacher+) |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/me` | any | The caller's own classes, newest membership first \\u00b7 paged |\\n| GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_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)\\"). A class may also\\nname a **homeroom teacher** (*sınıf öğretmeni*, `teacher_id` — any teacher+\\naccount, cleared automatically when that account is demoted), and while every\\nother class read is teacher+, a student reads their own şube at\\n`GET /classes/me` (staff and a linked parent read anyone's at\\n`GET /classes/user/{user}`). 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?, teacher_id?}` — create a class (şube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (sınıf öğretmeni, teacher+) |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/me` | any | The caller's own classes, newest membership first · paged |\\n| GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_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\\n **Known limit, accepted:** that gate is *per exam*. Instantiating one question\\n bank template into two exams copies its `correct` verbatim into both (the bank\\n is a copy-into-exam model, not a link), so a student sitting exam A can read\\n the same question's answer off exam B if B is graded and has review on. The\\n narrower gate cannot see it, and widening review to \\"no in-progress sitting on\\n *any* exam\\" would close review far too broadly, since `open`-mode sittings\\n never expire on their own. Teachers reusing one template across a live exam\\n and a reviewable one should expect that overlap.\\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 homeroom teacher.** A class may also name one — the *sınıf öğretmeni* —\\nwith `teacher_id` on create or `PATCH`, and it rides back out as a `teacher`\\nperson block (`null` when there is none, exactly like `grade`; both `null` and\\n`\\"\\"` clear it). The account must exist and hold **teacher, manager or admin**\\n(anything else is a `400` naming `teacher_id`, the same shape a non-student\\nmember gets). It is a label and nothing more: it grants no rights over the\\nclass, is not counted, and is not a second teacher assignment — courses keep\\ntheir own `teachers` list. A role change that takes the account below `teacher`\\nclears the column on **every** class it held, in the same sweep that drops\\ntheir course assignments, so no şube ever lists a demoted account.\\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**Except your own şube.** Every route above is staff-only, which left a student\\nwith no way to learn which class they are in. Two reads fix that, both paged\\nand both returning the same class objects: `GET /classes/me` is the caller's\\nown memberships (**any authenticated role** — staff, who are never members,\\nsimply get an empty page), and `GET /classes/user/{user}` is somebody else's,\\ngated exactly like the per-student reports — **teacher+, or a parent linked to\\nthat student**; anyone else gets a `403` that leaks no existence, and a user\\nwho does not exist is a `404`. Ordering is by when the membership was added,\\nnewest first, and `total` counts the memberships the window was cut from.\\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": "88a6774b50d758fcd6710daf4827cb6fba1a787c446dd1443daf929168f8e464"}]; +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), 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?, teacher_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (s\\u0131n\\u0131f \\u00f6\\u011fretmeni, teacher+) |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/me` | any | The caller's own classes, newest membership first \\u00b7 paged |\\n| GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_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)\\"). A class may also\\nname a **homeroom teacher** (*sınıf öğretmeni*, `teacher_id` — any teacher+\\naccount, cleared automatically when that account is demoted), and while every\\nother class read is teacher+, a student reads their own şube at\\n`GET /classes/me` (staff and a linked parent read anyone's at\\n`GET /classes/user/{user}`). 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+ — except `GET /classes/me`, which any authenticated user reads for themselves, and `GET /classes/user/{user}`, open to teacher+ and a linked parent; a member must be a `student`, a `teacher_id` must be teacher+ |\\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?, teacher_id?}` — create a class (şube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (sınıf öğretmeni, teacher+) |\\n| GET | `/classes` | teacher | List classes, newest first · paged |\\n| GET | `/classes/me` | any | The caller's own classes, newest membership first · paged |\\n| GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) · paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_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\\n **Known limit, accepted:** that gate is *per exam*. Instantiating one question\\n bank template into two exams copies its `correct` verbatim into both (the bank\\n is a copy-into-exam model, not a link), so a student sitting exam A can read\\n the same question's answer off exam B if B is graded and has review on. The\\n narrower gate cannot see it, and widening review to \\"no in-progress sitting on\\n *any* exam\\" would close review far too broadly, since `open`-mode sittings\\n never expire on their own. Teachers reusing one template across a live exam\\n and a reviewable one should expect that overlap.\\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 homeroom teacher.** A class may also name one — the *sınıf öğretmeni* —\\nwith `teacher_id` on create or `PATCH`, and it rides back out as a `teacher`\\nperson block (`null` when there is none, exactly like `grade`; both `null` and\\n`\\"\\"` clear it). The account must exist and hold **teacher, manager or admin**\\n(anything else is a `400` naming `teacher_id`, the same shape a non-student\\nmember gets). It is a label and nothing more: it grants no rights over the\\nclass, is not counted, and is not a second teacher assignment — courses keep\\ntheir own `teachers` list. A role change that takes the account below `teacher`\\nclears the column on **every** class it held, in the same sweep that drops\\ntheir course assignments, so no şube ever lists a demoted account.\\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**Except your own şube.** Every route above is staff-only, which left a student\\nwith no way to learn which class they are in. Two reads fix that, both paged\\nand both returning the same class objects: `GET /classes/me` is the caller's\\nown memberships (**any authenticated role** — staff, who are never members,\\nsimply get an empty page), and `GET /classes/user/{user}` is somebody else's,\\ngated exactly like the per-student reports — **teacher+, or a parent linked to\\nthat student**; anyone else gets a `403` that leaks no existence, and a user\\nwho does not exist is a `404`. Ordering is by when the membership was added,\\nnewest first, and `total` counts the memberships the window was cut from.\\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": "c93d3daccf07e0687ec3aae3669273524c50e264f7b821dcff5b66848b0f36e9"}]; +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), 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?, teacher_id?}` \\u2014 create a class (\\u015fube); `grade` is a free-text year label, `teacher_id` the homeroom teacher (s\\u0131n\\u0131f \\u00f6\\u011fretmeni, teacher+) |\\n| GET | `/classes` | teacher | List classes, newest first \\u00b7 paged |\\n| GET | `/classes/me` | any | The caller's own classes, newest membership first \\u00b7 paged |\\n| GET | `/classes/user/{user}` | teacher | Another user's classes (a parent linked to that student may read it too) \\u00b7 paged |\\n| GET | `/classes/{id}` | teacher | Get one class |\\n| PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_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; diff --git a/src/constant.rs b/src/constant.rs index 46645a6..dcb719d 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -86,9 +86,10 @@ pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; pub const MAX_COURSE_TITLE_LEN: usize = 200; pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; -/// A class (şube) is named like a course, but its optional `grade` is a free-text -/// label the school picks ("9", "10-A", "anaokulu") — a line of display text, so -/// it is bounded like the other short labels, not like a description. +/// A class section (şube) is named like a course, but its optional `grade` is +/// a free-text label the school picks ("9", "10-A", "anaokulu") — a line of +/// display text, so it is bounded like the other short labels, not like a +/// description. pub const MAX_CLASS_NAME_LEN: usize = 200; pub const MAX_CLASS_GRADE_LEN: usize = 20; @@ -97,7 +98,7 @@ pub const MAX_CLASS_GRADE_LEN: usize = 20; /// adding a member writes one per attached course, both in a *single* /// transaction, so each axis's counter is the bound on the other axis's write /// loop — a class with no ceiling is an unbounded transaction anyone with the -/// manager role can trigger. A şube is a homeroom (`MAX_HOMEWORK_ASSIGNED` +/// manager role can trigger. A section is a homeroom (`MAX_HOMEWORK_ASSIGNED` /// shares the 200) and its timetable is a school week, not a catalogue. /// /// Which is also why each write is refused on the *other* axis: a class created diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 35c3018..9bf0dbb 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -1,5 +1,5 @@ -//! A class (şube): a named set of students the school manages as one, so a -//! course attach enrolls the whole set at once. The membership and the +//! A class section (şube): a named set of students the school manages as one, +//! so a course attach enrolls the whole set at once. The membership and the //! attachments live in their own tables (`class_member`, `class_course`) and are //! counted on this row — a class may only be deleted at zero on both, the same //! stored guard shape courses and terms use. @@ -88,6 +88,12 @@ impl ClassGrade { /// One class. `creator` is who made it; the two refcounts behind the delete /// guard are database-side columns only, so no whole-row save can clobber one /// (see [`crate::domain::cap`]). +/// +/// `teacher` is the section's homeroom teacher (sınıf öğretmeni): optional, not +/// refcounted, and merely a label pointing at a teacher-or-higher account — the +/// web layer holds that bar, and a demotion sweeps the column +/// ([`ClassGroup::unassign_everywhere`]). Rows written before the column exists +/// carry no key at all, which reads back as `None`. #[derive(Debug, Clone, SurrealValue)] pub struct ClassGroup { id: ClassGroupId, @@ -95,6 +101,7 @@ pub struct ClassGroup { name: ClassName, grade: Option, term: Option, + teacher: Option, } impl ClassGroup { @@ -118,6 +125,11 @@ impl ClassGroup { self.term.as_ref() } + /// The homeroom teacher (sınıf öğretmeni), if one is assigned. + pub fn get_teacher(&self) -> Option<&UserId> { + self.teacher.as_ref() + } + pub fn is_creator(&self, user: &UserId) -> bool { &self.creator == user } @@ -133,6 +145,7 @@ impl ClassGroup { name: ClassName, grade: Option, term: Option, + teacher: Option, db: &Database, ) -> Result { let class = ClassGroup { @@ -141,6 +154,7 @@ impl ClassGroup { name, grade, term, + teacher, }; let id = class.id.record(); let Some(term) = class.term.clone() else { @@ -183,9 +197,9 @@ impl ClassGroup { /// Write only the fields the PATCH carried — `None` means the request /// omitted it, so the column is left alone rather than re-stated from the - /// snapshot this struct was read into. `grade` and `term` are nullable, so - /// they take the outer/inner `Option>`: `None` = omitted (keep), - /// `Some(None)` = clear. + /// snapshot this struct was read into. `grade`, `term` and `teacher` are + /// nullable, so they take the outer/inner `Option>`: `None` = + /// omitted (keep), `Some(None)` = clear. /// /// A term move claims the new term and releases the old one inside the very /// transaction that moves the link, exactly as in @@ -196,6 +210,7 @@ impl ClassGroup { name: Option, grade: Option>, term: Option>, + teacher: Option>, db: &Database, ) -> Result { let (claim, release) = term::ref_move(self.term.as_ref(), &term); @@ -204,6 +219,12 @@ impl ClassGroup { .set("name", name) .set("grade", grade) .set("term", term.map(|term| term.map(|term| term.record()))) + // Not refcounted: a homeroom assignment is a label, so it rides the + // plain `set` path and never arms the term CAS. + .set( + "teacher", + teacher.map(|teacher| teacher.map(|teacher| teacher.record())), + ) .refcount( TERM_CLASS_COUNT_FIELD, "term", @@ -216,6 +237,38 @@ impl ClassGroup { .await } + /// The classes `ids` names, in no particular order — the join behind + /// "which class section is this student in", where the ids come from + /// `class_member` rows already paged. Ids that name no row are simply + /// absent. + pub async fn list_by_ids( + ids: &[ClassGroupId], + db: &Database, + ) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = ids.iter().map(ClassGroupId::record).collect(); + let mut result = db + .query("SELECT * FROM class_group WHERE id IN $ids") + .bind(("ids", records)) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Strip `user` from every class they were the homeroom teacher of — the + /// sweep for a user demoted below `teacher`, who may no longer hold one. + /// The mirror of [`crate::domain::course::Course::unassign_everywhere`]; + /// nothing is counted on this column, so there is no reference to give back. + pub async fn unassign_everywhere(user: &UserId, db: &Database) -> Result<(), AppError> { + db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(()) + } + /// Delete the class and give its term reference back. Nothing cascades: a /// class that still holds students or courses is refused outright, because /// dropping it silently would leave the enrollments it pumped behind with @@ -281,12 +334,37 @@ mod tests { ClassName::try_new("9-A").unwrap(), None, term, + None, db, ) .await .unwrap() } + /// A class with a homeroom teacher, no term. + async fn class_of(teacher: Option, db: &Database) -> ClassGroup { + ClassGroup::create( + &UserId::from_key("manager"), + ClassName::try_new("9-A").unwrap(), + None, + None, + teacher, + db, + ) + .await + .unwrap() + } + + /// The stored `teacher` column, re-read. + async fn teacher_of(class: &ClassGroupId, db: &Database) -> Option { + ClassGroup::read(class, db) + .await + .unwrap() + .unwrap() + .get_teacher() + .cloned() + } + async fn a_term(db: &Database) -> Term { let at = crate::domain::timestamp::Timestamp::from_millis; Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), db) @@ -342,6 +420,92 @@ mod tests { assert!(ClassGrade::try_new(&"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err()); } + /// The homeroom teacher survives a create, is set and cleared by a PATCH, + /// and — the part a `.content(self)` save would break — is left alone by a + /// PATCH of another field. A row written before the column exists carries + /// no key at all, which must read back as `None`, not fail the decode. + #[tokio::test] + async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() { + let db = crate::database::init_mem().await.unwrap(); + let ada = UserId::from_key("ada"); + let boole = UserId::from_key("boole"); + + let bare = class_of(None, &db).await; + assert_eq!(teacher_of(bare.get_id(), &db).await, None); + let held = class_of(Some(ada.clone()), &db).await; + assert_eq!(teacher_of(held.get_id(), &db).await, Some(ada.clone())); + + // A name-only PATCH must not re-state the teacher out of its snapshot. + let renamed = held + .update( + Some(ClassName::try_new("9-B").unwrap()), + None, + None, + None, + &db, + ) + .await + .unwrap(); + assert_eq!(renamed.get_name().as_str(), "9-B"); + assert_eq!(teacher_of(renamed.get_id(), &db).await, Some(ada)); + + let moved = renamed + .update(None, None, None, Some(Some(boole.clone())), &db) + .await + .unwrap(); + assert_eq!(teacher_of(moved.get_id(), &db).await, Some(boole)); + + let cleared = moved + .update(None, None, None, Some(None), &db) + .await + .unwrap(); + assert_eq!(teacher_of(cleared.get_id(), &db).await, None); + + // …and the mirror: a teacher-only PATCH leaves the name alone. + let again = cleared + .update(None, None, None, Some(Some(UserId::from_key("ada"))), &db) + .await + .unwrap(); + assert_eq!(again.get_name().as_str(), "9-B"); + + // A row that predates the column: absent key, not NULL. + db.query("UPDATE $class UNSET teacher") + .bind(("class", bare.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + assert_eq!(teacher_of(bare.get_id(), &db).await, None); + } + + /// The demotion sweep: a user who drops below `teacher` is cleared from + /// *every* class they homeroomed, and nobody else's is touched. + #[tokio::test] + async fn unassign_everywhere_clears_only_that_users_classes() { + let db = crate::database::init_mem().await.unwrap(); + let ada = UserId::from_key("ada"); + let boole = UserId::from_key("boole"); + let first = class_of(Some(ada.clone()), &db).await; + let second = class_of(Some(ada.clone()), &db).await; + let other = class_of(Some(boole.clone()), &db).await; + let none = class_of(None, &db).await; + + ClassGroup::unassign_everywhere(&ada, &db).await.unwrap(); + for class in [&first, &second] { + assert_eq!( + teacher_of(class.get_id(), &db).await, + None, + "every class the demoted user homeroomed must be cleared" + ); + } + assert_eq!( + teacher_of(other.get_id(), &db).await, + Some(boole), + "…and nobody else's" + ); + assert_eq!(teacher_of(none.get_id(), &db).await, None); + } + /// The bite test for the class half of the term delete guard: a term is /// undeletable while a *class* links it, on its own column, and every way /// that link can end gives the reference back. Claiming into `course_count` @@ -368,7 +532,10 @@ mod tests { "two linked classes must refuse the delete" ); - patched.update(None, None, Some(None), &db).await.unwrap(); + patched + .update(None, None, Some(None), None, &db) + .await + .unwrap(); assert!( !term.clone().delete(&db).await.unwrap(), "one link is still one link" @@ -449,6 +616,7 @@ mod tests { ClassName::try_new("9-A").unwrap(), None, Some(id), + None, &db, ) .await @@ -492,6 +660,7 @@ mod tests { Some(ClassName::try_new("9-B").unwrap()), None, Some(Some(dead_id)), + None, &db, ) .await @@ -510,7 +679,7 @@ mod tests { ); let moved = class - .update(None, None, Some(Some(to.get_id().clone())), &db) + .update(None, None, Some(Some(to.get_id().clone())), None, &db) .await .unwrap(); assert_eq!(moved.get_term(), Some(to.get_id())); @@ -545,7 +714,7 @@ mod tests { let class = class_on(Some(from.get_id().clone()), &db).await; let stale = class.clone(); class - .update(None, None, Some(Some(to.get_id().clone())), &db) + .update(None, None, Some(Some(to.get_id().clone())), None, &db) .await .unwrap(); @@ -553,14 +722,14 @@ mod tests { // claim `other` on top of the winner's claim on `to`. let error = stale .clone() - .update(None, None, Some(Some(other.get_id().clone())), &db) + .update(None, None, Some(Some(other.get_id().clone())), None, &db) .await .expect_err("a mover that read a link it no longer holds must be refused"); assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); // The re-stater: shifts no counter, so only the CAS can stop it. let error = stale .clone() - .update(None, None, Some(Some(from.get_id().clone())), &db) + .update(None, None, Some(Some(from.get_id().clone())), None, &db) .await .expect_err("re-stating a link someone else moved must be refused"); assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); @@ -576,7 +745,7 @@ mod tests { // A genuine no-op re-state still lands and still moves nothing. let same = stored - .update(None, None, Some(Some(to.get_id().clone())), &db) + .update(None, None, Some(Some(to.get_id().clone())), None, &db) .await .expect("re-stating the link the row really holds is not a conflict"); assert_eq!(same.get_term(), Some(to.get_id())); diff --git a/src/domain/class_member.rs b/src/domain/class_member.rs index 8187191..ed7d8dd 100644 --- a/src/domain/class_member.rs +++ b/src/domain/class_member.rs @@ -167,6 +167,24 @@ impl ClassMember { .run(limit, offset, db) .await } + + /// The classes one student belongs to, newest membership first — the read + /// behind "which class section (şube) am I in". Same ordering story as + /// [`ClassMember::list_for_class`], along the other axis of the same index. + pub async fn list_for_user( + user: &UserId, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new( + format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), + "ORDER BY added_at DESC, id DESC", + ) + .bind("usr", user.record()) + .run(limit, offset, db) + .await + } } #[cfg(test)] @@ -183,6 +201,7 @@ pub(crate) mod tests { ClassName::try_new(name).unwrap(), None, None, + None, db, ) .await diff --git a/src/domain/class_pump.rs b/src/domain/class_pump.rs index 1983552..d01ce98 100644 --- a/src/domain/class_pump.rs +++ b/src/domain/class_pump.rs @@ -1,7 +1,8 @@ //! The pump behind the class layer: one link row changed, and every //! `enrollment` row that link implies reconciled with it, in one transaction. //! -//! A class (şube) has two link tables — `class_member` (a student in it) and +//! A class section (şube) has two link tables — `class_member` (a student in +//! it) and //! `class_course` (a course attached to it) — and the *product* of the two is //! the roster it owes: every member is enrolled in every attached course, in //! real `enrollment` rows tagged [`source`](crate::domain::enrollment) with the diff --git a/src/lib.rs b/src/lib.rs index 69a4c07..d805862 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,7 +36,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular taught course), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into classes (şube — a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (that tag rides out as the enrollment response's `source`; `null` = placed by hand, and a hand-placed row is never adopted, never swept — enrolling a pumped student by hand clears the tag, the mirror of a manual unenroll winning permanently). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), as is one whose class already holds `max_class_members` students or `max_class_courses` courses (200 and 50: each add writes one enrollment per row on the other axis in a single transaction, so each ceiling is the bound on the other's write loop) or one whose class carries a link to a course that no longer exists (409 naming it — detach that link, no capacity will help); removing a member or detaching a course takes back only the rows that class pumped — re-tagging a row a second class still claims instead of dropping it — and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular taught course), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into class sections (şube — a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (that tag rides out as the enrollment response's `source`; `null` = placed by hand, and a hand-placed row is never adopted, never swept — enrolling a pumped student by hand clears the tag, the mirror of a manual unenroll winning permanently). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), as is one whose class already holds `max_class_members` students or `max_class_courses` courses (200 and 50: each add writes one enrollment per row on the other axis in a single transaction, so each ceiling is the bound on the other's write loop) or one whose class carries a link to a course that no longer exists (409 naming it — detach that link, no capacity will help); removing a member or detaching a course takes back only the rows that class pumped — re-tagging a row a second class still claims instead of dropping it — and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", ), modifiers(&SecurityAddon), tags( @@ -50,7 +50,7 @@ use crate::state::AppState; (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), - (name = "classes", description = "Classes (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster"), + (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), diff --git a/src/migration_sql.rs b/src/migration_sql.rs index e8b1fa9..94ec57c 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -265,7 +265,7 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS homework_count ON subject TYPE option; DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course; - -- A class (şube) is a named set of students that bulk-manages real + -- A class section (şube) is a named set of students that bulk-manages real -- `enrollment` rows: `class_member` is one student in it, `class_course` one -- course it is attached to. Both counters gate the class delete. DEFINE TABLE IF NOT EXISTS class_group SCHEMAFULL; @@ -273,6 +273,7 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS grade ON class_group TYPE option; DEFINE FIELD IF NOT EXISTS term ON class_group TYPE option>; DEFINE FIELD IF NOT EXISTS creator ON class_group TYPE record; + DEFINE FIELD IF NOT EXISTS teacher ON class_group TYPE option>; DEFINE FIELD IF NOT EXISTS class_member_count ON class_group TYPE option; DEFINE FIELD IF NOT EXISTS class_course_count ON class_group TYPE option; diff --git a/src/web/classes.rs b/src/web/classes.rs index 460c8c9..f9279a4 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -1,4 +1,4 @@ -//! Classes (şube): a named set of students the school moves as one. +//! Class sections (şube): a named set of students the school moves as one. //! //! Nothing here is a second kind of membership — adding a student to a class //! enrolls them into every course the class carries, and attaching a course @@ -28,12 +28,21 @@ use crate::state::AppState; use super::courses::can_manage_course; use super::terms::resolve_term; use super::{ - Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map, set_or_clear, + CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, ensure_can_observe, + person_map, set_or_clear, undo_if_demoted, }; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(create_class, list_classes)) + // Registration order is irrelevant here, and saying otherwise would be + // a comment pinning nothing: axum routes on `matchit`, which prefers a + // static segment over a parameter no matter when either was added, so + // `/classes/me` reaches `my_classes` and never `get_class` with an id + // of `"me"`. `a_student_reads_exactly_their_own_classes` is what + // actually checks it, by asserting the body is a page envelope. + .routes(routes!(my_classes)) + .routes(routes!(user_classes)) .routes(routes!(get_class, update_class, delete_class)) .routes(routes!(add_member, list_members)) .routes(routes!(remove_member)) @@ -51,6 +60,10 @@ struct CreateClass { grade: Option, /// The academic term this class belongs to (`GET /terms`). Optional. term_id: Option, + /// The class's homeroom teacher (sınıf öğretmeni) — a teacher, manager or + /// admin account. Optional; omit (or send `""`) for a class with none. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + teacher_id: Option, } #[derive(Deserialize, ToSchema)] @@ -67,6 +80,11 @@ struct UpdateClass { #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option)] term_id: Option>, + /// Omit to keep the current homeroom teacher, send `null` (or `""`) to + /// clear it, or send a teacher+ user id to (re)assign. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + teacher_id: Option>, } #[derive(Deserialize, ToSchema)] @@ -87,8 +105,12 @@ struct AttachCourse { struct ClassResponse { #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] id: String, - /// Who created the class. - creator: PersonRef, + /// Who created the class — always a manager or admin, so it is `null` for + /// a caller below teacher+. `GET /classes/me` and a parent's + /// `GET /classes/user/{user}` are the only reads a non-staff account can + /// make here, and the office's account names are not theirs to learn: + /// `GET /users` is admin-only and `/users/search` is teacher+. + creator: Option, #[schema(example = "9-A")] name: String, /// The school's own free-text grade label; `null` when the class has none. @@ -97,20 +119,46 @@ struct ClassResponse { /// The academic term this class belongs to (`GET /terms`); `null` when /// unassigned. term: Option, + /// The class's homeroom teacher (sınıf öğretmeni); `null` when none is + /// assigned — as it is for every class after the account was demoted below + /// `teacher`. + teacher: Option, } impl ClassResponse { - fn new(class: &ClassGroup, people: &std::collections::HashMap) -> Self { + /// `with_creator` is the caller's clearance: every route but the two + /// membership reads is teacher+ and passes `true`; those two pass it only + /// for a staff caller. The homeroom teacher is never hidden — naming them + /// is the whole point of a student's own section read. + fn new( + class: &ClassGroup, + people: &std::collections::HashMap, + with_creator: bool, + ) -> Self { Self { id: class.get_id().key().to_string(), - creator: PersonRef::resolve(people, class.get_creator()), + creator: with_creator.then(|| PersonRef::resolve(people, class.get_creator())), name: class.get_name().as_str().to_string(), grade: class.get_grade().map(|g| g.as_str().to_string()), term: class.get_term().map(|term| term.key().to_string()), + teacher: class + .get_teacher() + .map(|teacher| PersonRef::resolve(people, teacher)), } } } +/// Every person a [`ClassResponse`] names: its homeroom teacher, plus its +/// creator when the caller is cleared to see one. Feed this into `person_map` — +/// an id the map is missing renders as a bare ULID, so a creator left out here +/// must also be left out of the response. +fn class_people(class: &ClassGroup, with_creator: bool) -> impl Iterator + '_ { + with_creator + .then(|| class.get_creator().clone()) + .into_iter() + .chain(class.get_teacher().cloned()) +} + #[derive(Serialize, ToSchema)] struct ClassMemberResponse { id: String, @@ -170,9 +218,78 @@ fn grade_or_none(text: Option<&str>) -> Result, AppError> { } } +/// The homeroom teacher a request names, as the row itself — an empty string is +/// *no* teacher, exactly like `grade`, so omitting the field and clearing it +/// with `""` land on the same stored row. The named account must exist and hold +/// teacher-or-higher: a class's sınıf öğretmeni is staff, and the check is the +/// same shape `add_member` uses for a non-student. The `User` comes back so the +/// caller can name them in the response without a second read. +async fn teacher_or_none(text: Option<&str>, db: &Database) -> Result, AppError> { + let (None | Some("")) = text else { + return resolve_teacher(text.unwrap_or_default(), db) + .await + .map(Some); + }; + Ok(None) +} + +/// The teacher-or-higher account `key` names, or the 400 both write paths give. +async fn resolve_teacher(key: &str, db: &Database) -> Result { + let Some(teacher) = User::read(&UserId::from_key(key), db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "teacher_id", + reason: "target user does not exist", + })); + }; + if !teacher.get_role().at_least(Role::Teacher) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "teacher_id", + reason: "only a teacher, manager or admin can be a class's homeroom teacher", + })); + } + Ok(teacher) +} + +/// One page of classes with their people joined on — the shared tail of the two +/// membership reads. Ordering follows `rows`, so the page stays newest-first. +/// +/// A membership whose class id resolves to nothing is *skipped*: class deletion +/// is refused while members exist, so it is unreachable, and if a repair ever +/// left one behind a student's own section list must degrade to one row short +/// rather than 500. `total` still counts the membership rows, which is what the +/// window was cut from. +async fn classes_page( + ids: &[ClassGroupId], + total: i64, + limit: Option, + offset: i64, + with_creator: bool, + db: &Database, +) -> Result, AppError> { + let classes = ClassGroup::list_by_ids(ids, db).await?; + let by_id: std::collections::HashMap<&str, &ClassGroup> = classes + .iter() + .map(|class| (class.get_id().key(), class)) + .collect(); + let people = person_map( + classes + .iter() + .flat_map(|class| class_people(class, with_creator)), + db, + ) + .await?; + let items = ids + .iter() + .filter_map(|id| by_id.get(id.key())) + .map(|class| ClassResponse::new(class, &people, with_creator)) + .collect(); + Ok(Page::new(items, total, limit, offset)) +} + /// Create a class. Requires manager+ — a class is school structure, not a /// teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), -/// `term_id` links the school calendar; both optional. +/// `term_id` links the school calendar, `teacher_id` names the homeroom teacher +/// (sınıf öğretmeni, a teacher+ account); all optional. #[utoipa::path( post, path = "/", @@ -181,9 +298,10 @@ fn grade_or_none(text: Option<&str>) -> Result, AppError> { request_body = CreateClass, responses( (status = 201, description = "Class created", body = ClassResponse), - (status = 400, description = "Invalid name or grade, or an unknown term", body = ErrorResponse), + (status = 400, description = "Invalid name or grade, an unknown term, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 409, description = "The named homeroom teacher was demoted below teacher while the request ran — the class was rolled back, nothing was created", body = ErrorResponse), ), )] async fn create_class( @@ -197,12 +315,47 @@ async fn create_class( // before it writes the link, and a term deleted in between fails that claim // with this very error — so an unknown id reads the same whichever side wins. let term = resolve_term(req.term_id.as_deref(), &st.db).await?; - let class = ClassGroup::create(user.get_id(), name, grade, term, &st.db).await?; - // The creator is the caller — already loaded, no extra lookup. - let people = PersonRef::map_of(&[&user]); + let teacher = teacher_or_none(req.teacher_id.as_deref(), &st.db).await?; + let class = ClassGroup::create( + user.get_id(), + name, + grade, + term, + teacher.as_ref().map(|t| t.get_id().clone()), + &st.db, + ) + .await?; + // The row is written; a demotion that raced this request's role check swept + // it too early to see it, so the live role is re-read now (see + // [`undo_if_demoted`]). + if let Some(teacher) = teacher.as_ref() + && let Err(demoted) = undo_if_demoted(teacher.get_id(), &st.db).await + { + // Roll the whole create back, not just the column: a `409` that left a + // teacherless class standing would have the caller either retrying into + // a duplicate or never learning it was there. + // + // The guard cannot refuse this delete — the class is one statement old + // and both of its counters are still absent — so a refusal is a broken + // invariant, not a client error, and it must not be reported as the + // `409` whose text promises nothing was created. + if !class.clone().delete(&st.db).await? { + return Err(AppError::Internal(format!( + "class {} took a member or a course between its create and the \ + rollback of a demoted homeroom teacher; it is still there, \ + without a teacher", + class.get_id().key() + ))); + } + return Err(demoted); + } + // The creator is the caller and the teacher was just read — no extra lookup. + let mut named = vec![&user]; + named.extend(teacher.as_ref()); + let people = PersonRef::map_of(&named); Ok(( StatusCode::CREATED, - Json(ClassResponse::new(&class, &people)), + Json(ClassResponse::new(&class, &people, true)), )) } @@ -229,15 +382,15 @@ async fn list_classes( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let (classes, total) = ClassGroup::list_all(limit, offset, &st.db).await?; - // Join creators onto the page alone — the lookup shrinks with the window. + // Join people onto the page alone — the lookup shrinks with the window. let people = person_map( - classes.iter().map(|class| class.get_creator().clone()), + classes.iter().flat_map(|class| class_people(class, true)), &st.db, ) .await?; let items = classes .iter() - .map(|class| ClassResponse::new(class, &people)) + .map(|class| ClassResponse::new(class, &people, true)) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -262,12 +415,12 @@ async fn get_class( Path(id): Path, ) -> Result, AppError> { let class = class_or_404(&id, &st.db).await?; - let people = person_map(std::iter::once(class.get_creator().clone()), &st.db).await?; - Ok(Json(ClassResponse::new(&class, &people))) + let people = person_map(class_people(&class, true), &st.db).await?; + Ok(Json(ClassResponse::new(&class, &people, true))) } -/// Update a class. Requires manager+. Omitted fields keep their value; `grade` -/// and `term_id` are nullable, so an explicit `null` clears them. +/// Update a class. Requires manager+. Omitted fields keep their value; `grade`, +/// `term_id` and `teacher_id` are nullable, so an explicit `null` clears them. #[utoipa::path( patch, path = "/{id}", @@ -277,11 +430,11 @@ async fn get_class( request_body = UpdateClass, responses( (status = 200, description = "Updated class", body = ClassResponse), - (status = 400, description = "Invalid name or grade, or an unknown term", body = ErrorResponse), + (status = 400, description = "Invalid name or grade, an unknown term, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "The term this update moves the class off changed since the caller read it — nothing was written, re-read and retry", body = ErrorResponse), + (status = 409, description = "The term this update moves the class off changed since the caller read it (nothing was written, re-read and retry), or the named homeroom teacher was demoted below teacher while the request ran (the assignment was undone)", body = ErrorResponse), ), )] async fn update_class( @@ -305,10 +458,117 @@ async fn update_class( Some(ref update) => Some(resolve_term(update.as_deref(), &st.db).await?), None => None, }; + let teacher = match req.teacher_id { + // Explicit `null` (or `""`) clears it; a value must name a teacher+. + Some(ref update) => Some(teacher_or_none(update.as_deref(), &st.db).await?), + None => None, + }; + + let assigned = teacher + .as_ref() + .and_then(|teacher| teacher.as_ref().map(|teacher| teacher.get_id().clone())); + let updated = class + .update( + name, + grade, + term, + teacher.map(|teacher| teacher.map(|teacher| teacher.get_id().clone())), + &st.db, + ) + .await?; + // Only when this request named a teacher: a PATCH that left the column + // alone raced nobody's demotion (see [`undo_if_demoted`]). The undo clears + // the column, which is the whole of what this request wrote to it. + if let Some(teacher) = assigned.as_ref() { + undo_if_demoted(teacher, &st.db).await?; + } + let people = person_map(class_people(&updated, true), &st.db).await?; + Ok(Json(ClassResponse::new(&updated, &people, true))) +} + +// ---- a student's own class ------------------------------------------------- - let updated = class.update(name, grade, term, &st.db).await?; - let people = person_map(std::iter::once(updated.get_creator().clone()), &st.db).await?; - Ok(Json(ClassResponse::new(&updated, &people))) +/// The classes the caller is a member of, newest membership first. Any +/// authenticated role — this is the one class read a student (or a parent, for +/// themselves) can make, since every other `/classes` route is teacher+. Paged +/// via `?limit=&offset=` (omit `limit` for all of them); returns a +/// `{items, total, limit, offset}` envelope. Staff, who are never class +/// members, simply get an empty page. +#[utoipa::path( + get, + path = "/me", + tag = "classes", + security(("session_cookie" = [])), + params(PageParams), + responses( + (status = 200, description = "A page of the caller's classes (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_classes( + State(st): State, + CurrentUser(user): CurrentUser, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + // A student may not learn who in the office created their class; staff may. + let with_creator = user.get_role().at_least(Role::Teacher); + Ok(Json( + classes_of(user.get_id(), limit, offset, with_creator, &st.db).await?, + )) +} + +/// Another user's classes. Requires teacher+, or a parent tied to the target +/// student — the same bar the per-student reports hold, and the same 403 for +/// everyone else (a student reads their own at `GET /classes/me`). +#[utoipa::path( + get, + path = "/user/{user}", + tag = "classes", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "User id"), PageParams), + responses( + (status = 200, description = "A page of that user's classes (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse), + (status = 404, description = "User not found", body = ErrorResponse), + ), +)] +async fn user_classes( + State(st): State, + CurrentUser(caller): CurrentUser, + Path(user): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let target = UserId::from_key(&user); + ensure_can_observe(&caller, &target, &st.db).await?; + // User must exist — a missing user is a 404, not an empty page. + User::read(&target, &st.db) + .await? + .ok_or(AppError::NotFound)?; + // A linked parent reads this too, and is no more entitled to the office's + // account names than their child is. + let with_creator = caller.get_role().at_least(Role::Teacher); + Ok(Json( + classes_of(&target, limit, offset, with_creator, &st.db).await?, + )) +} + +/// One user's class page: the membership rows are what the window is cut from, +/// and the class rows are joined onto that page alone. +async fn classes_of( + user: &UserId, + limit: Option, + offset: i64, + with_creator: bool, + db: &Database, +) -> Result, AppError> { + let (rows, total) = ClassMember::list_for_user(user, limit, offset, db).await?; + let ids: Vec = rows.iter().map(|row| row.get_class().clone()).collect(); + classes_page(&ids, total, limit, offset, with_creator, db).await } /// Delete a class. Requires manager+. Refused with a 409 while it still holds @@ -618,4 +878,60 @@ mod tests { ); assert!(grade_or_none(Some(&"x".repeat(1000))).is_err()); } + + /// The same nullable rule on the homeroom teacher, plus the bar it holds: + /// absent and `""` are the same *no teacher* (and never touch the store), + /// an id naming nobody is a `400`, and so is one naming a student — a + /// class's sınıf öğretmeni is staff. + #[tokio::test] + async fn an_empty_teacher_is_no_teacher_and_a_student_is_never_one() { + use crate::domain::role::Role; + use crate::domain::user::{Password, User, Username}; + + let db = crate::database::init_mem().await.unwrap(); + assert!(teacher_or_none(None, &db).await.unwrap().is_none()); + assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none()); + + let make = async |name: &str, role: Role| { + let user = User::create( + Username::try_new(name).unwrap(), + Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(), + &db, + ) + .await + .unwrap(); + user.set_role(role, &db).await.unwrap() + }; + let student = make("ali", Role::Student).await; + let teacher = make("ada", Role::Teacher).await; + + for (field, id) in [ + ("gone", "01J8XZ0K3Q8G7X2M4N5P6R7S8T"), + ("student", student.get_id().key()), + ] { + let refused = teacher_or_none(Some(id), &db).await; + assert!( + matches!( + refused, + Err(AppError::Validation(ValidationError::Invalid { + field: "teacher_id", + .. + })) + ), + "a {field} id must be a 400 naming teacher_id: {refused:?}" + ); + } + assert_eq!( + teacher_or_none(Some(teacher.get_id().key()), &db) + .await + .unwrap() + .map(|found| found.get_id().clone()), + Some(teacher.get_id().clone()), + "a teacher account is the one thing that resolves" + ); + } } diff --git a/src/web/courses.rs b/src/web/courses.rs index 0e8b81e..236ca89 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -36,6 +36,7 @@ use super::{ CourseResponse, CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef, RequireManager, RequireTeacher, SessionResponse, SubjectResponse, check_not_past, check_time_range, course_people, paginate, person_map, remove_blob, set_or_clear, + undo_if_demoted, }; pub fn routes() -> OpenApiRouter { @@ -540,6 +541,7 @@ async fn delete_course( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), + (status = 409, description = "That user was demoted below teacher while the request ran — the assignment was undone", body = ErrorResponse), ), )] async fn assign_teacher( @@ -570,6 +572,10 @@ async fn assign_teacher( } let updated = course.assign_teacher(&target, &st.db).await?; + // The row is written; a demotion that raced the bar above swept the list + // before this assignment was in it, and nothing re-sweeps (see + // [`super::undo_if_demoted`]). + undo_if_demoted(&target, &st.db).await?; let people = person_map(course_people(&updated), &st.db).await?; Ok(Json(CourseResponse::new(&updated, &people))) } diff --git a/src/web/mod.rs b/src/web/mod.rs index e4f4a66..2ef5661 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -98,6 +98,41 @@ pub(crate) async fn ensure_can_observe( )) } +/// Close the window between "this account is teacher+" and the write that +/// records a teacher-only assignment (a class's homeroom teacher, a course's +/// teacher list). Call it *after* the write, with the account it named. +/// +/// WHY: the demotion sweeps in `set_role` run **once**, over the rows that +/// exist at that moment. A `PATCH /users/{id}/role` interleaving between a +/// handler's role check and its write sweeps nothing — and nothing ever +/// re-sweeps — so the assignment stands forever, naming an account that may no +/// longer be a teacher at all. Re-reading the live role after the write is what +/// makes the pair ordered: either the sweep sees the row, or this read sees the +/// demotion. +/// +/// The undo is the very sweep `set_role` owed, and both halves of it are +/// conditional writes scoped to *this* user (`teacher = $usr`, +/// `$usr IN teachers`), so a legitimate concurrent assignment of somebody else +/// is untouched — no lock, the repo's existing idiom. Both are run, not just +/// the caller's own: a demoted account may hold neither, and the row this +/// request did not write is exactly the one a lost sweep left behind. +/// +/// A missing user counts as demoted. The ordinary path is one extra read and no +/// write at all. +pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<(), AppError> { + if User::read(target, db) + .await? + .is_some_and(|user| user.get_role().at_least(Role::Teacher)) + { + return Ok(()); + } + crate::domain::class_group::ClassGroup::unassign_everywhere(target, db).await?; + crate::domain::course::Course::unassign_everywhere(target, db).await?; + Err(AppError::Conflict( + "that user was demoted below teacher while this request ran — the assignment was undone; re-read their role and retry", + )) +} + /// If both ends are present, `ends_at` must not precede `starts_at`. Shared by /// everything that carries a time range (events, course sessions). The PATCH /// paths re-check this at write time via @@ -337,6 +372,132 @@ where mod tests { use super::*; + /// The demotion-vs-assign race, driven in the order the race produces it: + /// both assignments are already written (the handler's role check has + /// passed), *then* the account drops below `teacher` with no sweep — which + /// is exactly what `set_role`'s one-shot sweep leaves behind when it runs + /// before the write. The post-write re-read must undo both columns and + /// refuse; with the account still staff it must undo nothing at all. + /// + /// Asserted on stored state, never on a return value: the in-memory engine + /// forges those (see [`crate::domain::cap`]). + #[tokio::test] + async fn undo_if_demoted_repairs_both_assignments_or_neither() { + use crate::domain::class_group::{ClassGroup, ClassName}; + use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + use crate::domain::user::{Password, Username}; + + let db = crate::database::init_mem().await.unwrap(); + let office = UserId::from_key("office"); + let teacher = User::create( + Username::try_new("ada").unwrap(), + Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(), + &db, + ) + .await + .unwrap() + .set_role(Role::Teacher, &db) + .await + .unwrap(); + + let assigned = async |db: &Database| { + let class = ClassGroup::create( + &office, + ClassName::try_new("9-A").unwrap(), + None, + None, + Some(teacher.get_id().clone()), + db, + ) + .await + .unwrap(); + let course = Course::create( + &office, + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + db, + ) + .await + .unwrap() + .assign_teacher(teacher.get_id(), db) + .await + .unwrap(); + (class, course) + }; + /// `(the class's stored teacher, the course's stored teacher list)`. + async fn stored( + class: &crate::domain::class_group::ClassGroupId, + course: &crate::domain::course::CourseId, + db: &Database, + ) -> (Option, Vec) { + ( + ClassGroup::read(class, db) + .await + .unwrap() + .unwrap() + .get_teacher() + .cloned(), + Course::read(course, db) + .await + .unwrap() + .unwrap() + .get_teachers() + .to_vec(), + ) + } + + // Still staff: one read, and not a single write. + let (class, course) = assigned(&db).await; + undo_if_demoted(teacher.get_id(), &db) + .await + .expect("an account that is still teacher+ keeps what it was given"); + assert_eq!( + stored(class.get_id(), course.get_id(), &db).await, + ( + Some(teacher.get_id().clone()), + vec![teacher.get_id().clone()] + ), + "nothing may be undone while the bar still holds" + ); + + // Demoted with no sweep — the state a lost race leaves. + db.query("UPDATE $usr SET role = 'student'") + .bind(("usr", teacher.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + let refused = undo_if_demoted(teacher.get_id(), &db).await; + assert!( + matches!(refused, Err(AppError::Conflict(message)) if message.contains("demoted")), + "a demotion mid-request must be a 409 naming it: {refused:?}" + ); + assert_eq!( + stored(class.get_id(), course.get_id(), &db).await, + (None, Vec::new()), + "…with both assignments taken back, not just the caller's own" + ); + + // A user that is gone counts as demoted, and the repair is idempotent. + assert!( + undo_if_demoted(&UserId::from_key("ghost"), &db) + .await + .is_err() + ); + assert!(undo_if_demoted(teacher.get_id(), &db).await.is_err()); + assert_eq!( + stored(class.get_id(), course.get_id(), &db).await, + (None, Vec::new()) + ); + } + #[tokio::test] async fn check_time_range_orders_the_ends() { let at = |ms| Some(Timestamp::from_millis(ms)); diff --git a/src/web/users.rs b/src/web/users.rs index 829667b..a94a2c7 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -9,6 +9,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::board::Board; +use crate::domain::class_group::ClassGroup; use crate::domain::class_pump; use crate::domain::course::Course; use crate::domain::parent_link::ParentLink; @@ -399,6 +400,19 @@ async fn set_role( .await? .ok_or(AppError::NotFound)?; let updated = user.set_role(role, &st.db).await?; + // KNOWN GAP (deliberate, not an oversight): the role write above and the + // sweeps below are separate statements, so a sweep that errors answers 500 + // with the role already lowered and some of the old grants still standing. + // Every one of them is idempotent and re-running the same PATCH repairs it, + // and every security gate re-reads the live role rather than trusting a + // swept row — the residue pollutes rosters and lists, it does not grant + // anything. Folding it into one transaction means folding eight tables plus + // `class_pump`'s own transaction and the board-hub publish (an in-process + // side effect that cannot sit inside a database transaction) — see the + // report accompanying this change. The write ordering *within* a request is + // closed from the other end instead: a handler that assigns a teacher-only + // role re-reads the live role after its write ([`super::undo_if_demoted`]), + // so a demotion racing an assignment is caught by whichever side is second. // Roster hygiene: only students enroll, so a non-student sheds all their // enrollment rows (security checks re-read the live role and never // trusted these; this just stops them polluting rosters and counts). @@ -454,6 +468,11 @@ async fn set_role( // rows that grant nothing and still list a demoted user as its teacher. if !role.at_least(Role::Teacher) { Course::unassign_everywhere(&target, &st.db).await?; + // Same story for a class's homeroom teacher (sınıf öğretmeni): only + // teacher+ may hold one, so a demotion clears the column everywhere + // rather than leaving a class section (şube) listing a demoted account + // as its teacher. + ClassGroup::unassign_everywhere(&target, &st.db).await?; } Ok(Json(UserResponse::new(&updated))) } diff --git a/tests/integration.rs b/tests/integration.rs index 50d82e5..72b9560 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -25110,7 +25110,7 @@ async fn a_burst_of_strokes_comes_back_in_mint_order() { assert_eq!(payloads[59], "{\"p\":[59]}"); } -// --- classes (şube) --------------------------------------------------------- +// --- class sections (şube) -------------------------------------------------- /// The class routes' own gates, end to end: who may write, who may not, and /// that the writes really are enrollments. The pump itself is proven in the diff --git a/tests/regress_classes.rs b/tests/regress_classes.rs index e7a555b..67d9bf3 100644 --- a/tests/regress_classes.rs +++ b/tests/regress_classes.rs @@ -1,4 +1,4 @@ -//! Regressions for the class (şube) layer, its enrollment side, and the sweep a +//! Regressions for the class section (şube) layer, its enrollment side, and the sweep a //! role change runs. Every test here pins a defect that shipped: a link left //! pointing at a deleted course, the refusal that misnamed it, a hand enroll a //! class could still undo, and the two-transaction role sweep. @@ -6,7 +6,7 @@ mod common; use axum::http::StatusCode; -use common::{app_and_db, create_course, login_as, me_id, send}; +use common::{Res, app_and_db, create_course, login_as, me_id, send, total}; use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use hezarfen_backend::database::Database; use hezarfen_backend::domain::class_course::ClassCourse; @@ -64,6 +64,7 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() { ClassName::try_new("9-A").unwrap(), None, None, + None, &db, ) .await @@ -503,6 +504,7 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() { ClassName::try_new("9-A").unwrap(), None, None, + None, &db, ) .await @@ -570,6 +572,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() { ClassName::try_new("9-A").unwrap(), None, None, + None, &db, ) .await @@ -623,6 +626,7 @@ async fn a_class_refuses_the_member_past_its_ceiling() { ClassName::try_new("9-A").unwrap(), None, None, + None, &db, ) .await @@ -689,6 +693,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { ClassName::try_new("9-A").unwrap(), None, None, + None, &db, ) .await @@ -746,6 +751,7 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { ClassName::try_new("9-B").unwrap(), None, None, + None, &db, ) .await @@ -772,3 +778,787 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { 0 ); } + +// ---- homeroom teacher (sınıf öğretmeni) ------------------------------------ + +/// Create a class as `cookie` (asserts 201); returns the whole response body. +async fn create_class(app: &axum::Router, cookie: &str, body: serde_json::Value) -> Res { + let res = send(app, "POST", "/classes", Some(cookie), Some(body)).await; + assert_eq!(res.status, StatusCode::CREATED, "create class"); + res +} + +/// The `teacher` block of `GET /classes/{id}`, straight out of the store's own +/// read path — never off the write's response body. +async fn stored_teacher(app: &axum::Router, cookie: &str, class: &str) -> serde_json::Value { + let res = send(app, "GET", &format!("/classes/{class}"), Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "GET /classes/{class}"); + res.body["teacher"].clone() +} + +/// The whole write contract for the homeroom teacher over HTTP: set at create, +/// re-set and cleared by PATCH (both `null` and `""`), and — the one a +/// whole-row save would break — untouched by a PATCH of another field. The +/// response always names the person, never a bare id. +#[tokio::test] +async fn the_homeroom_teacher_round_trips_through_create_and_patch() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let other = login_as(&app, &db, "other", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let other_id = me_id(&app, &other).await; + + let created = create_class( + &app, + &manager, + json!({ "name": "9-A", "teacher_id": teacher_id }), + ) + .await; + let class = created.body["id"].as_str().unwrap().to_string(); + assert_eq!(created.body["teacher"]["id"], json!(teacher_id)); + assert_eq!( + created.body["teacher"]["username"], + json!("teacher"), + "the response must name the teacher, not echo an id" + ); + assert_eq!( + stored_teacher(&app, &manager, &class).await["id"], + json!(teacher_id) + ); + + // A name-only PATCH must leave the teacher exactly where it is. + let renamed = send( + &app, + "PATCH", + &format!("/classes/{class}"), + Some(&manager), + Some(json!({ "name": "9-B" })), + ) + .await; + assert_eq!(renamed.status, StatusCode::OK); + assert_eq!(renamed.body["teacher"]["id"], json!(teacher_id)); + assert_eq!( + stored_teacher(&app, &manager, &class).await["id"], + json!(teacher_id) + ); + + // …and a teacher-only PATCH must leave the name alone. + let moved = send( + &app, + "PATCH", + &format!("/classes/{class}"), + Some(&manager), + Some(json!({ "teacher_id": other_id })), + ) + .await; + assert_eq!(moved.status, StatusCode::OK); + assert_eq!(moved.body["name"], json!("9-B")); + assert_eq!(moved.body["teacher"]["id"], json!(other_id)); + + // Both spellings of "no teacher" land on the same stored row. + for clear in [json!(null), json!("")] { + send( + &app, + "PATCH", + &format!("/classes/{class}"), + Some(&manager), + Some(json!({ "teacher_id": other_id })), + ) + .await; + let cleared = send( + &app, + "PATCH", + &format!("/classes/{class}"), + Some(&manager), + Some(json!({ "teacher_id": clear })), + ) + .await; + assert_eq!(cleared.status, StatusCode::OK, "clearing with {clear}"); + assert_eq!( + cleared.body["teacher"], + json!(null), + "clearing with {clear}" + ); + assert_eq!(stored_teacher(&app, &manager, &class).await, json!(null)); + } +} + +/// A student is not staff: naming one as the homeroom teacher is a `400` on +/// both write paths, and so is an id that names nobody at all. +#[tokio::test] +async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let student = login_as(&app, &db, "ali", "student").await; + let student_id = me_id(&app, &student).await; + let ghost = "01J8XZ0K3Q8G7X2M4N5P6R7S8T"; + + for bad in [student_id.as_str(), ghost] { + let refused = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A", "teacher_id": bad })), + ) + .await; + assert_eq!(refused.status, StatusCode::BAD_REQUEST, "create with {bad}"); + } + assert_eq!( + rows("SELECT VALUE id FROM class_group", &db).await, + 0, + "a refused create may write no class" + ); + + let class = create_class(&app, &manager, json!({ "name": "9-A" })) + .await + .body["id"] + .as_str() + .unwrap() + .to_string(); + for bad in [student_id.as_str(), ghost] { + let refused = send( + &app, + "PATCH", + &format!("/classes/{class}"), + Some(&manager), + Some(json!({ "name": "9-B", "teacher_id": bad })), + ) + .await; + assert_eq!(refused.status, StatusCode::BAD_REQUEST, "patch with {bad}"); + } + // The refused PATCH carried a name too — it must not have landed either. + let stored = send( + &app, + "GET", + &format!("/classes/{class}"), + Some(&manager), + None, + ) + .await; + assert_eq!(stored.body["name"], json!("9-A")); + assert_eq!(stored.body["teacher"], json!(null)); +} + +/// End-to-end demotion: `PATCH /users/{id}/role` down to `student` clears that +/// account off every class it homeroomed, and off nobody else's — a demoted +/// user may hold no section. +#[tokio::test] +async fn a_demotion_clears_the_homeroom_teacher_everywhere() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "mudur", "admin").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let keeper = login_as(&app, &db, "keeper", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let keeper_id = me_id(&app, &keeper).await; + + let mut held = Vec::new(); + for name in ["9-A", "9-B"] { + held.push( + create_class( + &app, + &admin, + json!({ "name": name, "teacher_id": teacher_id }), + ) + .await + .body["id"] + .as_str() + .unwrap() + .to_string(), + ); + } + let untouched = create_class( + &app, + &admin, + json!({ "name": "10-A", "teacher_id": keeper_id }), + ) + .await + .body["id"] + .as_str() + .unwrap() + .to_string(); + + let demoted = send( + &app, + "PATCH", + &format!("/users/{teacher_id}/role"), + Some(&admin), + Some(json!({ "role": "student" })), + ) + .await; + assert_eq!(demoted.status, StatusCode::OK); + + for class in &held { + assert_eq!( + stored_teacher(&app, &admin, class).await, + json!(null), + "a demoted user may not stay a class's homeroom teacher" + ); + } + assert_eq!( + stored_teacher(&app, &admin, &untouched).await["id"], + json!(keeper_id), + "…and nobody else's assignment may move" + ); +} + +// ---- a student's own section ------------------------------------------------ + +/// `GET /classes/me` is the one class read a student can make: it returns +/// exactly their own memberships (with the homeroom teacher joined on), it does +/// not fall through to the teacher-only `GET /classes/{id}`, and it pages. +#[tokio::test] +async fn a_student_reads_exactly_their_own_classes() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let student = login_as(&app, &db, "ali", "student").await; + let lonely = login_as(&app, &db, "veli", "student").await; + let teacher_id = me_id(&app, &teacher).await; + let student_id = me_id(&app, &student).await; + + // Added oldest-first, with a gap wide enough that `added_at` really + // orders them — the composite ids break a tie in account-ULID order, which + // says nothing about who joined first. + let mut mine = Vec::new(); + for name in ["9-A", "9-B"] { + let class = create_class( + &app, + &manager, + json!({ "name": name, "teacher_id": teacher_id }), + ) + .await + .body["id"] + .as_str() + .unwrap() + .to_string(); + let added = send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&manager), + Some(json!({ "user_id": student_id })), + ) + .await; + assert_eq!(added.status, StatusCode::CREATED); + mine.push(class); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + // A class the student is *not* in must never show up. + create_class(&app, &manager, json!({ "name": "10-A" })).await; + + let res = send(&app, "GET", "/classes/me", Some(&student), None).await; + assert_eq!( + res.status, + StatusCode::OK, + "/classes/me must not fall through to the teacher-only /classes/{{id}}" + ); + assert!( + res.body.get("items").is_some() && res.body.get("total").is_some(), + "…which is what a page envelope, rather than one class object, proves: {:?}", + res.body + ); + assert_eq!(total(&res.body), 2); + let ids = |body: &serde_json::Value| -> Vec { + body["items"] + .as_array() + .unwrap() + .iter() + .map(|item| item["id"].as_str().unwrap().to_string()) + .collect() + }; + // Unsorted: the documented order is newest membership first, so the class + // joined *second* must lead. Sorting here is what made this assertion dead. + assert_eq!( + ids(&res.body), + vec![mine[1].clone(), mine[0].clone()], + "exactly the student's own classes, newest membership first" + ); + assert_eq!( + res.body["items"][0]["teacher"]["username"], + json!("teacher"), + "the homeroom teacher must be resolved, not left a bare id" + ); + // The office's account names stay out of a student's reach. + assert_eq!( + res.body["items"][0]["creator"], + json!(null), + "a student may not learn who in the office created their class" + ); + let staff = send(&app, "GET", "/classes/me", Some(&manager), None).await; + assert_eq!(total(&staff.body), 0, "staff are never class members"); + let staff_view = send( + &app, + "GET", + &format!("/classes/user/{student_id}"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + staff_view.body["items"][0]["creator"]["username"], + json!("manager"), + "…but teacher+ still sees the creator" + ); + + // The window must actually move: the second page is the *older* class, not + // the first page again. Asserting only the length let `offset` be ignored. + let paged = send( + &app, + "GET", + "/classes/me?limit=1&offset=1", + Some(&student), + None, + ) + .await; + assert_eq!(paged.status, StatusCode::OK); + assert_eq!(total(&paged.body), 2); + assert_eq!( + ids(&paged.body), + vec![mine[0].clone()], + "?offset=1 must return the second row of the full order, not the first" + ); + let first = send( + &app, + "GET", + "/classes/me?limit=1&offset=0", + Some(&student), + None, + ) + .await; + assert_eq!(ids(&first.body), vec![mine[1].clone()]); + + // A student in no class gets an empty page, not a 404. + let empty = send(&app, "GET", "/classes/me", Some(&lonely), None).await; + assert_eq!(empty.status, StatusCode::OK); + assert_eq!(total(&empty.body), 0); + assert!(empty.body["items"].as_array().unwrap().is_empty()); +} + +/// `GET /classes/user/{id}` follows the observer rule the per-student reports +/// use: teacher+ and a *linked* parent may read it, everyone else — an +/// unlinked parent, another student — is a `403` with no existence leak. +#[tokio::test] +async fn only_staff_and_a_linked_parent_read_another_users_classes() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "mudur", "admin").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let student = login_as(&app, &db, "ali", "student").await; + let peer = login_as(&app, &db, "veli", "student").await; + let parent = login_as(&app, &db, "anne", "parent").await; + let stranger = login_as(&app, &db, "baba", "parent").await; + let student_id = me_id(&app, &student).await; + let parent_id = me_id(&app, &parent).await; + let teacher_id = me_id(&app, &teacher).await; + + let class = create_class( + &app, + &admin, + json!({ "name": "9-A", "teacher_id": teacher_id }), + ) + .await + .body["id"] + .as_str() + .unwrap() + .to_string(); + send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&admin), + Some(json!({ "user_id": student_id })), + ) + .await; + let linked = send( + &app, + "POST", + &format!("/users/{parent_id}/students"), + Some(&admin), + Some(json!({ "user_id": student_id })), + ) + .await; + assert!( + linked.status.is_success(), + "link student: {}", + linked.status + ); + + let path = format!("/classes/user/{student_id}"); + // `creator` is the half of this route that is not about who may read it: + // a linked parent is below teacher+, so the office account that made the + // class must be hidden from them exactly as it is from their child — while + // the homeroom teacher, which is the point of the read, stays named for + // both. + for (who, cookie, creator) in [ + ("teacher", &teacher, json!("mudur")), + ("linked parent", &parent, json!(null)), + ] { + let res = send(&app, "GET", &path, Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{who} may read"); + assert_eq!(total(&res.body), 1, "{who} sees the class"); + assert_eq!(res.body["items"][0]["id"], json!(class)); + assert_eq!( + res.body["items"][0]["teacher"]["username"], + json!("teacher"), + "{who} must be told who the homeroom teacher is" + ); + let seen = &res.body["items"][0]["creator"]; + match creator.as_str() { + Some(name) => assert_eq!(seen["username"], json!(name), "{who} may see the creator"), + None => assert_eq!( + *seen, + json!(null), + "{who} is below teacher+ and may not learn an office account's name" + ), + } + } + for (who, cookie) in [("unlinked parent", &stranger), ("another student", &peer)] { + let res = send(&app, "GET", &path, Some(cookie), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{who} may not"); + } + + // The pagination envelope, and the 404 a user who does not exist gets. + let paged = send( + &app, + "GET", + &format!("{path}?limit=1&offset=0"), + Some(&teacher), + None, + ) + .await; + assert_eq!(paged.status, StatusCode::OK); + assert_eq!(total(&paged.body), 1); + assert_eq!(paged.body["items"].as_array().unwrap().len(), 1); + let ghost = send( + &app, + "GET", + "/classes/user/01J8XZ0K3Q8G7X2M4N5P6R7S8T", + Some(&teacher), + None, + ) + .await; + assert_eq!(ghost.status, StatusCode::NOT_FOUND); +} + +/// The documented decision on a `class_member` row whose class is gone: the +/// page still *counts* it (the window was cut from the membership rows) but +/// skips it from `items`, and answers `200` rather than a `500` or a short +/// page that silently loses the rest. Unreachable through the API — the class +/// delete guard refuses while members exist — so the row is forced here the +/// only way it could ever arise, a class row vanishing under its memberships. +#[tokio::test] +async fn a_membership_whose_class_is_gone_is_counted_but_skipped() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let student = login_as(&app, &db, "ali", "student").await; + let student_id = me_id(&app, &student).await; + + let mut classes = Vec::new(); + for name in ["9-A", "9-B"] { + let class = create_class(&app, &manager, json!({ "name": name })) + .await + .body["id"] + .as_str() + .unwrap() + .to_string(); + let added = send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&manager), + Some(json!({ "user_id": student_id })), + ) + .await; + assert_eq!(added.status, StatusCode::CREATED); + classes.push(class); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + // The guard would refuse this, so it is spelled as the raw row loss it + // stands in for; the membership row is deliberately left behind. + db.query("DELETE type::record('class_group', $key)") + .bind(("key", classes[0].clone())) + .await + .unwrap() + .check() + .unwrap(); + + let res = send(&app, "GET", "/classes/me", Some(&student), None).await; + assert_eq!( + res.status, + StatusCode::OK, + "a dangling membership is not a 500" + ); + assert_eq!( + total(&res.body), + 2, + "total counts the membership rows, which is what the window was cut from" + ); + let items = res.body["items"].as_array().unwrap(); + assert_eq!( + items.len(), + 1, + "the class that is gone is skipped, not faked" + ); + assert_eq!( + items[0]["id"], + json!(classes[1]), + "…and the surviving class is still there, in order" + ); +} + +// ---- the demotion-vs-assign race, made deterministic ----------------------- +// +// The window is between a handler's "this account is teacher+" check and the +// write that records it: a `PATCH /users/{id}/role` landing in there sweeps +// nothing (the rows it would sweep are not written yet) and nothing ever +// re-sweeps, so the assignment would stand forever naming a non-teacher. Every +// such handler therefore re-reads the live role *after* its write +// (`web::undo_if_demoted`). +// +// Racing it from a second task would be a coin flip the in-memory engine is +// known to lie about, so the demotion is injected by the database itself: a +// `DEFINE EVENT` on the very table the handler writes fires *inside* that +// write, which is exactly "after the role check, before the re-read", every +// single time. Nothing in `src/` knows about it — the seam is the schema, and +// these tests are what stop the three `undo_if_demoted` calls being deleted. + +/// Demote `user` from inside the next write to `table`, the instant it lands. +async fn demote_during_writes_to(table: &str, event: &str, user: &str, db: &Database) { + db.query(format!( + "DEFINE EVENT demote_mid_write ON TABLE {table} WHEN $event = '{event}' THEN {{ \ + UPDATE type::record('user', '{user}') SET role = 'student'; }};" + )) + .await + .unwrap() + .check() + .unwrap(); +} + +/// The homeroom teacher's live role, straight out of the store. +async fn role_of(user: &str, db: &Database) -> String { + let mut result = db + .query("SELECT VALUE role FROM user WHERE id = type::record('user', $k)") + .bind(("k", user.to_string())) + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap().pop().unwrap() +} + +/// `POST /classes` naming a teacher who is demoted while the row is being +/// written: `409`, and the class is rolled back **whole** — no teacherless +/// class left standing, and no reference stranded on the term it linked (which +/// would make that term undeletable forever). +#[tokio::test] +async fn a_create_whose_teacher_is_demoted_mid_write_rolls_back_whole() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let term = send( + &app, + "POST", + "/terms", + Some(&manager), + Some(json!({ "name": "2026", "starts_at": 100, "ends_at": 200 })), + ) + .await; + assert_eq!(term.status, StatusCode::CREATED); + let term_id = term.body["id"].as_str().unwrap().to_string(); + + demote_during_writes_to("class_group", "CREATE", &teacher_id, &db).await; + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A", "teacher_id": teacher_id, "term_id": term_id })), + ) + .await; + + assert_eq!( + res.status, + StatusCode::CONFLICT, + "a teacher demoted mid-write must not be recorded as one: {:?}", + res.body + ); + assert!( + res.body["error"].as_str().unwrap().contains("demoted"), + "the 409 must say why: {:?}", + res.body + ); + assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired"); + assert_eq!( + rows("SELECT VALUE id FROM class_group", &db).await, + 0, + "the 409 promises nothing was created — so nothing may be there" + ); + assert_eq!( + counter("SELECT VALUE class_count ?? 0 FROM term", &db).await, + 0, + "…and least of all a reference stranded on the term" + ); + let freed = send( + &app, + "DELETE", + &format!("/terms/{term_id}"), + Some(&manager), + None, + ) + .await; + assert_eq!( + freed.status, + StatusCode::NO_CONTENT, + "which is the point: the term must still be deletable" + ); +} + +/// `PATCH /classes/{id}` naming a teacher who is demoted while the row is being +/// written: `409`, and the column it just set is taken back. +#[tokio::test] +async fn a_patch_whose_teacher_is_demoted_mid_write_undoes_the_column() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let class = create_class(&app, &manager, json!({ "name": "9-A" })) + .await + .body["id"] + .as_str() + .unwrap() + .to_string(); + + demote_during_writes_to("class_group", "UPDATE", &teacher_id, &db).await; + let res = send( + &app, + "PATCH", + &format!("/classes/{class}"), + Some(&manager), + Some(json!({ "teacher_id": teacher_id })), + ) + .await; + + assert_eq!( + res.status, + StatusCode::CONFLICT, + "a teacher demoted mid-write must not be recorded as one: {:?}", + res.body + ); + assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired"); + assert_eq!( + counter( + "SELECT VALUE (IF teacher = NONE { 0 } ELSE { 1 }) FROM class_group", + &db + ) + .await, + 0, + "the assignment this request wrote must be taken back" + ); + // The class itself is untouched — only the column this request set is. + let stored = send( + &app, + "GET", + &format!("/classes/{class}"), + Some(&manager), + None, + ) + .await; + assert_eq!(stored.status, StatusCode::OK); + assert_eq!(stored.body["name"], json!("9-A")); + assert_eq!(stored.body["teacher"], json!(null)); +} + +/// The same guard on the other assignment it protects: +/// `POST /courses/{id}/teachers` for an account demoted while the list is being +/// written is a `409`, with the assignment dropped again. +#[tokio::test] +async fn a_course_assignment_whose_teacher_is_demoted_mid_write_is_undone() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let course = create_course(&app, &manager, "algebra").await; + + demote_during_writes_to("course", "UPDATE", &teacher_id, &db).await; + let res = send( + &app, + "POST", + &format!("/courses/{course}/teachers"), + Some(&manager), + Some(json!({ "user_id": teacher_id })), + ) + .await; + + assert_eq!( + res.status, + StatusCode::CONFLICT, + "a teacher demoted mid-write must not be recorded as one: {:?}", + res.body + ); + assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired"); + assert_eq!( + counter("SELECT VALUE array::len(teachers ?? []) FROM course", &db).await, + 0, + "the assignment must be dropped again, not left granting nothing" + ); +} + +/// The other end of that rollback: if the delete is ever *refused* — the class +/// took a member or a course between its own create and the rollback — the +/// class is still there, so answering the `409` whose text promises "nothing +/// was created" would be a lie about the stored state. It must surface as an +/// internal error instead. +/// +/// Unreachable through the API (the class is one statement old and both of its +/// counters are absent), so the seam does both halves at once: demote the +/// teacher *and* tick `class_member_count` inside the very write that creates +/// the row, which is the only ordering that reaches this branch. +#[tokio::test] +async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager", "manager").await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + + db.query(format!( + "DEFINE EVENT demote_and_occupy ON TABLE class_group WHEN $event = 'CREATE' THEN {{ \ + UPDATE type::record('user', '{teacher_id}') SET role = 'student'; \ + UPDATE $after.id SET class_member_count = 1; }};" + )) + .await + .unwrap() + .check() + .unwrap(); + + let res = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A", "teacher_id": teacher_id })), + ) + .await; + + assert_eq!( + res.status, + StatusCode::INTERNAL_SERVER_ERROR, + "a rollback that could not happen may not be reported as one: {:?}", + res.body + ); + assert_eq!( + rows("SELECT VALUE id FROM class_group", &db).await, + 1, + "the class really is still there — which is why the 409 would have lied" + ); + assert_eq!( + counter( + "SELECT VALUE (IF teacher = NONE { 0 } ELSE { 1 }) FROM class_group", + &db + ) + .await, + 0, + "…though the demoted teacher is off it, the undo having run first" + ); +}