forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on 03467171d2a77c2afca2575cd47f2d2e67e7818fFiltered to src/database.rsClear filter

2026-08-04

feat: 🏅 earn badges for the work already doneAhmet Kaan Gümüş · a00880e
feat: 🏅 earn badges for the work already done

Thirteen badges a student earns by doing the work, so the profile has
something to be proud of rather than just a photo and a bio.

Nothing awards a badge by hand and nothing takes one away. A badge is
earned when a counter crosses a threshold, and it is permanent: withdraw
the submission that earned it and the count falls while the badge stays,
because a stamped `earned_at` is the motivational payload and a badge
that evaporates is worse than no badge. The catalog is hardcoded, so
changing a threshold is a deploy and the evaluator stays a pure function
of the counters. It rides GET /limits as a group like every other bound;
labels and icons are the frontend's, keyed by badge id.

The counters are the real work. Homework, exam and attempt tables are
indexed for the questions the rest of the API asks, so counting a single
student's history meant a full table scan — the numbers are therefore
tallied at write time, in the same transaction as the write that causes
them. Existing accounts are seeded once from their real history, gated by
a mark whose skip is proven rather than assumed, so nobody starts at zero
for work they already did.

Withdrawing your own submission decrements, and that is the only
decrement in the codebase: withdrawal is student-callable, so without it
submit/delete/submit would farm the counter. Cascades never decrement —
history a teacher erased is still history the student lived. The cost is
that a re-run seed, which can only count rows that still exist, comes out
lower than the live tally; documented where someone would otherwise
"repair" it.

Deadlines move, so the on-time verdict is now stored on the submission
beside the count it fed. Judging it again at withdrawal read whatever the
deadline had become since, which drifted the tally in both directions —
far enough that on-time could exceed submitted.

Attendance counters were dropped: those tables already carry per-user
indexes, so there is no scan to fix, the status list is school-editable,
and roll-call corrections would need a decrement that fights permanence.

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.

2026-07-31

fix: 🔁 retry every guarded transaction that loses a write raceAhmet Kaan Gümüş · 755f4ab
fix: 🔁 retry every guarded transaction that loses a write race

08b1b0f gave the four guarded deletes a retry. It left the rest of the
class alone, and the rest of the class is the same defect: a guarded
BEGIN..COMMIT that loses a round reports the abort's generic sibling slot
as AppError::Db, so an ordinary contended write answers 500 instead of
the 409 or 404 it owes.

Eight more sites now go through transaction_with_retry: ExamResult's mark
and its removal, AppointmentSlot::delete_free, MenuDish::create,
PomodoroSession::finish, WorkEntry::check_out, and the exam freeze gate
covering ExamQuestion insert/update/delete and QuestionImage
upsert/delete.

The freeze gate needed restructuring rather than wrapping. unfrozen()
built the SQL and frozen_check() inspected an already-sent response, so
the five callers owned the send and nothing in that split could re-send.
Both are replaced by write_unfrozen(), which owns the send and therefore
can retry; frozen_check is gone, so no path skips it.

ExamResult::remove additionally dropped its .check()? — that returns the
lowest-slot error, so an aborted transaction's "not executed" sibling
masked the real retryable conflict. The same masker was deleted from
Exam::delete in 08b1b0f.

transaction_with_retry's admissibility clause is now a rule instead of a
list of callers, which had already gone stale: a statement is admissible
iff it cannot legitimately answer "already exists" — UPDATE and DELETE
never can, a CREATE cannot when no rival can reach its id, and an UPSERT
cannot when its id is bijective with every unique tuple its table
indexes.

Re-send soundness is measured, not argued: injecting a THROW just before
each batch's trailing RETURN makes every statement run and then aborts
the whole transaction, and re-sending the real SQL afterwards left the
suite green across all twelve sites, with no batch double-applied.

2026-07-30

fix: 🔁 retry a guarded cascade that loses a write raceAhmet Kaan Gümüş · 616a66b
fix: 🔁 retry a guarded cascade that loses a write race

