forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on 03467171d2a77c2afca2575cd47f2d2e67e7818fFiltered to src/lib.rsClear filter

2026-08-05

fix: 💳 stop telling a bursar a reversed charge was paidAhmet Kaan Gümüş · 26a740d
fix: 💳 stop telling a bursar a reversed charge was paid

A reversal is a `+amount` child of the line it undoes, so it fills
exactly the room a payment would: `applied_to` folds it in and a reversed
charge reads as full to the last minor unit. `POST /payments/credits` against one
therefore answered "the charge is already paid in full" — about a charge
where not one minor unit ever arrived. It was reversed, and a bursar reading
that goes hunting for money that does not exist.

The stored outcome is right and does not move: a reversed charge is no
longer owed and takes no payment. Only the diagnostic changes. The
reversal's id is derived from its target's, so telling the two refusals
apart is one read, taken on the refusal path alone. `refund` passes
`None` and spends no read: a credit is never reversed, so a full fold
there can only mean the refunds.

Doc surfaces move with it: the route's 409, its handler doc, the
`payments` tag description, and the README route table and section.
fix: 📅 stop offering a slot booking will refuseAhmet Kaan Gümüş · 2202807
fix: 📅 stop offering a slot booking will refuse

`GET /appointments/slots` listed every slot whose `ends_at` was still
ahead, but `Appointment::book` refuses any slot whose `starts_at` has
passed. The two windows disagreed, so a slot already underway sat on the
student's bookable calendar as an entry that could only answer 409 —
either published inside `check_not_past`'s 60-second grace, or simply
started while the page was open.

The listing moves to `book`'s bound: `starts_at > $from`. `book`'s rule
is the real constraint, so the calendar stops advertising what booking
refuses rather than booking loosening to match. The 60-second publish
skew grace deliberately does not reach the listing either — `book` does
not grant it, and a slot published a moment after its own start is
unbookable from birth.

Two source claims were false and are corrected with it: `book`'s comment
said `list_upcoming` hid these slots, and the route doc called them
"every slot still open in the future".
fix: 🏫 stop a deleted course from sticking in a blueprintAhmet Kaan Gümüş · b0f72a5
fix: 🏫 stop a deleted course from sticking in a blueprint

A grade template holds its courses as a list on its own row, so nothing in
`Course::delete`'s cascade could reach it: the id stayed, and the repair
every doc surface named — `PATCH` the template back as it stands — is a 400
for naming a course that does not exist. The pump's own prune only fires
while walking a section, so at a grade with no sections the id was permanent.

The cascade now sweeps `class_blueprint` in the same transaction that
detaches the course from the sections. Table scan, deliberately unindexed:
one row per grade label, and a course delete is rare — and the per-element
index the WHERE would want (`FIELDS courses[*]`) is the one this store
answers with no rows at all.

`prune` stays for the window the sweep cannot cover (a course deleted after
a pump read the list it walks) and for ids written before this existed; its
comment no longer argues the sweep should not exist.

2026-08-04

fix: 🧭 name the ceiling a class refusal actually hitAhmet Kaan Gümüş · 82c0ee2
fix: 🧭 name the ceiling a class refusal actually hit

The refusal codes shipped one commit ago read the same on both axes,
but two of them mean opposite things depending on which side is being
attached: a class at its ceiling is out of course places when a course
arrives and out of seats when a student does. So adding a student to a
full section answered class_at_course_ceiling next to a sentence about
students, and a section carrying too many courses answered
class_roster_too_large. The two tests covering it pinned the wrong
answer, one of them while asserting the prose was right.

The ceiling codes now live on the axis, so each names what it hit, and
the member route gains the two it needed.

Its documentation was wrong in the other direction too: it derived the
manual code set from the pump's, which quietly promised codes only a
pump can answer — a deleted class or course is a 404 there, never a
409. Each route now states its own set, and the spec guard compares
those sets rather than searching the whole document for the strings,
which is why it never caught any of this.
feat: 🏷️ answer a manual class refusal with the pump's own codeAhmet Kaan Gümüş · 574b977
feat: 🏷️ answer a manual class refusal with the pump's own code

