forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on af331ecc8a4a0c661bcdbc905b95bb2cf77a72deFiltered to src/web/mod.rsClear filter

2026-09-11

Merge branch 'layer-split/class'Ahmet Kaan Gümüş · dc8a635
Merge branch 'layer-split/class'

# Conflicts:
#	src/db/cap.rs
#	src/domain/class_group.rs
#	src/domain/event.rs
#	src/web/classes.rs
#	src/web/users.rs
#	tests/regress_role_sweep.rs

2026-09-05

✨ feat: builder sells modules per school, one at a time or in batchesAhmet Kaan Gümüş · c78e41a
✨ feat: builder sells modules per school, one at a time or in batches

`GET|PATCH /schools/{slug}/modules`, `POST|DELETE /schools/{slug}/modules/{module}`;
a batch names modules or whole packages, resolves to one set, is validated
against the dependency graph once and written once, or not at all. Public
`GET /modules/catalog` lists modules, packages and requirements; a school
reads its own set at `GET /modules`. Schools can be created with a narrowed
set.
✨ feat: per-school modules; a disabled module answers 403 on every route in its nestAhmet Kaan Gümüş · 5d7f87c
✨ feat: per-school modules; a disabled module answers 403 on every route in its nest

Twenty-one modules, one per router nest, with an explicit dependency graph
derived from the record links (exams need courses and subjects, marks need
exams, …) and four packages for the catalog. The enabled set lives on the
school's control row and rides the tenant resolution that already happens
once per request; every nest carries a route_layer gate, the four child
creates inside /courses are gated by their own module, and the AI blob
stream refuses `module_disabled` when course notes are off.
✨ feat: builder API — the vendor creates, suspends, enters and deletes schoolsAhmet Kaan Gümüş · 1ab298d
✨ feat: builder API — the vendor creates, suspends, enters and deletes schools

`POST /builder/login|logout`, `GET /builder/me`; `POST|GET /schools`,
`GET|PATCH|DELETE /schools/{slug}`, `POST /schools/{slug}/admin-password`,
`POST /schools/{slug}/enter`. Builder sessions live in the control database
behind their own strict per-IP login tier; deleting a school drops its
database and its files subtree.
✨ feat: one database per school behind a control registry; login names the schoolAhmet Kaan Gümüş · b7dfc0c
✨ feat: one database per school behind a control registry; login names the school