A BEGIN/COMMIT delete that lost a write conflict answered 500 instead of
the refusal or retry it owed. An aborted transaction errors *every* slot,
and all but the failing one say a generic "not executed" — the consequence
of the abort, never a reason of its own. Picking one of those out of the
unordered HashMap from take_errors, or taking the first via check(),
retired a retryable round as a database error. Measured on Course::delete
at 1-3 of 20 raced rounds against a real server.

transaction_with_retry is write_with_retry's story for the cascades that
cannot be one statement: it matches the caller's THROW markers first, since
a THROW is a decision and outranks a conflict, then re-sends while any slot
reports a lost round. It hands back both the response and the drained
errors because take_errors consumes and the caller needs the slots as well
as the map.

Course, Subject and Exam route through it; Exam also loses the check() that
was masking the conflict behind a sibling slot. Term needed none of it — it
is a single statement, so the existing write_with_retry was the whole fix.

Four ignored race tests come with it. Only the course one discriminates,
proven by cutting the retry loop to a single attempt and watching it go
red; the other three guard their handlers' status codes and say so on
themselves rather than implying a measurement they do not make. They share
a lock so the documented invocation works.
fix: 🧊 freeze a fee plan the moment it is assignedAhmet Kaan Gümüş · ac70cc0
fix: 🧊 freeze a fee plan the moment it is assigned

The 409 that stops an assigned plan being edited or deleted was a scan
followed, some microseconds later, by the write it licensed. An assign
landing in that gap left a plan edited and assigned, or deleted with a
live assignment still naming it. The comment called it an accepted race
and blamed the other replica; there was never another replica, and two
concurrent requests in one process were always enough.

A plan now carries an assignment refcount. The assign claims it in the
same transaction that writes the row, and the edit and the delete are
conditional writes that refuse while it stands. The plan freezes at the
instant of the claim, so the assign re-reads it afterwards and bills the
copy that froze — the refcount alone still let an edit slip in front and
bill the snapshot the handler had read.

Existing plans are seeded from the assignments they already carry. An
absent counter reads as zero, which is the value that licenses an edit,
so a plan assigned before this would otherwise have come unfrozen.

Two things this uncovered. A cap claim that lost a write conflict was
answered as a 500 five times in six: the retryable conflict shared the
error batch with the sibling statements it aborted, and an arbitrary one
of those was returned. And a guarded write had no retry at all, so a
raced PATCH or DELETE failed outright rather than trying again.

The race tests run against a real server. On the embedded engine they
watched a 45-in-50 failure rate and passed.
chore: 🧹 drop the coordination for replicas we never runAhmet Kaan Gümüş · a9cfe7b
chore: 🧹 drop the coordination for replicas we never run

The backend runs as one process against one database, deployed
stop-the-world. The machinery that let several of them agree was built
ahead of a multi-replica rollout that stayed parked, so none of it was
ever load-bearing: the boot lease elected a leader out of a field of
one, the ai_worker table announced a worker to nobody, and the chat
claim queue only ever claimed its own writes.

Boot now migrates and seeds straight-line; a chat turn is dispatched by
the handler that accepted it; the 503 gate reads the in-process
registry. The retired columns and tables are unset and removed in
separate batches, repair before REMOVE.

What stays, with its reason corrected rather than removed: cap.rs,
field_update.rs, the refcounts, the CAS retry loops and the in-process
locks. Those close write skew between concurrent requests inside one
process, which two replicas made worse but never caused.

A turn orphaned by a restart or a panic is no longer reclaimed. It
settles as timed_out within CHATBOT_PENDING_STALE_SECS.

The design survives in the ledger if a second process is ever wanted.

2026-07-27

fix: 🧷 close the cross-table races the locks never closedAhmet Kaan Gümüş · 4f7bdaf
fix: 🧷 close the cross-table races the locks never closed

Every remaining check-then-write that spanned tables becomes a
single-record conditional write, so it holds across replicas:

- subject delete: refcounts (exam_question_count/homework_count) claimed
  and released by every question/homework write; the triple lock hold
  dies, BANK/TERM/ENROLL locks die outright
- exam kinds: kind_ref {count,retired} records; grading claims, removal
  retires only at zero — grading a removed kind and re-kinding a graded
  exam are now 409 (both previously silently mis-weighted marks)