Attaching a course or adding a member by hand refused with an English
sentence, while the very same conditions reached through a blueprint
pump had just become machine codes. One cause, two shapes — and the
client that has to word them is bilingual.

The vocabulary now has one home on the pump's own refusal type, the
blueprint's skip list reads it from there, and the two manual routes
carry it as a code beside the sentence they already sent. Prose is
unchanged and no other route gains the field.

Coding these also exposed a claim this series had been making wrongly:
a pump attaches a course it has just proved alive, so it can never
report a stale link. Only a member add walks the section's existing
courses, and only it can answer that one.
feat: 🩺 say which sections are out of step with their blueprintAhmet Kaan Gümüş · 0684656
feat: 🩺 say which sections are out of step with their blueprint

A pump is best-effort, so it can leave a grade half stocked — and the
skip list saying which half lived in one response body and nowhere
else. A manager who closed the tab had no way back to it.

The status read answers it from the store: the template, how many
sections carry the label, and what each section is missing. A course
attached by hand counts as present, because that is exactly what the
pump does with it.

It also writes down the recovery nobody had been told: re-sending the
same list re-runs the pump, and a section can be re-stocked on its own.
A class moved to another grade keeps what the old template gave it —
which this read now shows rather than leaving to be discovered.
feat: 🔍 filter the class index by gradeAhmet Kaan Gümüş · cf0a010
feat: 🔍 filter the class index by grade

A blueprint keys on a grade label and its pump is best-effort, so a
manager can be handed a skip list naming three sections at grade 9 —
and had no way to list the sections at grade 9. The label the office
typed is the only thing tying them together, and nothing read it.

Matched verbatim, like the pump it exists to debug: a filter that
trimmed or folded would disagree with the thing it is meant to explain.
An empty value asks for the sections carrying no grade at all, which is
what an empty grade already means everywhere a class is written.
feat: 🏗️ stock a new section from its grade's blueprintAhmet Kaan Gümüş · 67ced09
feat: 🏗️ stock a new section from its grade's blueprint

Editing a template reached every section already at the grade, but
making a section reached no template — so a blueprint described every
section except the ones created after it, and the office had to
remember a second call each time.

A create now applies its grade's blueprint, after the homeroom
demotion rollback and never before it: the rollback deletes the class,
and that delete refuses while the class holds courses.

The 201 body carries the class, what could not be stocked, and which
grade's template stocked it — null when none covers the grade, which
is also what a stocking that faulted reports, because a 500 here would
strand a section whose id nothing else returns.
feat: 📊 say how many sections a blueprint pump reachedAhmet Kaan Gümüş · 81c5490
feat: 📊 say how many sections a blueprint pump reached

A grade label is free text and matched exactly, so a section typed "9 "
carries a grade no blueprint for "9" will ever find. The pump answered
that with an empty skip list, which reads exactly like every section
having taken the whole template.

It now says how many sections it walked, so nothing reached is a zero a
manager can see rather than a silence. Normalising the label was the
other way out and is not taken: the label is the blueprint's own record
id, schools spell their ladders differently on purpose, and nothing
would repair the labels already stored.
fix: 🔒 stop a deleted blueprint from stranding the rows it taggedAhmet Kaan Gümüş · b1c8e7a
fix: 🔒 stop a deleted blueprint from stranding the rows it tagged

Delete swept the course list the handler had read and then removed the
row, so a pump adding a course in between left class_course rows tagged
with a blueprint that no longer existed — reachable by nothing, since
the sweep is the only thing that reads the tag.

Delete now takes a compare-and-set on that list, removes the row first
and only then sweeps by the tag itself, so a racing addition is swept
too; the pump answers blueprint_deleted rather than landing an orphan,
claiming the blueprint inside its own transaction; and BLUEPRINT_LOCK
closes what neither could, since SurrealDB does not serialise the pump's
cross-record read against this delete. The residue is a process crash
between the delete and the sweep, which no lock survives: inert rows, a
detach each, counters exact.