Namespace `hezarfen` now holds one DATABASE per school (name = slug) plus a
`control` database with the school registry, builder accounts and builder
sessions. `Tenants` keeps one separately-connected handle per school; the
shadow `web::tenant_state::State` resolves the school from the
`<slug>.<token>` cookie so every handler's `st.db` is school-scoped by
construction. `POST /auth/login` / `register` carry `school`; a suspended
school answers 403 everywhere. `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed the
vendor account; the boot admin seed is gone. No customers, no compat shims.

2026-08-19

✨ feat: course notes uploadable by responsible teacher+Ahmet Kaan Gümüş · 6b1748c
✨ feat: course notes uploadable by responsible teacher+

Mirror of the personal-note stack scoped to a course: course_note +
course_note_file tables, /course-notes routes (POST/GET list?course=,
GET/PATCH/DELETE /{id}, POST/GET /{id}/files, GET/DELETE /{id}/files/{fid}).

Write = can_manage_course (creator, assigned teacher, manager+; live
Teacher role floor). Read = can_view_course (manage or enrolled).
Blob-first upload, cap via cap::claim_and_create (MAX_COURSE_NOTE_FILES),
create-vs-deleted-course refused via cap::touch_and_create, course delete
cascades note/file rows and unlinks blobs.

Tests: 8 integration cases (authz matrix, demoted creator, cross-course
file IDOR, cap 409/413, blob cleanup, cascade 404), race-contract cases
in regress_course_child_orphans, domain unit tests. README Endpoints
table regenerated via doc_sync; Layout updated.

2026-08-12

🤖 feat: let ai services read the api over quicAhmet Kaan Gümüş · b0af858
🤖 feat: let ai services read the api over quic

A service now opens a bidirectional stream of its own, writes one
ApiRequest and reads one ApiResponse: the bridge validates it and
dispatches it into the real router, so a service asks for school data
over the same handlers the REST API serves instead of getting a second
copy of them.

The router is handed over *before* the outer layers, because a synthetic
QUIC request is not a browser request from an IP: it has no address to
bill the per-IP limiter (it would drain the shared unknown-client
budget), and ETag/CORS are browser concerns. That skips the db guard too,
so this path runs the same liveness check and REQUEST_TIMEOUT_SECS
deadline itself.

Validation order is pinned, since it decides what is refused before the
router ever sees it: method (absent or GET) → the AI_API_ALLOWLIST path
→ the principal, loaded live from the database so a stale id cannot act
as a deleted user. Anything the router itself answered — 401, 403, 404
included — rides back as Ok with that status; the Err codes are
bridge-level refusals only: malformed, method_not_allowed,
path_not_allowed, unknown_user, unavailable, not_json, too_large.

The control-stream handshake and the backend→service dispatch are
untouched, and a service that never opens a second stream sees no
difference at all.

2026-08-02

fix: 🔩 clear the deferred backlog and ship class phase 2Ahmet Kaan Gümüş · afff737
fix: 🔩 clear the deferred backlog and ship class phase 2

Ten defects and two features, worked as one series because the doc
surfaces and the const table are shared.

Defects closed:

- Cross-exam answer-key leak. The bank copies `correct` into every
  instantiation, so reviewing exam A handed out the key to a question
  the caller was still writing in exam B. Review now blanks those
  questions rather than closing: the join matches on `from_bank` AND
  `banked_as` (a question can carry both — instantiated, then re-saved
  to the bank — so a coalesce misses a copy), redacting `correct`, the
  correctness flag and that question's `auto_score` share. Keyed on the
  template, never the exam, so the rest of the review reads normally.
- `set_role` was not atomic with its sweeps. The role write and every
  grant it invalidates now commit as one transaction; the board rooms
  are told after COMMIT from the cascade's own result slot. Built
  best-of-N; the losing charter left the one sweep outside whose failure
  strands an event seat no route can free.
- Board rosters held below-student ids, which 400d the creator's next
  roster PATCH. Repaired at boot, and a PATCH may now send back the
  roster it was served: an id already present that stopped qualifying is
  dropped, a new one still refused.
- `note_file` blobs leaked. The delete transaction returns the rows it
  removed and the handler unlinks exactly those, not a pre-read snapshot.
- Rate limiting failed open on a saturated map. Never-seen clients now
  share one metered overflow budget instead of arriving unmetered.
- Whiteboards: `GET /boards` takes `?open=`, `/strokes` no longer leaks
  a clear marker the socket filters out, and a locked board refuses its
  creator's clear (409) — the lock now means one thing on every path.
- Blueprint skips named the wrong record: `Attached::Gone` was two facts
  under one name, split into `Gone` (class) and `PivotGone` (course).

Features:

- Event audience `kind=class` — live from `class_member`, membership
  checked in one select because the (class, user) pair is the row id.
- Grade blueprints: a grade's course template, retro-pumped best-effort
  with a skip list. Attachments carry a provenance tag, so removal
  spares what a human placed. A course deleted out from under a
  blueprint is pruned from the template by the pump that finds it.

Forcing functions, because a hand-kept copy drifts:

- `protected_routes_require_session` is derived from the emitted
  OpenAPI: 248 -> 254 operations swept, was 80 typed by hand.
- Every JSON-bodied operation declares 422 (74 sites), pinned both ways
  — and multipart routes, which answer 400, are pinned to NOT declare it.
- The SurrealQL registration-freeze guard is pinned against the Rust it
  copies; both mutations of it fail the test.
- `migration_mark` gates one-time backfills. The roster repair rescanned
  every board against every user on every boot (773ms at 300/2000 with
  nothing to write); it is now skipped once done.

Verified by a three-lens verifier panel — which caught the `banked_as`
half of the answer-key leak by executing a probe, after the first fix
had been reported complete — and by a podman boot against the existing
volume: both new fields defined, the marker written, boot 2 skipping the
scan, and the live API answering on the new routes.
feat: 🧑‍🏫 give a class section a homeroom teacher and open it to studentsAhmet Kaan Gümüş · e590b84
feat: 🧑‍🏫 give a class section a homeroom teacher and open it to students

Two gaps in the class-section layer, closed together because the
second is what makes the first worth storing: a section could name no
homeroom teacher, and a student could never learn which section they were
in — every /classes route was teacher+, so the layer was invisible to the
people inside it.

A section carries an optional `teacher`. The named account must be
teacher+, `null` and `""` both clear it, and an omitted field is left
alone rather than re-stated from the caller's snapshot. The column is
additive: rows written before it carry no key at all, which reads back
as null, so nothing is backfilled and no whole-row write coerces a
counter. A demotion clears the column everywhere — only teacher+ may
hold a section, and the sweep set_role already ran for course staffing
now runs for sections too.

Two reads sit outside the teacher+ bar. GET /classes/me serves any
authenticated caller their own section; GET /classes/user/{user} serves
teacher+ or a linked parent, through the same observer gate marks,
attendance and pomodoro use — which 403s before it 404s, so a parent
never gets an existence oracle.

Opening those reads meant the response could no longer carry `creator`.
A section's creator is always manager+, and below teacher+ that identity
was unreachable: GET /users is admin-only and /users/search is teacher+.
So `creator` is null for those callers and the join never even fetches
it, which keeps the response and the person map from drifting apart.

The role bar was a read-then-write with nothing between them. A demotion
landing in that window left the account homeroom teacher forever, since
its sweep had already run and matched nothing — and course assignment
had carried the same hole since it was written. Both now re-read the
live role after the write and undo the assignment with a 409. A create
that loses this way rolls the whole section back rather than leaving a
teacherless one standing, and the rollback releases the term reference
inside its own transaction, so no term is left undeletable. A rollback
the delete guard refuses is a 500, not a 409 whose text promises nothing
was created.

Every guard here is pinned by a test that fails when the guard is
removed, including the three race sites: a DEFINE EVENT on the table
being written fires inside the handler's own write, which is exactly the
window between the role check and the re-read. No production code knows
the seam exists.

Verified against the real volume: the migration applies to a database
whose section rows predate the column, those rows come back byte-identical
with every refcount intact, a second boot changes nothing, and both new
reads answer correctly on stored data.

The English prose calls this a class section throughout, keeping şube as
a parenthetical gloss — the word has a plain equivalent and the docs were
carrying the Turkish as though it did not.

Known and left: can_manage_course still trusts Course.creator without
re-reading the live role, so a demoted creator keeps course-management
reads — its own series. set_role writes the role before its sweeps and
they are not one transaction; every sweep is idempotent and grants
nothing, so a re-sent PATCH repairs the residue.

2026-08-01

2026-07-31

chore: 🧵 fold the two rooms' shared plumbing into src/web/room.rsAhmet Kaan Gümüş · 6208c97
chore: 🧵 fold the two rooms' shared plumbing into src/web/room.rs

The exam room and the board room share the plumbing around their difference,
not the difference itself: how a frame goes out, how an incoming message is
classified, how an `AppError` becomes words a client may read, and how a
correlation id is echoed back untouched. Both now import that one copy.

Behaviour-preserving on the exam side: `public_message` interpolates the room
label, so "exam room: database reconnecting", "exam room: database timed out"
and "exam room error: {err}" come out byte-identical, and all ten
`exam_room_*` e2e tests stay green.

The `select!` loops, the pre-upgrade gates and presence stay per-room on
purpose — room.rs names each one and why. The boards tag description now
documents the room itself: the 404 door, current-epoch replay,
persist-then-publish, and a `forbidden` that keeps the socket.
feat: 🖌️ open the live board room over a WebSocketAhmet Kaan Gümüş · b9f3988
feat: 🖌️ open the live board room over a WebSocket

`GET /boards/{id}/ws` is the drawing half of the whiteboard: one socket per
participant, persist-then-publish so the fan-out can never carry a mark the
database refused, and a join that replays the current epoch only — a clear
bumps the epoch, it never deletes.

A `Lagged` receiver is the one failure that would corrupt a canvas silently,
so it says so and re-serves the whole current epoch rather than diffing from
a cursor whose gap is exactly what is unknown.

Every gate runs before the upgrade, so a stranger gets a 404 status and not
an instant close, and the roster is re-read on every stroke, clear and lock:
a frame is the prompt, the row is the authority.
feat: 🖍️ collaborative whiteboard domain, REST and limitsAhmet Kaan Gümüş · 5dfce55
feat: 🖍️ collaborative whiteboard domain, REST and limits

Boards are an ad-hoc invite list: the creator names participants, and
every participant draws. Clearing, locking, closing and deleting are the
creator's alone.

Strokes are an append-only log and a clear NEVER deletes — it bumps the
board's epoch, so the live canvas empties while the whole history stays
replayable. The clear marker row doubles as the epoch index, carrying the
epoch it closed and that epoch's final stroke count, which is why there
is no epochs table.

Growth is bounded by two counters claimed together in one conditional
write: epoch_stroke_count resets on a clear and caps the live canvas
(recoverable — clear and keep drawing), while total_stroke_count never
resets and stamps closed_at when the lifetime cap is hit, leaving the
board permanently read-only but fully readable. board_count on user
bounds the open-a-new-board escape hatch.

Outsiders get 404 everywhere so a board's existence never leaks;
a participant lacking creator rights gets 403, since existence has
already been disclosed to them.

The WebSocket room lands separately.

2026-07-29

feat: 💰 track school fees in an append-only ledger of fee plansAhmet Kaan Gümüş · 740e96a
feat: 💰 track school fees in an append-only ledger of fee plans

Fee plans (name + 1..60 installments of {amount_minor, due_at}) are
assigned directly to students; assignment appends every installment as
a charge at once, keyed <plan>_<student>_c<n> so a replay bills nobody.
Payments target one charge, refunds target one credit, and a reversal
undoes only the negative-fold kinds — a mistaken credit is corrected by
a refund, never edited. Balance is never stored; the over-payment cap
folds the target's source subtree under PAYMENT_LOCK and stays advisory
across replicas, which the module doc states outright.

Meal money is untouched: two ledgers, two balances, one shared amount
vocabulary.

2026-07-27

fix: 🪢 guard writes in the database, not the processAhmet Kaan Gümüş · 6c87eca
fix: 🪢 guard writes in the database, not the process

Two replicas are live; every process-local lock silently stopped
meaning anything. Move the invariants into the writes themselves:

- count caps (enroll/register/files/threads) become a counter column
  claimed by UPDATE .. WHERE n < cap (domain/cap.rs), backfilled once,
  decremented in the same transaction as every child delete
- exam freeze, re-draft and grade gates ride inside the write's own
  transaction (IF .. THROW); SESSION/WORK_ENTRY/EVENT locks die, range
  checks fold into the UPDATE's WHERE (FieldUpdate::ordered)
- appointment decisions CAS on status+proposed window+decided_by;
  bank/exam updates CAS on their editable columns
- rate limiter syncs local windows to a shared minute row every 2s,
  fail-open when the database is down
- paged GETs run LIMIT/START in the database (domain/page.rs); sites
  that post-filter in Rust stay web-sliced and say so
- exams.rs (3629 lines) splits into web/exams/{mod,attempts,questions,
  images,review}; image uploads single-source in web/image.rs; the
  bare-seq key rule lives once in domain/key.rs; migration SQL moves
  to migration_sql.rs

Every new guard is mutation-proven (removing it fails a named test).
Migration adds counter columns + rate_limit table; backfill is
one-time, guarded by = NONE, and verified against the live volume.

Traps recorded: SurrealQL 'x ?? 0 > 0' parses as 'x ?? (0 > 0)'; the
embedded mem engine drops one of two concurrent writes yet answers Ok.

2026-07-26

feat: 🍽️ run the canteen: menus, seats, allergens and a ledgerAhmet Kaan Gümüş · fd5cfd1
feat: 🍽️ run the canteen: menus, seats, allergens and a ledger

Published menu calendar (manager+ authors, everyone reads), per-student
dietary profiles that mark conflicting dishes, meal booking with an
optional per-menu capacity, meal attendance, and booking-triggered
billing.

Booking is the charge trigger: reserving a seat stamps a charge at a
price snapshot, so later dish edits never rewrite what a student owes.
No-show still pays, because the kitchen already bought the food, which
is why attendance has no billing effect at all. Money enters only as
admin-recorded credit entries; there is no gateway and no card data.

The ledger is append-only. Cancelling appends a reversal rather than
deleting the charge, balance is always folded from the rows, and the
sign lives in exactly one function. A deletable ledger row would
rewrite a student's financial history leaving no trace.

Charges and reversals are keyed per (booking, attempt) and written
under MENU_LOCK alongside the seat, so a double-click, a retry, or a
cancel cut short mid-flight all settle to one charge and one refund.
That lock is in-process only: a second replica would break every
capacity and charge guarantee here.

A parent may book for a linked student, the first write parent_link
has ever authorised, and sees only seats whose link is still live.

2026-07-25

feat: 📐 publish every hard limit instead of making the frontend guessAhmet Kaan Gümüş · 7152aa9
feat: 📐 publish every hard limit instead of making the frontend guess

Every bound the API enforces lived in one of two places the frontend
could not read: a `pub const` in `constant.rs`, or English prose in a
doc comment ("1–20 entries", "`1`–`100`"). So the frontend kept its own
copy of each number, and the copies drifted the moment one moved.

Two surfaces now carry them, because clients consume them two ways.
`GET /limits` is one JSON document grouped by resource, built by naming
the constants directly — a runtime fetch, no codegen step, and it
carries what OpenAPI holds awkwardly (`reserved_usernames`, the raster
`image_content_types`, the closed role/kind/mode/status sets). The spec
gets the other half: 105 `max_length`/`minimum`/`min_items` bounds on the
request DTOs, which is what `openapi-typescript` and friends turn into
validators for free.

`/limits` is unauthenticated — the register form needs the username and
password bounds before a session exists, and none of it is secret, it is
the same rule a 400 already spells out. It is also exempt from the
database guard: it reads no row, and a frontend booting against a
reconnecting backend is exactly when it needs the contract, not a 503
that sends it back to the hard-coded copy.

Its `rate` group is the one part that is not compile-time. The
rate-limit tiers are env-tunable, so the endpoint reports this server's
live values off `AppState` rather than the shipped defaults — a client
should learn its budget here, not by collecting a 429.

`MAX_CHATBOT_THREAD_TITLE_LEN` moves to `constant.rs` on the way past.
It was private in `domain/chatbot_thread.rs`, reaching neither surface,
and its own comment asked to be moved the next time anyone was here.

Three tests keep both surfaces honest, because each is a hand-kept
mirror and a mirror nothing checks is one that goes stale. A constant
must reach `/limits` or an exclusion list that states why it does not; a
bound may not be declared outside `constant.rs` at all; and the emitted
spec is fetched and compared field by field against the constants —
never against literals, which would just be a third copy that passes
while both are wrong. That last one is unavoidable rather than
belt-and-braces: utoipa 5.5 takes a literal only, so
`max_length = MAX_NOTE_TITLE_LEN` does not compile.

Two duplicated `maximum = 500` literals are now pinned to
`MAX_PAGE_LIMIT`, which `constant.rs` previously only asked a human to
keep in step.
feat: 🔭 let /events and /exams ask for the next rows, not the newestAhmet Kaan Gümüş · b50d48b
feat: 🔭 let /events and /exams ask for the next rows, not the newest

`?limit=100` handed back the 100 most recently created rows, so an event
scheduled for tomorrow that was created before them never appeared. The
only correct call was to drop `limit` entirely — ~3.4 MB per poll — and
the frontend has been paying that on every right-nav tab open.

`?starts_after=` / `?ends_after=` (unix ms, both optional) filter on the
schedule instead, and either one flips the order to soonest-first, so
`limit` finally truncates the right end. `ends_after` keeps rows whose
window has not finished, falling back to `starts_at` when `ends_at` is
null; a row with no schedule at all drops out rather than sorting to an
end. Send neither and the list is untouched — same order, same total —
so nothing has to deploy in lockstep.

For exams the window lands after the visibility split and the draft
retain, so `total` still counts only what the caller may see.
fix: 🏦 choice identity, bank visibility, and whole-row save racesAhmet Kaan Gümüş · ca93ae9
fix: 🏦 choice identity, bank visibility, and whole-row save races

- choices become {id, text} with stable server-minted ids; correct and
  exam_answer.selected name a choice id, and image rows key off it, so
  editing a choice list can no longer re-point an answer key, a picture
  or a student's recorded answer
- a PATCH carrying choices no longer wipes every option picture: it
  drops only rows whose choice id is absent from the new list, and
  omitting choices re-submits the stored ids untouched
- bank templates are private by default; list, read, both image routes
  and from-bank enforce it, and an invisible template 404s rather than
  403s so it cannot be probed for existence
- bank list pages in SQL, newest first, with server-side text and
  visibility filters and a count over the same predicate — it used to
  return the whole table and window it in memory
- text search folds Turkish casing through one shared table used by
  both the Rust needle and the SurrealQL column
- fix: ExamAttempt::finish whole-row-saved a stale struct, so a
  walk-out stamp written by the exam-room socket could be reverted;
  it now writes only finished_at
- fix: BankQuestion::update and Subject::update had the same shape;
  ban it going forward with scripts/check-whole-row-saves.sh and an
  explicit whole-row-save-ok opt-out for rows that cannot be raced
- fix: question_to_bank wrote its back-link holding only BANK_LOCK, so
  a save racing a question edit lost the link
- ids come from the monotonic ULID generator that already existed for
  appointment slots — Ulid::new is not monotonic within a millisecond,
  so newest-first ordering was wrong for same-ms rows
- source_bank splits into from_bank and banked_as; deleting a template
  clears both, deleting a subject clears the template's subject instead
  of blocking the delete
- add refresh-from-bank, frozen once an attempt exists, and a one-query
  per-page usage count
- Exam::delete no longer reads a hardcoded statement slot
- proptest over QuestionSpec::try_new: a key matching a stored choice is
  that choice, any other key is a new option that cannot steal an
  identity

2026-07-24

feat: ⚡ ETag conditional GET so polled reads become cheap 304s - add src/web/etag.rs: global axum middleware on the top-level router (innermost layer) that, for GET + 200 + application/json responses, hashes the body (SipHash, no new dep) into a strong ETag and sets Cache-Control: private, no-cache so the browser revalidates - matching If-None-Match returns 304 with an empty body and the validators kept; frequent frontend polls stop re-sending full payloads - passthrough untouched for non-GET, non-200, non-JSON (image blobs keep their own no-store), and streaming/oversized bodies (size_hint guard) - defensive: a handler that sets its own ETag is passed through without our hash/304 logic, and an existing Cache-Control is never overwritten - responses rebuilt via into_parts/from_parts so Set-Cookie and other handler headers survive on both the 200 and 304 paths - tests/etag.rs: ETag present + revalidation, matching validator → 304 empty, mutations never ETagged, handler-owned headers preservedAhmet Kaan Gümüş · a962778
feat: ⚡ ETag conditional GET so polled reads become cheap 304s
- add src/web/etag.rs: global axum middleware on the top-level router
  (innermost layer) that, for GET + 200 + application/json responses,
  hashes the body (SipHash, no new dep) into a strong ETag and sets
  Cache-Control: private, no-cache so the browser revalidates
- matching If-None-Match returns 304 with an empty body and the
  validators kept; frequent frontend polls stop re-sending full payloads
- passthrough untouched for non-GET, non-200, non-JSON (image blobs keep
  their own no-store), and streaming/oversized bodies (size_hint guard)
- defensive: a handler that sets its own ETag is passed through without
  our hash/304 logic, and an existing Cache-Control is never overwritten
- responses rebuilt via into_parts/from_parts so Set-Cookie and other
  handler headers survive on both the 200 and 304 paths
- tests/etag.rs: ETag present + revalidation, matching validator → 304
  empty, mutations never ETagged, handler-owned headers preserved
✨ feat(exams): add a reusable school-wide question bankAhmet Kaan Gümüş · 8b07cfa
✨ feat(exams): add a reusable school-wide question bank

Teachers weld a question to one exam today, so reusing it next year means
retyping. This adds a bank of question templates that copy into an exam on
demand: a fresh exam question with its own id, images, and answers, so the
copy never shares state with the template (a bank edit can't rewrite a
graded exam). Bank rows carry no exam tie and never freeze.

Reads and instantiate are school-wide (any teacher+); editing or deleting
a template needs ownership (admins aside). A template's subject is origin
metadata only — the same-course rule is checked at instantiate time
against the target exam's course. Both directions exist: author in the
bank, or save an existing exam question back into it.

Routes: CRUD + image slots under /bank-questions, plus
/exams/{id}/questions/from-bank/{bid} (instantiate) and
/exams/{id}/questions/{qid}/to-bank (save). Blob copies are all-or-nothing
and roll back on failure; a subject delete is guarded against live
templates, and bank writes serialize against it under BANK_LOCK. Copies
record provenance (source_bank / source_exam).

2026-07-23

🎨 style(chatbot): rename thread/message off the mail collisionAhmet Kaan Gümüş · 92b232b
🎨 style(chatbot): rename thread/message off the mail collision

The AI chatbot's storage and web layer reused "conversation" and
"chat_message", the latter one underscore away from the human-to-human
mail `message` feature — every reader had to disambiguate two unrelated
tables by eye.

Rename the whole chatbot feature to a `chatbot_*` vocabulary:

  conversation  -> chatbot_thread    (ChatbotThread*, CHATBOT_THREAD_*)
  chat_message  -> chatbot_message   (ChatbotMessage*, CHATBOT_MESSAGE_*)
  /chat/conversations -> /chatbot/threads
  max_chat_conversations -> max_chatbot_threads
  max_chat_message_len   -> max_chatbot_message_len
  chat_history_turns     -> chatbot_history_turns
  RATE_LIMIT_CHAT_PER_MINUTE -> RATE_LIMIT_CHATBOT_PER_MINUTE
  DTO conversation_id -> thread_id

The out-of-process AI-service wire contract is deliberately untouched:
ai/chat.rs payload types, AI_CHAT_CAPABILITY ("chat.reply"), the serde
field names and the hab/1 ALPN stay as-is — other-language services
match on those literals. ai/chat.rs remains "the chat.reply payloads",
a separate concern from the chatbot feature it feeds.

Clean break, no row migration (pre-customer, FE not yet synced): old
conversation/chat_message rows in the volume are abandoned. Frontend
must adopt the new routes, the thread_id field, and the renamed
settings keys.
✨ feat(appointments): teachers publish slots, students book themAhmet Kaan Gümüş · 771936e
✨ feat(appointments): teachers publish slots, students book them

Teachers keep a calendar of availability windows; students and parents
book one with a reason. Publishing a window is not consent to a specific
person and topic, so a booking lands pending until the teacher approves,
rejects, or counter-proposes another time — a counter-proposal returns it
to pending for the requester to accept or decline.

A slot holds one live booking, with occupancy derived under
APPOINTMENT_LOCK rather than stored, so rejecting or cancelling frees the
slot for someone else. No two approved meetings may overlap for the
teacher or the requester.

Cancelling refuses a meeting whose window has opened, so every path that
could land a booking on a past window is closed at the source: booking a
started slot, approving a started window, and proposing a started time
all refuse. Otherwise a booking could exist that nobody was able to
cancel.

Weekly repetition expands eagerly into concrete rows sharing a series id,
capped at 52, so cancelling one occurrence is an ordinary delete.
✨ feat(chat): relay chatbot over the AI bridgeAhmet Kaan Gümüş · b0aa0a1
✨ feat(chat): relay chatbot over the AI bridge

The backend relays between the frontend and an out-of-process AI service:
it owns auth, rate limiting, persistence and payload format, and may
inspect an answer before the frontend sees it. No rule or intent tables —
conversation is free-form.

Two-phase by design. POST persists the pending assistant row *before*
dispatching, then returns 202, so a reload never loses an answer; the
client either polls the message or opens an SSE stream. Both read the
same DTO, so they cannot disagree. Deltas are sliced from the finished
text because hab/1 is unary — the event shape exists so real streaming
drops in later without a client change.

A turn always settles. Every failure after the rows are written marks the
row failed with a machine-readable code, a boot sweep flips rows orphaned
by a restart, and a pending row older than five minutes reads as timed
out — projected at read, never written back, so a slow-but-alive answer
is not raced. An over-long answer is clipped and flagged rather than
dropped; an empty one fails.

Message ids come from a monotonic ULID generator: the two rows one POST
writes share a millisecond routinely, and a random tie-break rendered the
answer above its own question and handed the service [assistant, user],
breaking the documented oldest-first history contract.

The conversation cap counts and creates under a lock — SurrealDB
BEGIN/COMMIT does not serialize cross-record counts, and 16 concurrent
creators over-admitted a cap of 5 to 20 without it.

Every authenticated role may chat, parents included. Foreign threads are
404, never 403.
✨ feat(ai): QUIC bridge for out-of-process AI servicesAhmet Kaan Gümüş · dc49954
✨ feat(ai): QUIC bridge for out-of-process AI services

The AI features live in separate projects, so they need a transport. QUIC:
each request rides its own bidirectional stream on the service's single
long-lived connection, which puts multiplexing in the transport — no
correlation-id bookkeeping, no head-of-line blocking between concurrent
requests, one handshake instead of one per request.

The backend listens and the services dial in, so a service can sit behind
NAT, restart without the backend knowing its address, and scale out by
opening a second connection (each connection is an independent worker).

Protocol "hab/1", also the ALPN so an incompatible service is refused at the
TLS handshake rather than one frame later. Frames are length-prefixed JSON
(u32 big-endian) because the services will not be Rust; the length is checked
against an 8 MiB cap before any buffer is allocated. The control stream
carries Hello/Greeting and then stays open — its closure is the goodbye, so
there is no heartbeat frame, and a silent death is caught by the QUIC idle
timeout.

Routing is least-inflight rather than round-robin: AI request costs are
wildly uneven, and taking turns would pile a second long inference onto a
busy worker while an idle one sits next to it. Selection and the in-flight
increment happen under one lock so concurrent dispatches cannot overshoot a
worker's declared max_concurrent, which a Lease releases on drop.

Services authenticate with a shared token (constant-time compare); the
certificate only proves the backend, and is self-signed at boot unless a PEM
pair is configured. Since that regenerates per boot, GET /ai/certificate
publishes it (PEM + sha256) for a service to pin — public because a server
certificate is handed to every peer in the TLS handshake anyway, and 404 when
the bridge is off. A service must re-fetch on every reconnect, not once at
startup.

Off unless AI_QUIC_ADDR is set, so the API is unchanged for deployments
without AI. Set without AI_SHARED_TOKEN it refuses to boot rather than listen
unauthenticated.

2026-07-22

2026-07-21

✨ feat(courses): manager-assigned course teachersAhmet Kaan Gümüş · 5ff771b
✨ feat(courses): manager-assigned course teachers

A course used to have exactly one manager: its creator. A teacher taking
over someone else's class needed manager+, which is the wrong bar for
ordinary staffing.

Courses now carry a `teachers` list alongside the (still immutable)
`creator`. Manager+ assigns and unassigns via POST/DELETE
/courses/{id}/teachers; the assignee must already hold teacher+, since
every gate behind the assignment re-checks that bar anyway.

The rights split in two:

- can_manage_course: creator, assigned teacher, or manager+. Everything
  inside the course — edit, enroll, exams, sessions, subjects, grading,
  roll call. Every existing gate routes through this one helper, so
  assignment reaches all of them at once.
- owns_course: creator or manager+ only. Deleting the course and changing
  who teaches it. An assigned teacher runs a course; they don't own it,
  and can't delete it out from under the person who made it.

Staffing is deliberately manager-only: a course's own creator cannot hand
management rights to their peers.

Stale data: rows written before the field decode as unassigned (a serde
default on the field) and the boot backfill fills them to []. DDL and
backfill stay in separate batches — sharing one silently strips keys on
SurrealDB 3. Verified against the real volume, not just the in-memory
tests: a legacy-shaped row backfilled, rendered, and took an assignment.

A demotion below teacher sweeps the user off every course they were
assigned to, mirroring how promotion drops enrollments.
✨ feat(questions): student Q&A pool with moderated solutionsAhmet Kaan Gümüş · 0df048b
✨ feat(questions): student Q&A pool with moderated solutions

Students ask (one photo, pending-only edits), teacher+ approve into a
school-wide pool — approval freezes content so nothing unmoderated
slips in after review; rejection is deletion, no rejected state.
Anyone above parent offers solutions: text + one photo, author-edited
anytime (unmoderated), delete-only moderation. Question rows carry
solution_count; deletes cascade solutions and image blobs (zero
orphans). Question and solution photos reuse the exam-image raster
allowlist and size cap via serve helpers shared out of exams.

2026-07-19

🐛 fix: authz holes and stale-read races from the bug huntAhmet Kaan Gümüş · de938d8
🐛 fix: authz holes and stale-read races from the bug hunt

- messages: a PATCH rejected on the folder no longer half-applies the
  read flag; the whole body validates before any write
- messages: the delete-from-trash gate rides in the UPDATE's WHERE
  instead of a check-then-act window
- notes: all nine handlers now require the student role — the read-only
  parent role could create notes and upload files (new RequireStudent)
- reports: a parent link whose student side changed role is inert;
  ensure_can_observe re-reads the target's live role like enrollments
- exams: update_exam takes the EXAM_LOCK writer lease before reading
  the row its merge defaults and draft/mode gates judge

Re-link keeping one tie while linked_by moves to the latest linker is
deliberate (matches re-enroll); doc reworded to say so.
✨ feat(messages): one-to-one mail with per-side foldersAhmet Kaan Gümüş · f4b3828
✨ feat(messages): one-to-one mail with per-side folders

Any user writes to any user (the one place a parent acts); only
self-send is refused. A single row serves both parties, each owning
their copy: the recipient files through inbox/archive/trash with a
read flag the sender sees as a receipt, the sender through
sent/trash. Folder and read writes are field-scoped so the two
writers never clobber each other. Permanent delete works only from
the trash and drops the row once both sides are gone. Messages carry
an optional free-text label badge, and ?read=false with limit=1
turns the page total into the unread badge.
✨ feat(users): read-only parent role with student tiesAhmet Kaan Gümüş · ec44315
✨ feat(users): read-only parent role with student ties

Parent sits below student in the hierarchy: clears no staff bar and
fails every exact student gate, so it can only observe. Admins tie
students to a parent under /users/{id}/students; the tie alone opens
the student's marks/attendance/pomodoro reports (full, unnarrowed)
plus the parent's own /users/me/students list. A role change off
either end of a tie sweeps it, mirroring the enrollment sweep.
✨ feat(pomodoro): server-stamped student focus logAhmet Kaan Gümüş · 73d4367
✨ feat(pomodoro): server-stamped student focus log

Students start/finish pomodoro focus sessions; the server stamps both
instants, so recorded focus time is honest. Starting discards a dangling
unfinished session instead of conflicting — a crashed timer never blocks
the next one. Logs return the page envelope plus total_focus_ms (unpaged
sum of finished durations); teachers+ read any student's log. Breaks and
the work/break rhythm stay in the frontend — the backend stores no timing
policy.
✨ feat(exams): images on questions and choice optionsAhmet Kaan Gümüş · dbeb122
✨ feat(exams): images on questions and choice options

Teachers pin one illustration to any question (the map above the
prompt) and one picture per option on choice questions — the options
themselves can be images. Multipart upload per slot, replace by
re-upload, frozen with the question once attempts exist.

- rows in question_image (deterministic id per slot, UPSERT = replace);
  blobs beside note files under FILES_PATH, capped by max_file_bytes
- raster allowlist png/jpeg/webp/gif — SVG can script and these bytes
  render inline to students; served with nosniff + private, no-store
- students fetch bytes behind the sitting wall (enrollment + started
  attempt, no early peek); course managers anytime
- replacing a question's choices drops its option pictures (the
  illustration stays) — old pictures belong to the old options
- blob cleanup wired into image replace/delete and question, exam,
  and course deletes (exam cascade result slot shifted 5 -> 6)

2026-07-17

✨ feat(subjects)!: course subjects, required on every exam questionAhmet Kaan Gümüş · 022aaaa
✨ feat(subjects)!: course subjects, required on every exam question

Each course now owns its curriculum as subjects (name + optional
description; course link fixed at creation). Every exam question must
be tagged with a subject of its exam's own course, so exam content is
attributable to a topic.

- POST/GET /courses/{id}/subjects (manage / course-visibility, paged)
- GET/PATCH/DELETE /subjects/{id}; delete is a 409 while any question
  still references the subject — re-tag or delete those questions first
- course delete cascades its subjects

BREAKING: question create/update payloads require subject_id, and
questions written before subjects existed are destroyed on boot
(answers first) — nothing truthful to backfill, pre-customer clean
break.

2026-07-15

✨ feat(web)!: paginate every list endpointAhmet Kaan Gümüş · f3d2b0a
✨ feat(web)!: paginate every list endpoint

Every array-returning GET now accepts `?limit=&offset=` and returns a
`{ items, total, limit, offset }` envelope instead of a bare array.
Paging is opt-in: omitting `limit` returns the full list (limit echoes
null), so callers that need the whole set — an exam's questions during a
sitting, roster/grade pickers — are never silently truncated. `total`
always carries the unpaged count, so a frontend can render "100 of 256"
and drive a pager without a second request.

Windowing is a slice over the already-ordered domain list (the domain
layer is untouched); endpoints that embed people run that join over the
page alone. `limit` must be 1..=500 and `offset` >= 0 (else 400); an
offset past the end yields an empty page, not an error.

Covers all 17 list GETs, including /courses/me, /work/me, /work/{user},
and /users/search — whose hard 10-row cap is dropped in favour of the
same paging. Not paged: /exams/{id}/attempt/{questions,answers}, the
marks & attendance report objects, /exams/{id}/live, and /settings.

Shared machinery lives in web::page (Page<T>, PageParams, paginate).
Docs updated across the OpenAPI spec (utoipa query params + Page_*
response schemas), the Swagger UI it feeds, and the README (a Paging
section plus a `· paged` tag on every list row).

BREAKING CHANGE: list endpoints return a pagination envelope, not a bare
JSON array — clients must read `.items`. /users/search no longer caps at
10 results.

2026-07-13

✨ feat(school): editable policy settings + academic termsAhmet Kaan Gümüş · ea8bfeb
✨ feat(school): editable policy settings + academic terms

Every school differs; the varying parts become data instead of code:

- settings singleton (GET any user, PATCH manager+): exam kinds,
  attendance statuses, grade-display bands. Absent row = old
  hardcoded defaults, so existing databases behave unchanged.
- core four attendance statuses stay mandatory — the attendance
  rate is defined over them; school extras tally rate-neutral
  under a new `custom` bucket in reports.
- grade bands are display-only over the canonical 0-100 marks:
  reports gain grade/average_grade/overall_grade labels, stored
  marks never change with the display scale.
- terms are rows (semester/trimester/quarter all fit); courses
  link via nullable term_id, term delete unlinks, past dates
  allowed for mid-year calendar backfill.
- settings edits never rewrite stored rows: retired kinds and
  statuses live on in old records; only new writes validate
  against the current lists.

2026-07-12

✨ feat(schedule): reject past times on exam, session, and event writesAhmet Kaan Gümüş · bd67462
✨ feat(schedule): reject past times on exam, session, and event writes

- check_not_past (web/mod.rs): a request-set starts_at/ends_at must not
  lie before the server clock — a deadline that starts in the past is
  dead on arrival (400); applied on create and PATCH of exams, course
  sessions, and events
- SCHEDULE_PAST_GRACE_MS (60 s) absorbs request latency and client-clock
  skew so "starts now" survives its own round trip; genuine backdating
  stays rejected
- PATCH judges only values the request carries: stored times merged in
  are exempt, so a running exam (past starts_at) still takes renames and
  deadline extensions
- work-log check_in/check_out corrections stay free — records of past
  work, not schedules
- unit tests for check_not_past and check_time_range; OpenAPI field docs,
  400 descriptions, and schema examples updated (examples moved to a
  future instant)
✨ feat(attendance): course sessions, roll call, work log, reportsAhmet Kaan Gümüş · 5b6aac1
✨ feat(attendance): course sessions, roll call, work log, reports

- course_session: a course's lesson (teacher, topic, required starts_at,
  optional ends_at); managed under course rights like exams; explicit
  teacher_id must hold teacher+; lists ordered by starts_at (timetable)
- session_attendance roll call: one row per session+user by composite id,
  course denormalized so reports need no join; students never self-mark —
  the session's teacher or a course manager marks enrolled students, and
  the teacher's own presence row is manager+ only (no self-declared
  presence); session/course deletes cascade roll-call rows
- work_entry staff timesheet (teacher+): check-in/out stamped by the
  server clock only, so a client clock or crafted request can't forge
  presence; one open stint per user held atomically — INSERT IGNORE on
  the deterministic open_{user} id, check-out takes it via DELETE RETURN
  BEFORE and re-files under a ULID; manager+ reads any log, corrects
  closed stints (ordered instants), deletes entries
- attendance reports at /attendance/me and /attendance/{user} (teacher+),
  mirroring the marks report: event tallies + session tallies +
  per-course breakdown; rate = (present+late)/(present+absent+late) —
  late attends, excused counts against no one; unenrolling hides marks
  but never absences (attendance is a historical record)
- RequireManager extractor; check_time_range shared by events/sessions
✨ feat(exams): scheduled attempts, live monitor, questions, answers, exam roomAhmet Kaan Gümüş · ade4fed
✨ feat(exams): scheduled attempts, live monitor, questions, answers, exam room

- exam scheduling as one validated unit: mode sync|async + window
  (+ per-student duration_ms for async); unscheduled stays offline-graded
- exam_attempt: one row per exam+user by composite id; start = attendance
  signal, finish = submission; status/deadline recomputed from the current
  schedule on every read (mode frozen once attempts exist, times extend live)
- teacher live monitor: GET /exams/{id}/live snapshot + SSE /live/stream
- exam_question: choice|text authored per exam, kind bundle (choices+correct)
  validated as a unit, frozen once attempts start, ULID order
- exam_answer: upsert per question+user via composite id, kind-coherent,
  server-clock stamped; pure auto_score over choice questions as a grading
  suggestion — final mark stays human via /results
- student exam room WebSocket at /exams/{id}/attempt/ws: state ticks,
  autosave acks, finish/expire lifecycle, gates rejected pre-upgrade with
  proper HTTP statuses; shares the REST write path
- PersonRef embeds (id + username + display name) in people-bearing
  responses, plus teacher+ GET /users/search
- cascades: exam/course deletes sweep attempts, questions, answers, results

2026-07-11

✨ feat(marks): weighted mark reports per course and overallAhmet Kaan Gümüş · ebc1bd2
✨ feat(marks): weighted mark reports per course and overall

GET /marks/me gives any authenticated user their own report; GET
/marks/{user} (teacher+) reads anyone's, 404 for unknown users. For
each enrolled course the report joins the course's exams with the
user's graded results: per-exam entries (title, kind, weight, mark,
grader), a Σ(mark×weight)/Σ(weight) course average, and a plain mean
of course averages overall. Ungraded exams don't appear, averages stay
null until something is graded, and unenrolling hides a course's block
without deleting result rows.

ExamResult::list_for_user_in_course supplies the raw rows behind each
course block.
✨ feat(courses): courses, enrollment, and course-scoped weighted examsAhmet Kaan Gümüş · cd56c5b
✨ feat(courses): courses, enrollment, and course-scoped weighted exams

Courses become the unit exams and enrollments hang off. Teachers create
them; editing, deleting, enrolling, and adding exams require course
management rights (creator, or manager/admin). Enrollment rows use a
deterministic composite (course, user) id, so enrolling is one atomic
idempotent UPSERT with no find-then-insert race. Deleting a course
cascades its exams, their results, and enrollments in one transaction.

Exams move inside a course (POST /courses/{id}/exams) and gain a weight
(1-100) that says how many times they count into the course average;
kinds grow to homework, quiz, midterm, final, project, and oral —
informational only, weight drives the math. Grading now demands course
management rights and an enrolled target; moving an exam between
courses is deliberately impossible so results can't be stranded.

Routes: courses CRUD, GET /courses/me for the caller's enrollments,
roster listing, enroll/unenroll, and per-course exam creation/listing.
✨ feat(web): axum handlers, DTOs, and auth extractorsAhmet Kaan Gümüş · 3c4822c
✨ feat(web): axum handlers, DTOs, and auth extractors

The HTTP layer over the domain. DTOs are plain strings on the wire;
handlers parse them into validated newtypes before touching the
database. Responses share one UserResponse shape (id, username, role).

Auth is a session cookie: login sets an HttpOnly, SameSite=Lax
`session` cookie (Secure when configured) backed by a server-side row;
logout is idempotent. Extractors encode access control by type —
CurrentUser for any logged-in caller, RequireTeacher / RequireAdmin
for role-gated routes — with the role re-read every request so a change
takes effect on the next call.

Routers: auth (register/login/logout/me), users (admin listing + role
changes), notes (per-user CRUD), events + attendance, and exams +
results. Ownership and role rules live in the handlers: event/exam
edits are creator-or-manager+, grading is teacher+ and never targets
oneself, and admins can't change their own role.