- homework: the grade stamps the submission row in its own transaction;
  student writes are conditional on the stamp being absent
- appointments: slot occupancy is a cap-1 counter; the lock survives
  only for the within-replica approved-overlap check
- meals: seat counter + menu version CAS (price can no longer tear mid
  booking) + deterministic menu:date_slot id kills duplicate publish
- cap::claim_and_create: member gate, then seat, then child CREATE in
  one transaction — a duplicate loser no longer eats a stranger's seat
  or gets refused for a row it already owns
- boot: the two unguarded lease statements now retry on transaction
  conflict (the escape was ~1-in-15 under full-suite load)

Two races reviewed and accepted, documented in README ## Concurrency
model: the attempt-seq late save (one history row, grade of record
untouched) and cross-replica approved-overlap (visible, cancellable).

Deployment contract (README): counter-adding releases restart all
replicas together — an old binary's writes skip new counters and the
= NONE backfill guard rightly refuses to re-seed.

Every guard is mutation-proven; backfills are one-time, = NONE-guarded,
ordered after the destructive sweeps, and verified against the live
volume.
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: 🗳️ elect the boot, and make a chat turn a claimed jobAhmet Kaan Gümüş · 0787b14
feat: 🗳️ elect the boot, and make a chat turn a claimed job

Two things assumed there was only ever one process. Both stop assuming it,
and both pay off on a single replica today, where a rolling restart already
overlaps two containers.

**The boot is elected.** Every process ran the whole migration, backfill and
admin seed on startup, so two overlapping ones raced all three. A process now
claims `migration_lock:boot` with a deterministic-id CREATE, renews a lease
while it works, and stamps a sha256 of the SQL it applied; the others wait for
that stamp and only trust it when the fingerprint is their own, so a new binary
never serves on the previous one's schema. A leader that loses its lease fails
its boot rather than reporting a success it no longer owns, and an abandoned
lock is taken over once the lease lapses.

Seeding the admin was two writes — create as a student, then promote — and a
process killed between them left a student holding ADMIN_USERNAME that no later
boot would ever promote, because nothing can tell that row from a stranger who
registered the name. The role is now minted with the row.

**A chat turn is a claimed job.** The answer used to ride on a `tokio::spawn`
belonging to whichever process took the POST, so a restart orphaned it and the
turn only settled at the stale horizon. The POST now just writes the pending
row; a replica holding a `chat.reply` worker claims it with a conditional
update and answers over its own socket. A claim left behind by a dead process
expires and is retried, and a configured AI timeout is capped below that
horizon so a slow inference is never reclaimed out from under itself.

The gate and the dispatcher are deliberately separate: `ai_worker` is a
heartbeated table that only answers "could anything, anywhere, serve this",
may be stale, and never guards a write; the in-process registry owns the
socket and is the only thing that decides who dispatches.

hab/1 is untouched. Verified on two live replicas against one SurrealDB: a
turn posted to a worker-less replica was answered by its peer, survived a
restart of the other replica mid-flight, and was dispatched exactly once.
fix: 🕰️ stop the boot sweep from killing chat turns still being answeredAhmet Kaan Gümüş · f77d48a
fix: 🕰️ stop the boot sweep from killing chat turns still being answered

The migration failed every `pending` chatbot_message on startup, so any
deploy or restart shot down answers that were dispatched seconds earlier
and whose AI worker was still on the other end of the bridge.

The sweep now only claims rows past `CHATBOT_PENDING_STALE_SECS`, bound
into the statement so the constant stays the single source of truth. A
younger row is left alone: the reader already presents an over-age
`pending` as failed, and the next boot sweeps for real whatever crossed
the horizon meanwhile.
chore: 📦 give every constant one homeAhmet Kaan Gümüş · 78b25b5
chore: 📦 give every constant one home

Constants were scattered across 18 modules: table names and migration SQL in
database.rs, limits in config.rs and rate_limit.rs, magic strings sitting next
to the only code that read them. Nobody could answer "what are all the hard
values in this service?" without a grep.