The pump's created-row slot was hand-counted (7, or 9 on an axis with a
pivot claim). The guard would have shifted it silently on the only path
that uses the guard, so the statement list is built as a list and the
slot is read off its length.
fix: 🏷️ name blueprint skips with codes a client can branch onAhmet Kaan Gümüş · b7a351c
fix: 🏷️ name blueprint skips with codes a client can branch on

The pump reported a refused (class, course) pair with an English
sentence, which a bilingual client can neither branch on nor translate.
Every other enum here is an id plus a client-side label; skips now are
too, over a closed set documented on the response schema.

No information is lost: Skip already carried the class and the course as
their own fields, and neither sentence that named a record ever
interpolated it.
feat: 🎖️ earn badges on both sides of the classroomAhmet Kaan Gümüş · 46c76f5
feat: 🎖️ earn badges on both sides of the classroom

Pass 2 gave badges only to students doing their own homework. Seven new
families cover the rest of the school and the two shapes a plain tally
could not express.

Teachers earn `marks_given` (a grade recorded, once per pair — a regrade
moves nothing), `lessons_held` (credited at the first roll call taken for
a session, so a lesson scheduled and cancelled counts for nothing), and
`pool_approved`. Students earn `pool_published`, `high_mark` (an exam
mark at or above 90, once per sitting), `lessons_attended` (marked
present or late at roll call, moved back down by a correction), and
`study_streak` — the longest run of consecutive days finishing a
pomodoro, read as a high-water mark so breaking it never takes the badge
back. Days end at midnight UTC, like every other day calculation here.

Both counters of the question pool skip a self-approval: a counter moves
only when one person's work was judged by somebody else, which closes the
ask-approve-delete farm on the staff side the way crediting at approval
closes it on the student side.

Every counter moves inside the transaction of the write that causes it.
The streak needs two statements rather than one because sibling SET
clauses read the row's before-state, so `longest` would lag `current`
forever; the pair sits in one transaction, and `max` keeps it monotone
under every interleaving, verified on a real 3.2.3 server. No backfill
and no migration mark: every counter starts at zero at this deploy.
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.
feat: 🪪 give every person a public profileAhmet Kaan Gümüş · b326165
feat: 🪪 give every person a public profile

Avatar, bio, display name, live class/course blocks and read-time stat
counters, so the school has something to motivate students with.

The fields ride the user row rather than a profile table: the row already
carries the self-service columns and their field-scoped writers, so a
separate table would only add a "profile row missing" state every read
must degrade, plus a second write to the admin-seed path. DDL only, no
backfill — every pre-existing row reads null, or 0 for derived stats.

Contact fields stay off the public projection and keep their old gate.
Reads are school-wide except for parents, who reach only their own
profile and their currently-linked students'; the link and the target's
live role are re-read per call, so a promoted-out student stops being
readable at once. The courses block is intersected with what the viewer
can already see, since a course title a caller is 403'd from reading
directly must not leak through someone else's profile. stats.courses
stays the owner's true total — an aggregate reveals magnitude, not
identity — so a stranger sees an empty block beside a non-zero count.
Classes stay a narrowed id/name/grade projection: a homeroom section is
the social signal, a private club name is not.

Stats are computed at read and floored at 0. Exam average, homework rate
and attendance rate are deliberately absent: those tables are indexed
such that a per-user aggregate is a full table scan.

Avatars reuse the one-image-on-the-owning-row pattern and the school's
existing max_file_bytes, raster only. Deleting one is admin-reachable
because an offensive avatar is a real school problem and no user-delete
route exists to fall back on.

Also floors pomodoro focus time at both ends: a backwards clock could
record a negative stint, which the profile would have served as a
negative total.

No badges yet — those are auto-earned only and land next.
feat: 🧑‍🏫 invite a whole class or club to a boardAhmet Kaan Gümüş · 0e3eae0
feat: 🧑‍🏫 invite a whole class or club to a board

A board roster was one id at a time, so opening a canvas for a class
meant typing thirty of them and the cap refused an ordinary club.

