forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to src/domain/user.rsClear filter

2026-09-23

✨ feat(profile): add gender, address, and emergency contact to the user row Local-Gate: 1f2b0abcf3798a63b2c5365e0d15c9f708f45833 (1523 passed, 430s)Ahmet Kaan Gümüş · f151345
✨ feat(profile): add gender, address, and emergency contact to the user row
Local-Gate: 1f2b0abcf3798a63b2c5365e0d15c9f708f45833 (1523 passed, 430s)

2026-09-20

✨ feat(users): give students a school-issued student numberAhmet Kaan Gümüş · 777c7df
✨ feat(users): give students a school-issued student number

Every school numbers its students its own way ("1234", "9-B/17"), and the
account carried no field for it: the office kept the mapping outside the
product. The number is now a first-class optional field on the user row,
unique inside the school (per-school uniqueness is the per-school database)
and held by students only.

- migrations/school/20260920000001_student_number.sql: `app_user
  .student_number TEXT NULL`, the partial unique index over its non-NULL
  values, and a CHECK (student_number IS NULL OR role = 'student'). The boot
  sweep applies the file to already-provisioned schools like every other
  school migration.
- domain: `StudentNumber`, a validated newtype (trimmed, non-blank, at most
  MAX_STUDENT_NUMBER_LEN = 32) in the shape of `Username`, plus the one
  spelling of the non-student refusal both the web gate and the database map
  answer; `User` carries `Option<StudentNumber>`.
- db: `create_with_role` binds it into the mint; `set_profile` writes it and
  maps the index's 23505 to the coded 409 and the row's 23514 to the same 400
  the handler gate answers; `set_role_cascade` clears it in the same statement
  that leaves the `student` role. The CHECK is what closes the read-then-write
  race the handler-side gate cannot see: a profile save carrying a number from
  a `student` snapshot while a promotion commits first is refused by the row
  itself, and a test pins exactly that (it writes a teacher holding a number
  without the CHECK).
- web: `POST /users` and both profile doors (`PATCH /users/me`,
  `PATCH /users/{id}/profile`) accept it under the merge semantics the other
  patchable fields have (omitted = keep, blank = clear), with the role gate as
  a 400 and a duplicate as a 409 carrying `code: student_number_taken`.
  `UserResponse` (admin reads, create/patch echoes, `/auth/me`) and `PersonRef`
  (pickers, students lists) carry it; the school-wide public profile
  deliberately does not — an office identifier is not broadcast school-wide.
- /limits publishes `max_student_number_len`; spec_bounds pins both new
  `max_length` annotations and the README's bound count moves to 224.
- tests: the mint and both patch doors — trimmed storage, 33 chars a 400,
  whitespace read as absent, a duplicate a coded 409 on both paths, a
  non-student a 400, blank clearing, a promotion clearing with the role change
  (and a demotion back not restoring it), and the stale-snapshot race at the
  db layer.

Evidence: the partial index refuses a duplicate (23505 naming
app_user_student_number) and admits both rows once dropped inside a
rolled-back transaction; with the 409 mapping removed both write paths answer
500 and the tests fail; with the CHECK removed the race test writes the
forbidden row (role: Teacher, student_number: Some(...)) and fails.
Local-Gate: 2c10aae51c575b7f4207fa310d8938070c0fbb80 (1509 passed, 572s)

2026-09-17

📝 docs: rewrite the Turkish comments and doc comments in EnglishAhmet Kaan Gümüş · 7fec874
📝 docs: rewrite the Turkish comments and doc comments in English

The Rust repo's own language is English; Turkish had leaked in from the
sibling AI services. Translate every comment and doc comment to English
using the code's own vocabulary (şube -> class section, dönem -> term,
sınıf öğretmeni -> homeroom teacher, ortak sınav -> shared exam, karne ->
report card, …). Quoted Turkish letters/words that are themselves the
data under test (the text-fold examples in `text_fold`/`settings`, the
non-ASCII filename sample) are kept.

The README endpoint table is generated from those doc comments, so it is
regenerated. AGENTS.md records the convention going forward: Turkish
survives only where it is the data under test or user-visible content.

2026-09-16