They all live in constant.rs now — validation bounds, the 37 SurrealDB table
names, the PRE_REPAIR/MIGRATION/BACKFILL schema SQL, and the enum value tables
that used to hide as associated consts (Role::ALL -> ROLES, Folder::SENDER ->
SENDER_FOLDERS, and friends). Values are byte-identical; this changes no
behavior. constant.rs now imports crate::domain for the enum types, an
intra-crate cycle that compiles fine.

Statics stayed where they were. A Mutex or a ULID generator is runtime state,
not a constant, and moving them would only blur that line.

Two guards keep the consolidation honest. limits_completeness.rs already
failed on any pub const in constant.rs that is neither published through
/limits nor excluded with a reason; the *_TABLE names are excused by shape
rather than by 37 lines of boilerplate, but the excuse now requires the
absence of a MAX_/MIN_/DEFAULT_ prefix so a real bound cannot hide behind the
naming convention. And the move quietly dropped three rules off the end of the
text-fold table, which every existing test still passed — so the circumflexed
vowels are pinned, and search_fold_sql must emit one string::replace per rule
or the needle and the column drift apart.

2026-07-25

fix: 🗃️ backfill the rows the choice-identity retype left unwritableAhmet Kaan Gümüş · b005e15
fix: 🗃️ backfill the rows the choice-identity retype left unwritable

dde4896 retyped fields but shipped no backfill, so every row written
before it survived the DDL unchanged and then failed on the next write:

  Couldn't coerce value for field `choices` of `exam_question:q1`:
  Expected `none | array<object>` but found `['3','4','5']`

- convert `exam_question`/`bank_question` `choices` from `array<string>`
  to id-carrying objects, minting one id per position, and remap
  `correct`, `question_image.slot`, `bank_question_image.slot` and
  `exam_answer.selected` from the old integer index to the id minted at
  that same position — a student's stored answer keeps resolving to the
  option they actually saw
- f90014b's `source_bank` needed `UNSET` before `REMOVE FIELD` takes it
  away, so that repair runs as its own PRE_REPAIR query ahead of the DDL
  batch; it is guarded by `IF 'exam_question' IN
  object::keys((INFO FOR DB).tables)` because `UPDATE` on an undefined
  table errors rather than returning empty on a fresh database
- the conversion has to precede the `seq = 1` stamps and set
  `seq = seq ?? 1` itself: a legacy `exam_answer` lacks `seq` *and* has
  an int `selected`, and a write coerces the whole record, so either fix
  alone fails on the other and the whole loop rolled back
- every statement is shape-guarded, so re-running on a converted row is
  a no-op and no id is ever re-minted

Proven on a scratch surrealkv db with these consts: old-shaped rows read
back converted, previously-failing writes succeed, index 2 still
resolves to "5", and a second boot changes nothing.
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(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).
✨ feat(appointments): record who cancelled or rejected and whyAhmet Kaan Gümüş · 5d48a8d
✨ feat(appointments): record who cancelled or rejected and why

Reject and cancel now take an optional free-text reason and stamp the
actor: bookings gain cancelled_by, cancel_reason, and reject_reason, all
#[surreal(default)] so rows written before these existed still read back
as None. The reason is validated (400 if over-long) before it touches the
row; a blank or absent one records nothing. AppointmentResponse exposes
the new fields, and decline_reschedule cancels with no reason.
✨ feat(exams): let students review their own graded examAhmet Kaan Gümüş · 4db4ff2
✨ feat(exams): let students review their own graded exam

Add a per-exam teacher toggle `allow_review` (default false, opt-in,
mirrors `allow_rejoin`) and three student self-review endpoints:

  GET /exams/{id}/review/attempts
  GET /exams/{id}/review/attempts/{seq}/answers
  GET /exams/{id}/review/attempts/{seq}/answers/{qid}/image

All are CurrentUser-scoped (no {user} param, so a student only ever
sees their own data) and gated by reviewable_exam(): 404 on missing or
draft exam, 403 when allow_review is off, 404 until an ExamResult row
exists for that student (proves the teacher marked them). Readers are
the same ones the teacher history endpoints use.