POST /boards/{id}/invite names a group instead — a class section, a
course (a club is a course), or an event's roster, resolved through the
audience machinery events already had. The ids expand once, into the
same flat participants array: a snapshot, not a subscription. Live
resolution would have made is_participant, the room's door and
list_for_user cross-table queries, and would have taken per-person
removal away from the creator, which is most of what a board roster is
for. The board stores no source, so re-inviting is both how a roster is
topped up and the one thing that undoes a removal.

Additive only; removal stays PATCH. The participant cap moves 50 -> 200
and is all-or-nothing — a partial invite would silently pick which half
of a class gets to draw. Ineligible members (gone, or below student, or
already there) drop silently, because one of them must not fail the
invite for the other twenty-nine.

The gate is not a new permission: a roster is visible to everyone on the
board, so inviting a group discloses it, and each source carries the
gate its own listing route carries. Bulk invite is therefore teacher+;
a student can still build a board by hand but cannot pour a class into
one.

resolve_participants now batches its lookup. It read one row per id,
which at the new cap made a read-modify-write PATCH of a class-filled
board — the ordinary client shape now — two hundred sequential reads.

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.
fix: 🔩 make ownership a live grant, not a permanent oneAhmet Kaan Gümüş · 8c0ba1e
fix: 🔩 make ownership a live grant, not a permanent one

Creating a course, teaching a session, publishing an event, owning a bank
template — each of these granted rights forever, whatever role the
account held afterwards. `set_role` swept the course *assignment* list on
demotion but never the creator link, and none of the ownership helpers
re-read the caller's role, so an account demoted to `student` or
`parent` kept management of everything it had ever made.

That was reachable over plain HTTP, not theoretical. Several routes take
`CurrentUser` rather than `RequireTeacher`, so a demoted creator still
read draft exams — defeating the 404-not-403 rule that exists to hide a
draft's very existence — still listed and read that course's homework,
and still saw the course in every catalogue. A demoted session teacher
still read their session with no course rights at all.

Every ownership arm now carries a live `teacher` floor, enforced inside
the helper rather than trusted from the caller:

- `can_manage_course` and `owns_course`, plus `visible_courses`, which
  fed the id sets behind `/courses`, `/exams` and `/homework`;
- `is_live_session_teacher`, replacing a bare `session.is_teacher`;
- `can_manage` for events and for appointment slots;
- `can_see` and `ensure_owner` for the question bank — floored whole, not
  only on the owner arm, since gating one arm would have left a demoted
  owner locked out of their own private template while still reading
  every school-wide one, the strictly larger set.

The `creator`, `owner` and `teacher` columns are deliberately not swept.
They answer "who made this", which stays true after a demotion; it is
the grant that is conditional, not the history.

The helpers carried a comment claiming callers had already cleared the
teacher bar via `RequireTeacher`. It was false at five call sites and had
been since the first `CurrentUser` route was added — nobody rechecks a
comment. The appointments copy was false twice over: it justified an
exception for `cancel` reaching the helper, and `cancel` is
requester-only and never calls it. That phrasing is now extinct in this
codebase, which matters more than the individual fixes: a helper that
trusts its callers is one extractor change away from this bug.

Each floor is pinned by a test that fails when the floor is removed, and
the no-orphan side by tests that fail when a floor is made too strict —
manager and admin clear the `teacher` bar by definition, so nothing is
left unadministerable. The bank's admin arm had a test that passed
vacuously, asserting against a school-visible row where the school arm
alone would grant; it now asserts on a private template owned by someone
else.

Verified against the real volume: on unswept rows, a demoted creator
loses the catalogue, the draft, the homework and the session, while
manager, admin and still-teacher accounts keep everything, and no
pre-existing row became unreachable.

Left standing: `set_role` still writes the role before its sweeps and
they are not one transaction. Every sweep is idempotent and, now that
rights are re-read live, grants nothing in the meantime.
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.
fix: 🔩 close the leaks a five-domain hunt turned upAhmet Kaan Gümüş · a3fe8cf
fix: 🔩 close the leaks a five-domain hunt turned up

Five hunters swept exams, homework/attendance, identity, money/scheduling
and messaging/courses; a three-lens verifier panel then refuted three of
the first fixes, and those corrections are folded in here.