✨ feat: the class×course instance is the academic anchor (K-12 remodel)Ahmet Kaan Gümüş · ae84034
✨ feat: the class×course instance is the academic anchor (K-12 remodel)

`course` was a school-wide singleton: enrollment, exams, sessions,
roll-call and homework all keyed on it, so two class sections teaching the same
course shared one roster, one exam set and one timetable. This moves the
academic anchor to `class_course` — the per-class instance — and rebuilds
the academic model around Turkish K-12.

Schema (migrations/school/20260916000001_k12_remodel.sql): `class_course`
becomes an instance (ders_saati, counts_toward_karne, enrollment_count,
class_course_teacher); enrollment re-keys to (class_course, app_user);
exam carries class_course + term (+ exam_audience for shared exams);
course_session / session_attendance / homework re-key; `class_member` is a
soft-leave history table (uuid PK, joined_at/left_at, partial unique index
on the live stint); `academic_year` sits above `term`; `class_group` links
a year, not a term; new `course_membership` (clubs/study), `karne_snapshot`;
settings gain branches/excuse_kinds/absence limits/timezone; profile gains
branch. Drops/recreates the identity-changing tables (pre-customer; the
migration resets every counter on a kept table that pointed at a dropped
one).

Layers: domain/db/service/web rewritten to the instance seam, with
`ensure_instance_teacher` gating instance writes (D10), the report card computed per
instance and weighted by ders_saati, an absence report, `/instances`
and `/academic-years` nests, and `/classes/{id}/instances`. Capacity and
the seat-claim 409 are gone; detach sweeps the whole instance subtree and
unlinks its blob keys.

Gates: cargo check --all-targets, SQLX_OFFLINE check (cache regenerated),
doc_sync, spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1370/1370.

2026-09-14

🗃️ feat: pre-prod schema: person join key, drop school password copyAhmet Kaan Gümüş · 804bd3c
🗃️ feat: pre-prod schema: person join key, drop school password copy

app_user no longer stores password_hash (login already verifies
control person). School rows carry person uuid + created_at.
class_blueprint is uuid-keyed; exam child rows composite-FK to
(exam, question); pool/solution images are child tables;
graded_at/marked_at/enrollment timestamps added.

Left alone: occupancy/refcount counters (cap locks, not lies),
ledger source, menu derived id, school.slug PK, fee_plan JSONB.

2026-09-12

2026-09-11

🧹 chore: split note/session/settings into domain/db/service layersAhmet Kaan Gümüş · efea304
🧹 chore: split note/session/settings into domain/db/service layers

Pilot wave of the three-layer split. All query execution for the three
domains now lives in src/db/{note,session,settings}.rs as free fns taking
db first; web handlers call service::<x>::* only; domain keeps pure types.