Schema: DEFINE FIELD allow_review DEFAULT false + a separate backfill
query flipping legacy NONE rows to false — no existing exam auto-exposes
answer sheets. Podman-verified: 9 legacy rows migrated null->false.

2026-07-23

✨ feat(exams): keep every attempt's answers, drawings, and markAhmet Kaan Gümüş · 3668684
✨ feat(exams): keep every attempt's answers, drawings, and mark

Retakes wiped the prior sitting's answer sheet and overwrote the single
mark row, so a re-sit erased any record of how the student did before.
Teachers need that history to understand a student.

Each sitting now keeps its own rows, keyed by the attempt `seq` (in the
record id + a denormalized field). `seq==1` maps to the old bare key, so
existing rows need no migration beyond a `seq=1` backfill; the unique
indexes move to include `seq`. The retake answer/image wipe and the
per-retake blob GC are gone.

Grade-of-record stays the latest sitting: roster, report, and by-user
reads return the newest `seq`. Prior sittings are read-only, exposed to
course managers via new history endpoints:
  GET /exams/{id}/students/{user}/attempts
  GET /exams/{id}/students/{user}/attempts/{seq}/answers
  GET /exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image
  GET /exams/{id}/students/{user}/marks
Live reads (autosave, exam-room WS, monitor) scope to the current seq.
🎨 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(messages): remember where a filed copy came fromAhmet Kaan Gümüş · 79189b8
✨ feat(messages): remember where a filed copy came from

Archiving or trashing a copy stamps the folder it left onto that side's
origin field, exposed as `previous_folder`, so restoring puts it back
where it came from instead of always in the inbox.

The trash is never stamped — pulling a copy out of it must not leave the
copy pointing back at the discard pile — and a no-op move keeps the stamp
it had. `null` means "restore to the home folder", which is also how rows
filed before the field existed read (option columns, no backfill).

Folder names become a `Folder` enum: the DB columns, the list filter and
the stamp all pass through it, so the stale string arrays are gone and a
typo is a compile error rather than a silently empty folder.
✨ 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.

2026-07-22

2026-07-21

feat: 🎨 student answer-image endpoints mirroring question imagesAhmet Kaan Gümüş · 2c83c6f
feat: 🎨 student answer-image endpoints mirroring question images

- new AnswerImage domain keyed by (exam, user, question), stored as an
  image/png blob with upsert-overwrite, mirroring QuestionImage
- routes: POST/DELETE/GET /exams/{id}/attempt/answers/{qid}/image (student
  own, gated by the save_answer writable-attempt chain) and GET
  /exams/{id}/attempts/{user}/answers/{qid}/image (teacher grading)
- answer_image (Option<ImageMetaResponse>) on the student sitting view and
  the teacher grading sheet; live monitor and exam_ws untouched
- a drawing-only answer creates a blank text answer row so the drawing
  surfaces in both views; removing the drawing grooms that blank row away
- cascade blobs+rows on exam delete, course delete, and retake wipe (rows
  in the wipe transaction, blobs swept in start_attempt)
- integration tests: raster wall, own/teacher auth walls, upsert, retake +
  exam-delete cascade, drawing-only surfacing and its cleanup
🐛 fix(db): share one session, stop cloning the handle per requestAhmet Kaan Gümüş · 11fa250
🐛 fix(db): share one session, stop cloning the handle per request

The database was never reconnecting. `Surreal`'s own `Clone` mints a fresh
server-side session — `Uuid::new_v4()` plus a fire-and-forget
`SessionId::Clone` to the router (SDK lib.rs:340) — and axum clones the
application state on every request, so `db: Surreal<Any>` in `AppState`
meant a new session, and a matching `SessionId::Drop`, per request served.

Under concurrency those lifecycle events race the queries riding on them.
Sessions vanish outright ("Session not found", surfaced as a 500), and a
session whose signin has not been replayed yet answers "Anonymous access
not allowed" / "Specify a namespace" — the exact strings
`is_session_replay_error` attributes to a post-reconnect replay. So the
failures were reported as a transient reconnect and a retryable 503, which
is why the field logs showed sporadic 503s while the keepalive pinged `ok`
every 5s without a single miss. A healthy socket the whole time.