Leaks and races closed:

- exam self-review gated on *any* mark, so a seq-1 grade opened the
  answer key forever — a student mid-retake read `correct` and
  `is_correct` off the sheet they were still writing. All four review
  reads now 409 while the caller's latest sitting is in progress.
- roll call could land after its session was deleted, and the orphan was
  unremovable (its delete route 404s on the vanished session) while the
  attendance report went on counting it. The write now proves its parent
  exists in the same transaction, the way ExamResult::grade does.
- a teacher could counter-propose and then approve their own proposal,
  committing the requester to a time only the teacher ever named; and
  even after that, re-proposing between the requester's read and their
  accept moved the meeting under them. Approve refuses while a proposal
  stands, and accept now pins the window it is answering.
- two concurrent chatbot posts on one thread cross-attributed their
  answers — both replied to the second prompt, the first was never
  answered. The prompt id rides the request instead of being re-derived
  from write order.
- a whiteboard participant demoted to `parent` kept drawing, and kept
  *reading* the live canvas for up to 15s. Every frame is authorized
  before delivery now, and a demotion sweeps the account off rosters.
- a demotion to `parent` stranded event signups no one could free.
  Promotions are left alone (staff free their own seats) and closed
  lists are never rewritten.
- the rate-limit bucket map was unbounded past 10k live keys and then
  scanned O(n) under the global mutex on every request. Eviction is
  bounded and never frees an exhausted bucket — the first attempt did,
  which traded a memory bug for an auth-bypass, so it is pinned by a
  test that floods at the victim's own spend.
- session and event cascades ran as loose queries; a concurrent write
  slipped between them and orphaned rows, and for notes a blob nothing
  could ever reclaim. All three are one transaction now.
- sixteen id generators still used Ulid::new(), whose random low bits
  scramble same-millisecond rows under the "newest first" the docs
  promise; five listings had no tie-break at all, so offset paging could
  skip or duplicate a row.

Also: $session is a protected SurrealDB 3 variable — binding it fails
the whole query as a bare 500, which is what hid the attendance fix.

Accepted, documented, not fixed: one bank template instantiated into two
exams copies `correct` into both, and the review gate is per-exam.
fix: 🔩 close the bug hunt across meals, classes and capsAhmet Kaan Gümüş · 7198cea
fix: 🔩 close the bug hunt across meals, classes and caps

A three-domain hunt, its fixes, and a verifier panel that refuted two of
them. Kept as one commit because the pieces interlock — cap.rs, the
settings pair and the pump all move together, and no smaller cut compiles.

Money can no longer be lost or stranded. Both seat transitions carry
their ledger line inside their own transaction: the claim writes the
charge, the flip writes the reversal. Before, a crash between the two
left a seat held with no bill, or a bill with no seat, keyed to an
attempt no later request could ever reach. A lost cancel could refund a
live seat. The menu revision was bumped in a query of its own, so a
booking reading in the gap claimed against a capacity or a price the
menu had already left.

Deleting a menu now takes its marks and its dishes with it, in the
transaction that deletes the row. The id is deterministic on (date,
slot), so anything left behind came back on the next publish — the
kitchen reading "served" for a student who never came.

A seat is always releasable: manager+ cancels any booking and is not
bound by the cutoff, so a promoted student's seat no longer wedges its
menu forever, and a debt that outlived its owner's role can be settled.
Canteen money follows /payments and is manager+, not teacher+ — what a
family owes the school is not classroom information.

The class pump claims its pivot in-transaction. An attach racing a
course delete used to commit a link to a row that was gone, and nothing
could then detach it or delete the class. A hand enroll now disowns a
pumped row, so a sweep cannot take back a roster decision an operator
made by hand. The role sweep is one transaction. Rosters are ordered by
when a student was added, which is what they always claimed. Both class
axes have a ceiling, and each refuses on the other's, because a pump
writes one row per member per course in a single transaction.