- service/settings.rs gains the PATCH workflow (apply) and SETTINGS_LOCK —
  it spans a multi-call pair (retire names, CAS save, restore), so it is a
  service lock, not a db lock. The service takes its own input records
  (SettingsPatch/*Input) so wire DTOs stay in web and list validation keeps
  its original order, including the try_kept grandfathering that needs the
  stored list.
- Note/Session/Settings fields the db layer mints or CAS-binds become
  pub(crate); Settings::record_id becomes pub(crate).
- Unit tests rode with their fns: note delete cascade → db/note, session
  purge → db/session, settings load/save/CAS → db/settings, the whole
  settings edit workflow suite → service/settings.
- Doc links re-pointed (user, class_blueprint, bank_question, exam,
  note_file, tests/regress_roles); NoteId::generate's stale
  'Note::list_for_user' link now names db::note::list_for.
- Known residual for a later wave: web/notes.rs:411 file.delete() is
  note_file-domain persistence (note_file splits in C3).
🧹 chore: drop stale multi-replica prose; single process is the contractAhmet Kaan Gümüş · 8b8a45d
🧹 chore: drop stale multi-replica prose; single process is the contract

2026-09-07

🔒 fix: telemetry privacy sweep, in-flight gauge guards, request-id validation, tenant gauge on createAhmet Kaan Gümüş · ae0957a
🔒 fix: telemetry privacy sweep, in-flight gauge guards, request-id validation, tenant gauge on create

- No account name reaches an exported log record: the admin seed
  (domain/user.rs), the ADMIN_USERNAME refusal and the builder seed
  (domain/builder.rs) log the event without the `username` field.
- The forbidden-key list moves to tests/common (`FORBIDDEN_TELEMETRY_KEYS`,
  `is_forbidden_key`), gains `username`/`email` and the header prefixes, and
  is used by both the HTTP-edge and the AI-bridge guard tests. The telemetry
  suite now also exports tracing EVENTS through an in-memory log exporter and
  holds log records to the same rule.
- `http.server.active_requests` and `ai_requests_inflight` are closed by a
  `Drop` guard, so a dropped request future (client hang-up, outer timeout)
  no longer leaks the gauge upwards. A cancelled request is recorded as 499.
- A caller-supplied `x-request-id` is only kept when it is at most 64 chars of
  `[A-Za-z0-9._-]`; anything else is dropped and a UUID is minted, so a client
  cannot write free text onto `http.request.id` of every span.
- `tenant_cache_size` is reported by `Tenants::create` and by the bootstrap
  insert, not only by the lazy-dial path.
- The keepalive logs its first `up` verdict, which its comment already claimed.

Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s

2026-09-05

✨ feat: builder API — the vendor creates, suspends, enters and deletes schoolsAhmet Kaan Gümüş · 1ab298d
✨ feat: builder API — the vendor creates, suspends, enters and deletes schools

`POST /builder/login|logout`, `GET /builder/me`; `POST|GET /schools`,
`GET|PATCH|DELETE /schools/{slug}`, `POST /schools/{slug}/admin-password`,
`POST /schools/{slug}/enter`. Builder sessions live in the control database
behind their own strict per-IP login tier; deleting a school drops its
database and its files subtree.
✉️ feat: messages go upward only; students and parents can search staffAhmet Kaan Gümüş · 1d423c0
✉️ feat: messages go upward only; students and parents can search staff

A student or parent may only write to a teacher, manager or admin
(`Role::may_message`); staff still write to anyone. `POST /messages`
answers 403 below that bar, and only new sends are gated — stored
student↔student rows stay readable and filable.

`GET /users/search` opens to every signed-in role: a caller below
teacher sees only the staff they may message (the restriction sits in
the query, so `total` stays right), and asking for `role=student` or
`role=parent` from there is a 403. This is the recipient picker the
messaging rule needs.

Closes #23, closes #24.

2026-08-12

🤖 feat: add service-only Role::AiAhmet Kaan Gümüş · 3a01d26
🤖 feat: add service-only Role::Ai

The principal an out-of-process AI service carries over the QUIC bridge.
Declared first in the enum so the derived Ord puts it under every role: it
clears no `at_least` bar and fails every exact `== Role::Student` /
`== Role::Parent` gate. Absent from ROLES, which is what makes it
unassignable — `try_from_str` searches that table, so "ai" is rejected like
any unknown word, and /limits keeps listing the five human roles. Role still
carries no serde derive, so nothing deserializes it off the wire.

`User::ai_principal` builds it in memory only, on the literal record key
`ai_service` that no minted ULID can collide with, with an empty password
hash that verifies against nothing. Never written to the database.

The web DTO gains the variant because the mapping is exhaustive, so "ai"
appears in the OpenAPI Role schema — documented there as never assignable.

2026-08-05

🖍️ fix: close a whiteboard whose creator was demotedAhmet Kaan Gümüş · 26e7470
🖍️ fix: close a whiteboard whose creator was demoted

A board's creator demoted to `parent` left a room nobody could command.
The whiteboard is shut to that role outright, so the creator was answered
404 on their own board; clear, lock, close and delete are the creator's
alone, so every other participant was answered 403; and
`Board::list_for_user` is the crate's only enumeration, so no manager or
admin could so much as find the id. Meanwhile the participants kept
drawing (the room re-derives membership per frame and they still pass)
into a board only the 50 000-stroke lifetime cap could ever retire — and
`Board::delete`, the sole releaser of `board_count` and the sole deleter
of `board_stroke`, was unreachable forever.

The demotion now stamps `closed_at` on every board the account created,
in `set_role`'s own transaction and with the same compare-and-set
`Board::close` uses, so an already-closed board keeps its first stamp.
Written before the roster strip, so the strip's `RETURN AFTER` carries
the closed row the caller fans out — as a `closed` frame beside the
`participants` one, which is what turns the open sockets read-only.

Closed and not deleted: the marks are the other participants' work too,
so the board, its history and its epochs stay readable and only writes
are refused (`board_closed`, terminal). The cost is accepted — the
creator's `board_count` seat stays taken, which is correct while the row
it counts still exists, and the strokes stay on disk.

The concurrent half needs nothing: `Board::create` claims the creator's
own user row (`cap::claim_and_create` on `board_count`), the very record
this transaction writes `role` on, so a board opened while the demotion
runs collides in the store and one side re-sends — it cannot slip past
the sweep.
📅 fix: withdraw the calendar a demotion used to leave unreachableAhmet Kaan Gümüş · e879fd3
📅 fix: withdraw the calendar a demotion used to leave unreachable

`set_role`'s below-teacher arm dropped course staffing and the homeroom
column and stopped there, so a demoted teacher's `appointment_slot` rows
outlived the role that published them — and no route could reach them
again: the teacher+ branch of `list_slots` lists the caller's OWN slots,
so no manager ever learns the id; the below-teacher branch filters out
slots whose owner is no longer staff, so neither students nor the demoted
owner see them; and both slot deletes are `RequireTeacher`. One
undeletable row per slot ever published, forever.

A live booking on one was worse. `approve`/`reject`/`reschedule` go
through `for_decision`, which needs `can_manage` AND `RequireTeacher`:
the demoted owner fails the extractor, and the manager who would pass
`can_manage` has no route that yields the id. The requester's `cancel` is
refused once the window opens. So the booking sat `pending` in their list
for good, pinning the slot's `occupied` at one — which also makes
`delete_free`'s `(occupied ?? 0) = 0` guard unsatisfiable.

The sweep now runs in the role write's own transaction, beside the other
arms: live bookings are flipped to `cancelled` with the ex-teacher on
`cancelled_by` and the reason on `cancel_reason`, then the slots go.

Cancelled rather than deleted, deliberately. Deleting them is what the
slot's own delete cascade does, but that path refuses while a booking is
live — precisely because someone is expecting the meeting — and a
demotion cannot refuse. This crate has no notification of any kind, so
the strongest defined end available to a requester is a settled row they
can still read, naming who dropped it and why; deleting it would make a
confirmed meeting vanish with no trace at all. The slot goes either way,
which is what releases the seat and keeps this convergent; the booking
then renders without a window, the shape `AppointmentResponse` already
documents for a vanished slot.

The race is closed at both ends. A booking landing mid-demotion claims
the slot row the sweep deletes, so the store settles it. A slot
*published* mid-demotion shared no key with anything the demotion wrote
and survived it, so `AppointmentSlot::create`/`publish_weekly` now claim
the publisher's own record (`cap::role_claim`, the enrollment/registration
pattern): either the sweep sees the slot, or the publish sees the new
role and answers 403.

Tests: the sweep and the refusal are unit-tested (both go RED on the
reverted fix), and the publish-vs-demotion race is a real-server test
held open with a DEFINE EVENT — 4/4 rounds strand a slot without the
claim, 0/4 with it.
👤 fix: keep a school from losing its last adminAhmet Kaan Gümüş · bd9005e
👤 fix: keep a school from losing its last admin

set_role blocked only self-demotion. Two admins each demoting the other
resolved both RequireAdmin extractors before either transaction
committed, so both writes landed and no admin remained — and
ensure_admin refuses to promote an existing non-admin row on later
boots, so recovery meant hand-run SurrealQL against the volume.

ADMIN_FLOOR_LOCK now serializes every demotion with a last-admin check
that asks the live rows, not a possibly-stale snapshot. The 409 is
unreachable sequentially over HTTP — demoting an admin requires a second
admin — which is why the guard lives in the writer.

students_page listed parent links without re-reading the student side's
live role, unlike every other reader. Stale links already on the volume
go inert with no migration.

2026-08-04

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.

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: 🔩 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.

2026-07-30

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-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.
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: 🔑 bound argon2's memory, and stop register leaking usernamesAhmet Kaan Gümüş · d31f9ce
fix: 🔑 bound argon2's memory, and stop register leaking usernames

Two auth problems, both about a cost paid off the request path.

684f18b correctly moved argon2 onto `spawn_blocking`, but that pool is
unbounded: tokio grows it to 512 threads and argon2's default `m_cost`
is 19 MiB, so a distributed login flood could claim ~8.7 GB and get the
process OOM-killed. Before the move, concurrency was implicitly capped
at the 12 async workers. A semaphore of `nproc * 2` now gates all three
wrappers — 200 concurrent hashes drop from ~2.2 GB to ~0.63 GB peak RSS
with no wall-clock cost, since throughput was already core-bound. Both
login branches take a permit, and a (impossible) closed-semaphore error
maps exactly like a pool panic does, so no branch becomes
distinguishable by status.

The decoy hash is also pre-warmed at boot, off the runtime: it used to
initialise lazily, so the first unknown-username login paid two argon2
hashes instead of one and stood out.

`POST /auth/register` answered 409 on a taken username, which handed out
the entire user list to anyone unauthenticated and made the login-side
decoy that 684f18b preserved decorative. It now answers 201 with a body
shaped exactly like a real creation. The write is still rejected — only
the response is uniform. Register already hashed before the availability
check, so both paths already cost the same argon2 work; a comment and a
timing floor in the test pin that ordering, since reversing it would
re-open the oracle by latency.

Accepted cost, deliberately: a user who collides gets no distinct error.

The three tests that proved their point *via* the 409 could not just be
flipped to expect 201 — that would assert nothing. They now observe the
rejection where it is still visible: exactly one row exists, and the
first registration's password still logs in while the duplicate's is
refused. That is strictly stronger than the old assertion, which never
checked that the row had not been overwritten.
fix: 🧩 finish the partial-PATCH sweep — 4 more handlers lost writesAhmet Kaan Gümüş · d773e7e
fix: 🧩 finish the partial-PATCH sweep — 4 more handlers lost writes

32bca26 routed six resources through `FieldUpdate` so a PATCH writes only
the fields it was given. It stopped at six of ten. The remaining four
still read the row unguarded and then wrote a field-scoped `SET` bound to
that stale snapshot, so two concurrent PATCHes of different fields
reverted each other, 200 OK, silently:

- subjects and the two user routes (`apply_profile`/`apply_preferences`,
  four endpoints) move to `FieldUpdate`. No lock needed — neither has a
  cross-field check, so request-scoped values alone close it
- course sessions get `SESSION_LOCK`, taken *before* the row read
  whenever `starts_at`/`ends_at` arrives, with the range merged and
  revalidated against the stored other end. The lock is not optional:
  converting to `FieldUpdate` without it re-introduces 9e25e0c, verified
  by disabling it and watching a one-ended PATCH store
  `starts_at > ends_at` with both requests answering 200
- bank questions instead take `BANK_LOCK.write()` before `owned_question`.
  This one is a genuine read-modify-write — the kind/choices/correct
  trio must merge from the stored row because choice ids carry the option
  pictures — so an exclusive lease over read+merge+write is the fix, the
  same shape as the exam PATCH. Per-field writes cannot express it
- `subject.rs` also mints ids via `monotonic_id::next_ulid()` now, since
  subjects list `ORDER BY id ASC`; `bank_questions.rs` rustdoc stops
  calling a choice id a position

Also verified safe and left alone: the exam and exam-question PATCHes
already hold `EXAM_LOCK.write()` across read and write, settings uses a
CAS retry, and messages/chatbot/questions/appointments write single
fields.

Each new suite races 20 rounds and reads the row back; every one fails if
the stale refill is restored.
fix: 🇹🇷 split the fold: search collapses letters, identity must notAhmet Kaan Gümüş · 50966f8
fix: 🇹🇷 split the fold: search collapses letters, identity must not

c19dcea deduped the settings lists by folded word, but the fold it used
is a destructive ASCII collapse — `ı`, `İ`, `I` and `i` all become `i`,
`ü` becomes `u`. Correct for search, wrong for identity: it made
genuinely distinct Turkish words collide, so a school could not have
both a "tur" and a "tür" exam kind. The second was rejected 400 with no
way to override.

- `text_fold::case_fold_tr` is the new identity fold: Turkish casing
  only (`i`↔`İ`, `ı`↔`I`, plus decomposed `İ`), conflating no letters
- `fold`/`fold_sql` become `search_fold`/`search_fold_sql`. They keep
  the destructive collapse, which is a feature there — typing "tur"
  should still find "tür", and an ASCII keyboard should match accented
  data. The vague old name is part of why this went wrong
- settings dedup switches to `case_fold_tr`; the two search call sites
  keep the collapse, unchanged in behaviour

Relaxation only: `case_fold_tr` equal implies `search_fold` equal, so no
stored row becomes invalid and nothing needs migrating — previously
rejected values simply become legal. `ExamKind`/`AttendanceStatus`
lookups match byte-exactly, so newly coexisting entries stay
individually resolvable.

Tests pin both directions: `TÜR`/`tür` and `KIR`/`kır` fold together
while `tur`/`tür` and `kir`/`kır` do not — and each of those is asserted
still equal under `search_fold`, so the collapse stays deliberate.
fix: 🔑 argon2 no longer starves the async runtime - hash and verify passwords on `spawn_blocking`; argon2 is deliberately CPU-expensive, so running it on an async worker stalled the whole runtime and pushed requests past `REQUEST_TIMEOUT_SECS` into a 503 - login verifies in the match arm instead of a match guard, since guards cannot await - the decoy verification that hides username enumeration moves off the runtime too, along with the one-time decoy hash - the seed's admin hash goes through the same path - make the blocking `hash`/`verify`/`verify_decoy` private so no request path can call them again by accidentAhmet Kaan Gümüş · cf04258
fix: 🔑 argon2 no longer starves the async runtime
- hash and verify passwords on `spawn_blocking`; argon2 is deliberately
  CPU-expensive, so running it on an async worker stalled the whole
  runtime and pushed requests past `REQUEST_TIMEOUT_SECS` into a 503
- login verifies in the match arm instead of a match guard, since guards
  cannot await
- the decoy verification that hides username enumeration moves off the
  runtime too, along with the one-time decoy hash
- the seed's admin hash goes through the same path
- make the blocking `hash`/`verify`/`verify_decoy` private so no request
  path can call them again by accident
fix: 🔎 Turkish search folding for users, per-question exam-room errorsAhmet Kaan Gümüş · e0f9d63
fix: 🔎 Turkish search folding for users, per-question exam-room errors

- User::search folded its needle with Rust to_lowercase and its columns
  with SurrealQL string::lowercase; both turn İ into i + U+0307, so
  searching "ilker" never found "İLKER". It now runs both sides through
  the shared text_fold table, like the question bank already does
- exam-room error frames carry question_id when the failure belongs to
  one save — a validation reject or an unknown question, raised inside
  the save past the sitting gates. The client could not tell which save
  failed and had to fail every one in flight
- auth, conflict, malformed-frame and database errors stay unattributed
  on purpose: they doom the next save too, and a failed database is not
  a per-question fact. An absent question_id keeps its old meaning
- Subject::update is field-scoped: the handler holds no lock across its
  read and write, so a whole-row save reverted a concurrent edit of the
  other field
- annotate the three whole-row saves that genuinely cannot be raced
  (exam update holds EXAM_LOCK across the read; the two image upserts
  build their struct in place under a deterministic slot id)

2026-07-19

🐛 fix(users): blank search query lists the whole roleAhmet Kaan Gümüş · f658a4e
🐛 fix(users): blank search query lists the whole role

/users/search?q=&role=student was a 400, but the frontend pickers use
exactly that shape as their initial unfiltered listing. A blank q now
skips the fragment clause, so blank + role lists everyone in that role
(still ordered by username, still paged). Blank q without a role stays
a 400 — an unscoped full dump was never a search.
✨ 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)
🐛 fix: five holes from fan-out auditAhmet Kaan Gümüş · 7d8df31
🐛 fix: five holes from fan-out audit

- serialize exam-subsystem check-then-writes with EXAM_LOCK RwLock
  (answer saves read, structural writes write): freeze gate vs first
  attempt, subject delete vs question write, retake wipe vs in-flight
  save; start_attempt re-derives the sittable gate under the lock
- field-scope User::set_role/set_profile/set_preferences: whole-row
  content() writes let a stale PATCH /users/me carry the snapshot role
  back over a concurrent admin demotion (exploitable by hammering the
  endpoint); each writer now updates only the fields it owns
- CORS: expose Retry-After and Content-Disposition so cross-origin JS
  can read the documented 429 backoff and download filename

2026-07-16

✨ 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(web)!: paginate every list endpointAhmet Kaan Gümüş · f3d2b0a
✨ feat(web)!: paginate every list endpoint

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

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

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

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

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

2026-07-13

✨ feat(auth): strict username charset + reserved namesAhmet Kaan Gümüş · 4384914
✨ feat(auth): strict username charset + reserved names

Usernames accepted any ASCII between the length checks — control
characters, spaces, quotes, and HTML metacharacters all passed, which
enables log injection (\n, ESC), lookalike impersonation ('admin
support'), and stored XSS wherever a frontend renders names unescaped.

- allowlist: lowercase letters, digits, single interior . _ -
- must start and end with a letter or digit; no consecutive separators
- staff-looking names (admin, administrator, root, support, system,
  moderator, staff) rejected at /auth/register only — the
  ADMIN_USERNAME bootstrap still seeds them through the same newtype
- duplicate-register 409 kept: usernames are public handles, the
  existence leak is deliberate

Existing rows are not revalidated or migrated.

2026-07-12

✨ feat(authz): wall course reads behind enrollment and ownershipAhmet Kaan Gümüş · ed007d9
✨ feat(authz): wall course reads behind enrollment and ownership

Students could read any roster, roll call, and event attendance; any
teacher could read any exam's results, statistics, live monitor,
answer sheets, and answer key (correct included), plus full
marks/attendance reports of any user.

- can_view_course = enrolled | creator | manager+; the /courses and
  /exams catalogs filter per caller (list_created, list_for_courses)
- course sub-reads (roster, results, statistics, live, questions,
  answer sheets) require course-management rights
- roll-call and event rosters become teacher+ views; students keep
  /attendance/me and /marks/me
- /marks/{user} and /attendance/{user} narrow to the courses the
  caller manages; manager+ still sees the full report
✨ feat(users): optional role filter on user searchAhmet Kaan Gümüş · 9ecc818
✨ feat(users): optional role filter on user search

Pickers want one role at a time — enroll wants students, not the
teacher who shares the name fragment. `role` narrows the match;
omitted keeps the old all-roles behavior. Unknown role is a 400.
✨ 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(admin): seed an admin account at startupAhmet Kaan Gümüş · ea497d9
✨ feat(admin): seed an admin account at startup

ADMIN_USERNAME and ADMIN_PASSWORD (both-or-neither; half a pair aborts
boot, blank counts as unset) create an admin at startup when the
username doesn't exist. The seed is idempotent and never rewrites
credentials: an existing admin is left as-is, and a non-admin holding
the name is never promoted — that would be a privilege escalation, so
it only logs a warning pointing at the out-of-band paths.

compose.yaml ships local-dev credentials for first boot; .env.example
documents the knob.
✨ 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(domain): validated newtypes and entity persistenceAhmet Kaan Gümüş · ba2b9b1
✨ feat(domain): validated newtypes and entity persistence

Every value is a newtype constructed only after its validator passes
(Username, Password, NoteTitle, Mark, ...), so an invalid value can't
be represented. Each type derives SurrealValue, so one typed value
flows unchanged from HTTP input into the SCHEMAFULL store, and each
entity module owns its own persistence.

- user/role: argon2-hashed passwords; four hierarchical roles
  (student < teacher < manager < admin) with at_least() checks.
- session: an opaque random token, 7-day expiry, server-side lookup.
- note: per-user notes.
- event/attendance: events own attendance rows keyed by event+user;
  optional unix-millisecond starts_at/ends_at with ends >= starts.
- exam/exam_result: homework|quiz exams; one 0-100 mark per exam+user
  in its own row, never on a note.
- timestamp: the unix-millisecond instant shared across entities.

Record ids are ULIDs — time-sortable and safe to expose.