`Arc<Surreal<Any>>` shares the one session established at boot; cloning the
state is now a refcount bump. `Deref` covers all 175 call sites unchanged.

Same storm, 200 logins at 40 parallel, before → after:
  23×200 / 16×500 / 161×503  →  200×200, zero "Session not found"
600 at 80 parallel also clean.

The classifier is left alone: with the churn gone those two strings can
only come from a real post-reconnect replay, which is what it was for.
✨ 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.
🐛 fix(db): retry boot connect, refuse while socket downAhmet Kaan Gümüş · bebca49
🐛 fix(db): retry boot connect, refuse while socket down

Two failures survived 6627128, which only classified errors from queries
in flight *at* the drop — queries arriving after it produce no error at
all, so there was nothing to classify.

Boot did one connect() and exited on refusal. The runtime then restarted
the process, it failed again in ~100ms, and a few seconds of startup skew
burned the whole restart budget: 6 deaths in 0.6s in the field log, then
down for 12h. Now retries 1s doubling to 5s, forever — only the dial,
since bad credentials never heal by waiting.

A query issued while the socket is down does not fail. The SDK's
router_reconnect loops on 1s retries and stops draining route_rx, so the
query parks until the database returns and only then executes. Reproduced:
POST /auth/login gave no response at 25s, and the keepalive went silent
4m17s before firing two pings in the same millisecond on heal.

Those two pings rule out a plain timeout middleware — a parked query still
runs, so a timeout-sourced 503 would let a client retry double-apply a
mark or an exam answer. Instead the keepalive (now 5s) publishes DbHealth
and db_guard refuses at the edge, before anything is queued, which is what
keeps Retry-After: 1 honest. The 30s request timeout is only a backstop
for requests racing detection; those answer DbTimeout — same 503, no
Retry-After, "may or may not have applied". WS and SSE are unaffected:
both return their response immediately and stream afterwards.

Known gap: exam_ws socket-loop queries run after the upgrade response, so
db_guard does not cover them; they still park and heal on reconnect.

Verified in podman against the existing volume: boot with the database
down backs off and stays alive, requests during an outage answer 503 in
0.3ms, recovery needs no restart.
✨ 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.
✨ feat(db)!: swap embedded surrealkv for a SurrealDB serverAhmet Kaan Gümüş · 60b4509
✨ feat(db)!: swap embedded surrealkv for a SurrealDB server

BREAKING CHANGE: the backend no longer opens a database file. DB_PATH
is gone; DB_URL/DB_USER/DB_PASS point at a SurrealDB server over
WebSocket (compose ships one on surrealkv storage in its own volume,
backend waits on its healthcheck). Pre-switch data was wiped on
purpose — fresh volumes seed from scratch. Tests keep the in-memory
engine; persistence.rs re-runs the boot migration on a live handle
instead of reopening a file.

2026-07-19

✨ 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(exams): draft exams hidden until publishedAhmet Kaan Gümüş · d8fdbf0
✨ feat(exams): draft exams hidden until published

Exam prep is long work: draft: true keeps an exam private to its
course's managers while it's written. Students get 404s (not 403/409 —
existence must not leak) on get/attempt/ws and filtered lists; sitting
and grading are blocked. Publish via PATCH draft: false; re-drafting is
409 once attempts or results exist. grade now holds an EXAM_LOCK read
lease so a mark can't race a re-draft. Modeless exams renamed
offline-graded/unscheduled everywhere — "draft" now means only this.
Old rows backfill published at boot.
✨ 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-18

🐛 fix(users): drop enrollments when a user leaves the student roleAhmet Kaan Gümüş · 6917977
🐛 fix(users): drop enrollments when a user leaves the student role

Enrollment is student-only, but promotion left the rows behind: the
ex-student stayed on course rosters, inflated the live monitor's
enrolled/absent counts, and kept course view access. Security paths
always re-checked the live role — this is roster hygiene, not a hole.

PATCH /users/{id}/role to any non-student role now sweeps the target's
enrollments, and a boot backfill deletes rows already stale on disk
(including rows whose user record is gone: user.role = NONE).

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-16