Settings edits are serialized: retire is idempotent, so an undo log
cannot tell the attempt that flipped a name from one that found it
already flipped, and the loser un-retired what the winner had legally
retired — leaving a kind gone from the list, gradable, and unremovable
for good. Grading now checks the school's list, not only the counter.
Three caps that read a snapshot integer now read the live column.

A clear marker is charged to the board's lifetime counter and boot
repairs the boards that predate it. Blank canvases refuse the clear, and
the room reports that as its own code: the refusal text had drifted into
the substring the WebSocket read as "closed", which told a live room it
was permanently read-only.

Verified against the real volume: both boot backfills, the slot-name
rule and its grandfather clause, and the new money gate.

2026-08-01

2026-07-31

fix: 🚫 keep parents off the whiteboard entirelyAhmet Kaan Gümüş · 860b4ce
fix: 🚫 keep parents off the whiteboard entirely

A parent is the school's read-only observer, but every board route was
`CurrentUser` only — so a parent could open a board and draw on it.

The cut that does the work is in `resolve_participants`: a parent id is
refused as a participant, so a parent is never on a roster. That alone
makes `board_for` and the room's door answer the outsider's 404 on every
id-scoped route. `POST /boards` and `GET /boards` take `RequireStudent`
(a 403 there leaks nothing — no board exists to hide), while the read
path and the socket door re-check the role and answer 404, never 403,
which would confirm the board is there. Refusing the door is also what
stops a parent drawing: no socket, no `stroke` frame, and no per-stroke
role read on the hot path.

A board row written earlier that still lists a parent is inert — that
parent now sees a 404 for it like any stranger.
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: 🖍️ 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-30

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.
feat: 🎨 sync the accent color like theme and languageAhmet Kaan Gümüş · 9490623
feat: 🎨 sync the accent color like theme and language

The frontend's palette picker kept the chosen accent in localStorage, so
it never followed the user to another device. `palette_color` joins
`theme` and `language` as a third per-user preference: a nullable hex
color on the user row, self-managed and admin-editable through the same
two PATCH routes, `null` until chosen.

The value set is deliberately open — any `#rrggbb` — rather than an enum
of the frontend's palette entries, so adding a palette is a frontend-only
change. Mixed case is accepted and stored lowercase, which is why
`/limits` publishes the accept-set pattern (`^#[0-9a-fA-F]{6}$`) and not
the storage form: a client validating its own input against the published
regex has to agree with the server, and a test now compiles that regex
and runs it over the validator's own accept/reject examples.

2026-07-29

fix: 🔁 make a retried payment one payment, and page the statementAhmet Kaan Gümüş · 4fe02bc
fix: 🔁 make a retried payment one payment, and page the statement

A client that resends POST /payments/credits or /refunds after a
timeout may now carry a request_key; the line's id derives from
(target, kind, key), so the replay reads back the recorded line
instead of minting a second one, even when it filled the charge to
the brim. Same key with a different amount or target is answered 409
— the stored line never bends to a retry. Keys are letters, digits
and '-' only: '_' joins id parts, so a key like 'abc_r' could spell
another line's reversal id; append() now also refuses to hand back a
line of another kind, turning any future grammar slip into a 500
instead of money on the wrong line.

Statements page their per-charge rows through the usual
?limit&offset envelope; the balance and every rollup still fold the
whole ledger before the window is cut.
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: 🗳️ 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 handing out a register id that matches no userAhmet Kaan Gümüş · 14334bc
fix: 🆔 stop handing out a register id that matches no user

The uniform-201 answer to a taken username carried a freshly minted ULID
so the two paths would look alike, which meant a client storing
`response.id` held an id resolving to nothing.

Register now answers `{username, role}` — the only facts true of both
paths — built once before the branch, so a divergent body is not
something a later edit can reintroduce by hand. The anti-enumeration
behaviour is unchanged: same 201, same bytes, argon2 still paid before
the availability check.
fix: 🕛 anchor the meal cutoff to when lunch is actually servedAhmet Kaan Gümüş · 21f4643
fix: 🕛 anchor the meal cutoff to when lunch is actually served

The booking and cancel deadline counted back from midnight UTC of the
menu date, so a two-hour cutoff on lunch barred bookings from 22:00 the
day before. Meal slots now carry an optional serving time and the
deadline counts back from that; a slot without one keeps the old
midnight behaviour, so nothing changes until a school sets hours.

Times are minutes past midnight UTC. There is deliberately no school
timezone setting, so a UTC+3 school enters 09:00 to mean noon; the
field says so wherever it is described.

Serving time is looked up live rather than snapshotted onto the menu,
because the cutoff minutes already are — freezing one half of a
deadline and not the other would split a single policy in two.

Storing an Option inside an object turned out to break the settings
CAS. SurrealDB drops an object key whose value is NONE, and a stored
{name} never again equals the {name, serving_minute: NONE} the derive
emits, so every PATCH /settings would have answered 409 forever for any
school whose slots predate this field. The guard now compares a rebuilt
projection. Verified against the live volume, whose singleton is
exactly that aged shape.

Also: losing a race to write a ledger line returned 500 rather than the
line the winner had already written. A duplicate record id is now read
back instead, matched on the typed error so real database failures
still surface.
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.
docs: 📝 make the docs match what appointments and the bank actually doAhmet Kaan Gümüş · 25747d8
docs: 📝 make the docs match what appointments and the bank actually do

Three appointment commits changed behaviour and moved none of the three
doc surfaces this repo keeps in step.

- a2613cd made cancel requester-only, but README (intro, route table,
  section), both lib.rs mentions, the cancel operation's own OpenAPI
  description and the domain rustdoc all still said "either side, the
  requester or the teacher". Swagger UI was documenting a call that is
  now a guaranteed 403. All corrected, and each says what the teacher
  does instead — reject while pending, or reschedule then reject
- 6dd0c0e's overlap 409 was missing from `publish_slots`' responses, the
  README slot section and the tag; documented, including that touching
  boundaries are legal and the guard is per-teacher
- d0d2883's `cancelled_by`/`decided_by`/`cancel_reason`/`reject_reason`
  appeared nowhere in README; documented with their audience (requester
  and the slot's teacher) and that legacy rows read null

Also: the choice-image routes were not missing from the endpoint table,
they were stale — spelled `/choices/{index}/image` since dde4896 made
choices id-keyed. Renamed to `{choice_id}`, and the rustdoc that still
called it a zero-based position corrected. `refresh-from-bank` added, and
`## Layout` gained `field_update`, `monotonic_id`, `text_fold` and
`etag`. The register section now records that the uniform 201 is a
deliberate anti-enumeration measure, so nobody restores the 409.
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).
✨ feat(exams): let students read the answer key in self-reviewAhmet Kaan Gümüş · e9ffc5e
✨ feat(exams): let students read the answer key in self-review

Student self-review rendered the answer sheet but had no way to fetch
the questions — GET /exams/{id}/questions is teacher-only (it exposes
the `correct` index). Add a self-scoped GET /exams/{id}/review/questions
returning the full QuestionResponse (with `correct`) behind the same
reviewable_exam gate: draft->404, review off->403, unmarked caller->404.
Revealing the key is the point — the gate proves the caller was marked.

list_questions and review_questions now share question_page(); they
differ only in the access wall (can_manage_course vs reviewable_exam).
Browser-verified: student review renders questions + answers + drawing
playback end to end.
✨ 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.
✨ feat(messages): let a sender archive their own copyAhmet Kaan Gümüş · 24dba16
✨ feat(messages): let a sender archive their own copy

Filing was asymmetric: a recipient could move their copy to
inbox/archive/trash, but a sender only to sent/trash — so a sent
message could never be archived, only trashed. Add `archive` to the
sender's allowed folders.

The archive folder view now unions both sides, matching how trash
already works, so a sender's archived copy actually shows up in the
archive list (previously the query was recipient-only for archive).
Origin-stamping and restore are folder-generic and already handle it:
a sender archiving from `sent` restores back to `sent`.

Doc surfaces (utoipa move-request + list docs, the messages and core
tag descriptions, README route table and messaging section) moved with
it; the folder-parse test now asserts both sides may archive while the
sender still cannot reach the inbox.
🎨 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.
✨ 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.