✨ feat(courses): add kind course|study (supervised study)Ahmet Kaan Gümüş · f29537c
✨ feat(courses): add kind course|study (supervised study)

Supervised study sessions are courses under a different label: `kind` is
settable at creation, PATCH-editable, and returned on every course
response. Behavior (enrollment, exams, sessions, marks) is identical
for both kinds.

Boot backfills pre-kind rows to `kind = 'course'`; new writes default
the same way.
✨ feat(events)!: registration audience replaces hand-picked usersAhmet Kaan Gümüş · 31e155a
✨ feat(events)!: registration audience replaces hand-picked users

Events gain a `registration` audience: a signup list built one seat
at a time — teachers place students (students never register, not
even themselves), staff take only their own seat, never another's.
An optional capacity caps the list (seat count re-checked inside the
insert transaction), and the list freezes the moment the event
starts, both directions. Seats resolve live like every audience:
roster, marking gate, and who-missed report inherit unchanged.

- POST /events/{id}/register {user_id?}: idempotent seat upsert
  (enrollment's composite-id trick); 409 when full or started
- DELETE /events/{id}/register/{user}: same self-or-student rule;
  a deleted account's leftover seat is any teacher's to free
- event delete cascades signup rows; audience switches leave them
  inert (they resurface if the kind returns)
- migration split into DDL + backfill queries: statements in one
  batch see the batch-start schema, so a backfill next to a fresh
  DEFINE FIELD silently lost the keys it wrote (audience became {})

BREAKING CHANGE: the hand-picked `users` audience kind is gone —
requests naming it are rejected. Existing users-audience events
convert on boot: each listed user becomes a registration row
credited to the event creator and the audience becomes an uncapped
registration list.
✨ feat(events)!: audience targeting + teacher-only attendanceAhmet Kaan Gümüş · bd9e7d8
✨ feat(events)!: audience targeting + teacher-only attendance

Every event now carries an audience — school (default), one exact
role, a course's live enrollment, or a hand-picked user list (<=100)
— defining its expected-attendee roster. Resolved at read time, never
snapshotted, so role changes and (un)enrollment move people in and
out by themselves. Visibility is unchanged: everyone sees every event.

- GET /events/{id}/roster: who-missed report (teacher+), expected
  list joined with marks, status null = never marked
- marks for people later dropped from the audience stay in the
  attendance listing but leave the roster report
- pre-audience rows backfill to school-wide on boot

BREAKING CHANGE: POST /events/{id}/attendance requires teacher+ —
students can no longer mark attendance, not even their own — and the
target must be in the event's audience (400 otherwise). Event
responses gain an audience object.
✨ feat(users): per-user UI preferences (theme, language)Ahmet Kaan Gümüş · 7168ba0
✨ feat(users): per-user UI preferences (theme, language)

Theme (light/dark) and language (tr/en) live on the user row and
return on every user response. PATCH /users/me/preferences is
self-service for any role; PATCH /users/{id}/preferences is the
admin path. Same merge semantics as the profile patch: omitted
keeps, "" clears, anything else validates or the patch is a 400.

Null means "never chose": clients fall back to the device
preference (prefers-color-scheme, browser language), so there is
deliberately no server-side default to stomp device detection.
Pre-feature rows read back null through the option<string> columns
— no backfill needed.

2026-07-15

✨ feat(notes): file attachments with school-set size capAhmet Kaan Gümüş · f1b532b
✨ feat(notes): file attachments with school-set size cap

Blobs live on disk under FILES_PATH (same volume as the DB), named by
the row's ULID so user input never shapes a path; the note_file row
keeps only metadata. DB-blob storage rejected: multi-MB PDFs bloat
surrealkv's LSM tree and buffer whole in RAM on every read.

- POST/GET /notes/{id}/files, GET/DELETE /notes/{id}/files/{file_id};
  owner-only through the owning note, staff included
- max_file_bytes in settings (1 KiB-25 MiB hard cap, default 5 MiB),
  enforced on streamed bytes (413), inside the settings CAS guard;
  option<int> so pre-field volumes boot without a backfill
- 10 files per note; deleting a note removes rows first, blobs after,
  so a crash strands at worst an unreachable blob

2026-07-14

🐛 fix(db)!: drop backfills that crashed bootAhmet Kaan Gümüş · 992619b
🐛 fix(db)!: drop backfills that crashed boot

Single-field backfills fail on volumes predating the attempt/rejoin
fields: UPDATE re-validates the whole record, so backfilling
max_attempts tripped bool coercion on the still-NONE allow_rejoin
before its own backfill could run. DEFAULT only applies on CREATE,
so it never rescues existing records.

Pre-customer policy is clean breaks over migrations: remove the exam
and exam_attempt backfills plus the old-index compat drop instead of
merging them into one statement.

BREAKING CHANGE: volumes created before the attempt/rejoin fields no
longer boot; wipe the data volume (podman volume rm
hezarfen_backend_hezarfen-data) and reseed.
✨ feat(exams)!: move weight off exams onto their kindAhmet Kaan Gümüş · 3681441
✨ feat(exams)!: move weight off exams onto their kind

Weighting is school policy, not per-exam data: each settings
exam_kinds entry is now {name, weight} (1-100, defaults all 1) and
mark reports resolve weights at read time, so editing a kind
reweights every exam of that kind at once; an exam keeping a
since-removed kind counts as 1.

BREAKING CHANGE: exams lose `weight` on the wire and in storage,
settings `exam_kinds` become objects. No data migration (pre-customer
clean break) — delete ./data/hezarfen.db and reboot.

2026-07-13

✨ feat(exams): open mode, attempt limits, retakes, rejoin doorAhmet Kaan Gümüş · 9835fe7
✨ feat(exams): open mode, attempt limits, retakes, rejoin door

Unscheduled exams were dead ends: attempts answered 409 "nothing to
sit", and every exam was hard-wired to a single sitting.

- mode "open": sittable anytime, no window; duration_ms optional per
  attempt (absent = unlimited time). Modeless exams stay offline
  drafts — still 409, so a student can't freeze a draft's questions.
- max_attempts (0 = unlimited, default 1): terminal attempts can be
  followed by numbered retakes that start from a blank answer sheet;
  the previous sitting's answers are wiped on the next start.
- allow_rejoin: live teacher toggle. Leaving the exam room (WS close
  mid-attempt) stamps left_at; with the door closed, re-entry and all
  saves 409 until reopened. Finish stays allowed either way.
- Attempt deadline generalized to min(ends_at, started_at + duration),
  either side optional; none = ends only by submission.

Boot migration backfills max_attempts/allow_rejoin/seq on existing
rows and replaces the single-attempt unique index (exam, user) with
(exam, user, seq) via REMOVE INDEX IF EXISTS. Sitting #1 keeps the
legacy {exam}_{user} record id, so pre-upgrade attempts stay valid.
✨ 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(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(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(profile): optional personal info on user accountsAhmet Kaan Gümüş · baceaf5
✨ feat(profile): optional personal info on user accounts

Every account (any role) gains name, surname, email, phone, and birth
date as optional fields backed by validated newtypes: PersonName keeps
unicode and trims, Email and Phone get pragmatic shape validators, and
BirthDate parses real calendar dates in YYYY-MM-DD form and refuses the
future. Existing rows read back as None via option<string> columns.

Endpoints: PATCH /users/me lets any authenticated user edit their own
info; GET /users/{id} and PATCH /users/{id}/profile give admins the
school-office path for maintaining records. Patch semantics per field:
omitted keeps the current value, an empty string clears it, anything
else is validated and set. UserResponse now carries the new fields.
✨ feat(db): embedded SurrealDB connection and schemaAhmet Kaan Gümüş · 0b4bc10
✨ feat(db): embedded SurrealDB connection and schema

init opens the file-backed surrealkv store and applies the schema;
init_mem gives tests a fresh in-memory database with the same schema.

The migration is one idempotent SCHEMAFULL block (DEFINE ... IF NOT
EXISTS), safe to run on every boot. Every column is typed, foreign
keys are record<..> links, and unique indexes enforce the invariants
that matter: one username, one session token, one attendance row per
event+user, and one result per exam+user.

Table-name constants are exported so the domain layer never spells a
table as a bare string.