Commits
2026-09-24
✨ feat(schedule): holiday calendar, slot topics, and the weekly-plan materializer coreAhmet Kaan Gümüş · 7c481f7
✨ feat(schedule): holiday calendar, slot topics, and the weekly-plan materializer core Schema (migrations/school/20260924000001_holidays_and_materialize.sql): a school-wide `holiday` table over instant ranges, an optional `topic` on both weekly-plan slot tables, and UNIQUE (class_course, starts_at) on course_session so two lessons of one section cannot start together. Domain: `holiday` (name/kind/range newtypes, inclusive `overlaps`) and `calendar` (the school-zone day math hoisted out of web/attendance, which now imports it). `WeeklySlot` carries an optional topic; `overlaps` is unchanged. Db: `holiday` CRUD + overlap-paged list + the materializer's unpaged read; `course_session::insert_many` (one unnest INSERT .. ON CONFLICT DO NOTHING RETURNING, so the reported rows are the rows actually inserted) plus `existing_starts`; a duplicate start on the single-session route now answers 409 session_time_taken instead of a 500. Service: `holiday` pass-throughs and `course_session::materialize` — one transaction, archived-year wall, row lock on the instance, refusals coded instance_has_no_weekly_plan / instance_has_no_teacher, a range cap of 366 days and a candidate cap of 500, holidays and already-scheduled starts skipped and counted, nothing ever deleted. Dry run is side-effect free. The HTTP surface, per-section course lists, and the integration suite follow in later commits.
✨ feat(courses): grade-ladder course templates with per-class overridesAhmet Kaan Gümüş · 450bc8c
✨ feat(courses): grade-ladder course templates with per-class overrides course_offering per (course x grade_level 0..=12), per-class overrides on class_course (nullable scalars + *_inherited flags), subjects/weights/ weekly-plan axis tables, instance_resolve with batched twin, resolved title/description on instance-scoped reads, six new route groups, integration scenario test, README regenerated. Evolution migrations squashed into the base schema (20260912000002_courses + 20260916000001_k12_remodel). Local-Gate: 246daa3fb3ee7b0ff507a95d6ab346bab1333a37 (1556 passed, 455s)
2026-09-17
✨ feat: the podcast job's row and audio now live in the backend - backend-owned row, mp3 ingest, read gates without the serviceAhmet Kaan Gümüş · c44f362
✨ feat: the podcast job's row and audio now live in the backend - backend-owned row, mp3 ingest, read gates without the service
The job record lived only in the podcast service's own volume, so a restart
or a wiped volume lost every in-flight job a caller was polling and the mp3 it
was about to download. The backend now owns both ends of that state:
* `migrations/school/20260917000003_podcast.sql` — `podcast_job`, the job's
own row (user/source/format/state/stage/progress/error_code/audio_*/
duration/eta/created/updated). No `school` column: the school IS the
database, and the row's tenancy is (this database, user_id).
* `POST /podcast/jobs` mints the id, writes the row, THEN dispatches
`podcast.submit` with `{job_id, source_id, format, user_id}`; the service
echoes that id in its receipt (mismatch = 502 + a failed/bad_reply row).
No worker = 503 and no row; a refusal or transport failure tombstones the
row with the reason code — nothing is left claiming `queued`.
* The service reports every transition back through `podcast.report` (the new
client-initiated capability call, School-scoped, wired through
`src/ai/capability.rs`), which validates the echo, the jobs.py transition
table, the retention window and the done-means-audio rule before one
conditional UPDATE keyed on the state it read.
* The finished mp3 arrives as a `BlobUploadRequest` stream (exactly `size`
raw bytes), lands under the school's own blob root at
`podcast/<job-id>.<ext>` (temp+rename, row stamped in the same act, file
removed again if the row write finds the job gone), and `POST`ing a done
report before it is refused `audio_missing`.
* The read doors — `GET /podcast/jobs/{id}`, `.../result`,
`.../audio` — answer from the row with no service round trip: 404 for an
unknown or foreign job (foreign ids read as absent), 409 `not_ready` /
`audio_missing`, 410 past PODCAST_JOB_RETENTION_SECS, and a read-side-only
projection that presents a queued/running row nobody has updated inside its
ETA-scaled window as failed/interrupted — the GET writes nothing and a real
report overwrites it. `podcast.status`/`podcast.result` capabilities are
deleted with their payloads; the old `GET /podcast/audio?path=…` door is
gone (it named a cross-volume path and could not be owner-scoped).
Also: `AppError::Expired` (410) + the two room matches that needed it,
MIN_PROTECTED 323 -> 337 (real swept count), the three clippy fixes on the
committed tree, README regenerated, and the .sqlx entries for both lanes'
queries. This commit completes the tree that 7c96e47 half-staged: that commit
took the shared files (server/protocol/constant/db-mod/ai-capability) while
leaving `src/ai/podcast.rs`, `src/web/podcast.rs` and `tests/podcast.rs` at
their old versions, so main did not compile until this one.✨ feat: add the /rag nest over the course-note RAG bridgeAhmet Kaan Gümüş · a61e0a6
✨ feat: add the /rag nest over the course-note RAG bridge A separate rag_thread/rag_message pair of tables and a Module::Chatbot gated /rag nest, mirroring the chatbot's asynchronous send: POST answers 202 with a pending assistant row, an in-process task settles it, and both the poll read and the SSE stream project a stale pending row as failed. Every question is scoped server-side to the asker's own (sinif, ders) pairs — class-section instances, a linked parent's children, school-wide club/study memberships — never from the body. Each citation's corpus doc_id is resolved per candidate to a course-note file the asker may view, and the two storage caps refuse an over-bound reply whole rather than clipping it. rag.index replies now stamp each file's rag_doc_id, the missing link between a citation and its file. The chatbot's SSE helpers move to web/mod.rs so both nests stream through one implementation, and the instance/course visibility gates move from web to service so the scope deriver and the routes share one rule. Gates: cargo check --all-targets, clippy -D warnings, limits_completeness, spec_bounds, doc_sync (README regenerated), protected_routes_require_session (MIN_PROTECTED 269 -> 318, the real swept count), ai_bridge (75 tests).
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-13
✨ feat: person-scoped login; select school afterAhmet Kaan Gümüş · fae1f79
✨ feat: person-scoped login; select school after Login is username+password only. A person is global, memberships are per-school (role stays on app_user), and POST /auth/school binds when the account belongs to more than one school.
2026-09-12
2026-09-11
2026-09-05
✨ feat: one database per school behind a control registry; login names the schoolAhmet Kaan Gümüş · b7dfc0c
✨ feat: one database per school behind a control registry; login names the school Namespace `hezarfen` now holds one DATABASE per school (name = slug) plus a `control` database with the school registry, builder accounts and builder sessions. `Tenants` keeps one separately-connected handle per school; the shadow `web::tenant_state::State` resolves the school from the `<slug>.<token>` cookie so every handler's `st.db` is school-scoped by construction. `POST /auth/login` / `register` carry `school`; a suspended school answers 403 everywhere. `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed the vendor account; the boot admin seed is gone. No customers, no compat shims.
✨ feat: rag_output table + rag.index dispatch for course notesAhmet Kaan Gümüş · d42a1c3
✨ feat: rag_output table + rag.index dispatch for course notes The backend now owns the RAG side of a course note: a new `rag_output` table stores whatever an AI service produced for a note, and the backend asks for it — the AI service still writes no human data, and the api-read bridge stays GET-only. `rag.index` is dispatched fire-and-forget (tokio::spawn) after a note is created, edited, or gains/loses a file, so no HTTP handler waits on, or fails because of, an AI service; with no worker carrying the capability the trigger is a silent no-op. The request carries the note's text plus attachment METADATA only (file bytes deliberately off the wire — open with the service owner). Rows are derived data, so they cascade: the note delete drops its outputs, and a file delete drops every output built from it even when no service is connected. HTTP GET/DELETE routes over the rows are part 2. Ref #27
2026-08-19
✨ feat: course notes uploadable by responsible teacher+Ahmet Kaan Gümüş · 6b1748c
✨ feat: course notes uploadable by responsible teacher+
Mirror of the personal-note stack scoped to a course: course_note +
course_note_file tables, /course-notes routes (POST/GET list?course=,
GET/PATCH/DELETE /{id}, POST/GET /{id}/files, GET/DELETE /{id}/files/{fid}).
Write = can_manage_course (creator, assigned teacher, manager+; live
Teacher role floor). Read = can_view_course (manage or enrolled).
Blob-first upload, cap via cap::claim_and_create (MAX_COURSE_NOTE_FILES),
create-vs-deleted-course refused via cap::touch_and_create, course delete
cascades note/file rows and unlinks blobs.
Tests: 8 integration cases (authz matrix, demoted creator, cross-course
file IDOR, cap 409/413, blob cleanup, cascade 404), race-contract cases
in regress_course_child_orphans, domain unit tests. README Endpoints
table regenerated via doc_sync; Layout updated.2026-08-04
feat: 🏅 earn badges for the work already doneAhmet Kaan Gümüş · a00880e
feat: 🏅 earn badges for the work already done Thirteen badges a student earns by doing the work, so the profile has something to be proud of rather than just a photo and a bio. Nothing awards a badge by hand and nothing takes one away. A badge is earned when a counter crosses a threshold, and it is permanent: withdraw the submission that earned it and the count falls while the badge stays, because a stamped `earned_at` is the motivational payload and a badge that evaporates is worse than no badge. The catalog is hardcoded, so changing a threshold is a deploy and the evaluator stays a pure function of the counters. It rides GET /limits as a group like every other bound; labels and icons are the frontend's, keyed by badge id. The counters are the real work. Homework, exam and attempt tables are indexed for the questions the rest of the API asks, so counting a single student's history meant a full table scan — the numbers are therefore tallied at write time, in the same transaction as the write that causes them. Existing accounts are seeded once from their real history, gated by a mark whose skip is proven rather than assumed, so nobody starts at zero for work they already did. Withdrawing your own submission decrements, and that is the only decrement in the codebase: withdrawal is student-callable, so without it submit/delete/submit would farm the counter. Cascades never decrement — history a teacher erased is still history the student lived. The cost is that a re-run seed, which can only count rows that still exist, comes out lower than the live tally; documented where someone would otherwise "repair" it. Deadlines move, so the on-time verdict is now stored on the submission beside the count it fed. Judging it again at withdrawal read whatever the deadline had become since, which drifted the tally in both directions — far enough that on-time could exceed submitted. Attendance counters were dropped: those tables already carry per-user indexes, so there is no scan to fix, the status list is school-editable, and roll-call corrections would need a decrement that fights permanence.
2026-08-02
fix: 🔩 clear the deferred backlog and ship class phase 2Ahmet Kaan Gümüş · afff737
fix: 🔩 clear the deferred backlog and ship class phase 2 Ten defects and two features, worked as one series because the doc surfaces and the const table are shared. Defects closed: - Cross-exam answer-key leak. The bank copies `correct` into every instantiation, so reviewing exam A handed out the key to a question the caller was still writing in exam B. Review now blanks those questions rather than closing: the join matches on `from_bank` AND `banked_as` (a question can carry both — instantiated, then re-saved to the bank — so a coalesce misses a copy), redacting `correct`, the correctness flag and that question's `auto_score` share. Keyed on the template, never the exam, so the rest of the review reads normally. - `set_role` was not atomic with its sweeps. The role write and every grant it invalidates now commit as one transaction; the board rooms are told after COMMIT from the cascade's own result slot. Built best-of-N; the losing charter left the one sweep outside whose failure strands an event seat no route can free. - Board rosters held below-student ids, which 400d the creator's next roster PATCH. Repaired at boot, and a PATCH may now send back the roster it was served: an id already present that stopped qualifying is dropped, a new one still refused. - `note_file` blobs leaked. The delete transaction returns the rows it removed and the handler unlinks exactly those, not a pre-read snapshot. - Rate limiting failed open on a saturated map. Never-seen clients now share one metered overflow budget instead of arriving unmetered. - Whiteboards: `GET /boards` takes `?open=`, `/strokes` no longer leaks a clear marker the socket filters out, and a locked board refuses its creator's clear (409) — the lock now means one thing on every path. - Blueprint skips named the wrong record: `Attached::Gone` was two facts under one name, split into `Gone` (class) and `PivotGone` (course). Features: - Event audience `kind=class` — live from `class_member`, membership checked in one select because the (class, user) pair is the row id. - Grade blueprints: a grade's course template, retro-pumped best-effort with a skip list. Attachments carry a provenance tag, so removal spares what a human placed. A course deleted out from under a blueprint is pruned from the template by the pump that finds it. Forcing functions, because a hand-kept copy drifts: - `protected_routes_require_session` is derived from the emitted OpenAPI: 248 -> 254 operations swept, was 80 typed by hand. - Every JSON-bodied operation declares 422 (74 sites), pinned both ways — and multipart routes, which answer 400, are pinned to NOT declare it. - The SurrealQL registration-freeze guard is pinned against the Rust it copies; both mutations of it fail the test. - `migration_mark` gates one-time backfills. The roster repair rescanned every board against every user on every boot (773ms at 300/2000 with nothing to write); it is now skipped once done. Verified by a three-lens verifier panel — which caught the `banked_as` half of the answer-key leak by executing a probe, after the first fix had been reported complete — and by a podman boot against the existing volume: both new fields defined, the marker written, boot 2 skipping the scan, and the live API answering on the new routes.
2026-08-01
2026-07-31
feat: 🖍️ collaborative whiteboard domain, REST and limitsAhmet Kaan Gümüş · 5dfce55
feat: 🖍️ collaborative whiteboard domain, REST and limits Boards are an ad-hoc invite list: the creator names participants, and every participant draws. Clearing, locking, closing and deleting are the creator's alone. Strokes are an append-only log and a clear NEVER deletes — it bumps the board's epoch, so the live canvas empties while the whole history stays replayable. The clear marker row doubles as the epoch index, carrying the epoch it closed and that epoch's final stroke count, which is why there is no epochs table. Growth is bounded by two counters claimed together in one conditional write: epoch_stroke_count resets on a clear and caps the live canvas (recoverable — clear and keep drawing), while total_stroke_count never resets and stamps closed_at when the lifetime cap is hit, leaving the board permanently read-only but fully readable. board_count on user bounds the open-a-new-board escape hatch. Outsiders get 404 everywhere so a board's existence never leaks; a participant lacking creator rights gets 403, since existence has already been disclosed to them. The WebSocket room lands separately.
2026-07-29
feat: 💰 track school fees in an append-only ledger of fee plansAhmet Kaan Gümüş · 740e96a
feat: 💰 track school fees in an append-only ledger of fee plans
Fee plans (name + 1..60 installments of {amount_minor, due_at}) are
assigned directly to students; assignment appends every installment as
a charge at once, keyed <plan>_<student>_c<n> so a replay bills nobody.
Payments target one charge, refunds target one credit, and a reversal
undoes only the negative-fold kinds — a mistaken credit is corrected by
a refund, never edited. Balance is never stored; the over-payment cap
folds the target's source subtree under PAYMENT_LOCK and stays advisory
across replicas, which the module doc states outright.
Meal money is untouched: two ledgers, two balances, one shared amount
vocabulary.2026-07-27
fix: 🪢 guard writes in the database, not the processAhmet Kaan Gümüş · 6c87eca
fix: 🪢 guard writes in the database, not the process
Two replicas are live; every process-local lock silently stopped
meaning anything. Move the invariants into the writes themselves:
- count caps (enroll/register/files/threads) become a counter column
claimed by UPDATE .. WHERE n < cap (domain/cap.rs), backfilled once,
decremented in the same transaction as every child delete
- exam freeze, re-draft and grade gates ride inside the write's own
transaction (IF .. THROW); SESSION/WORK_ENTRY/EVENT locks die, range
checks fold into the UPDATE's WHERE (FieldUpdate::ordered)
- appointment decisions CAS on status+proposed window+decided_by;
bank/exam updates CAS on their editable columns
- rate limiter syncs local windows to a shared minute row every 2s,
fail-open when the database is down
- paged GETs run LIMIT/START in the database (domain/page.rs); sites
that post-filter in Rust stay web-sliced and say so
- exams.rs (3629 lines) splits into web/exams/{mod,attempts,questions,
images,review}; image uploads single-source in web/image.rs; the
bare-seq key rule lives once in domain/key.rs; migration SQL moves
to migration_sql.rs
Every new guard is mutation-proven (removing it fails a named test).
Migration adds counter columns + rate_limit table; backfill is
one-time, guarded by = NONE, and verified against the live volume.
Traps recorded: SurrealQL 'x ?? 0 > 0' parses as 'x ?? (0 > 0)'; the
embedded mem engine drops one of two concurrent writes yet answers Ok.2026-07-26
feat: 🍽️ run the canteen: menus, seats, allergens and a ledgerAhmet Kaan Gümüş · fd5cfd1
feat: 🍽️ run the canteen: menus, seats, allergens and a ledger Published menu calendar (manager+ authors, everyone reads), per-student dietary profiles that mark conflicting dishes, meal booking with an optional per-menu capacity, meal attendance, and booking-triggered billing. Booking is the charge trigger: reserving a seat stamps a charge at a price snapshot, so later dish edits never rewrite what a student owes. No-show still pays, because the kitchen already bought the food, which is why attendance has no billing effect at all. Money enters only as admin-recorded credit entries; there is no gateway and no card data. The ledger is append-only. Cancelling appends a reversal rather than deleting the charge, balance is always folded from the rows, and the sign lives in exactly one function. A deletable ledger row would rewrite a student's financial history leaving no trace. Charges and reversals are keyed per (booking, attempt) and written under MENU_LOCK alongside the seat, so a double-click, a retry, or a cancel cut short mid-flight all settle to one charge and one refund. That lock is in-process only: a second replica would break every capacity and charge guarantee here. A parent may book for a linked student, the first write parent_link has ever authorised, and sees only seats whose link is still live.
2026-07-25
fix: 🧩 a PATCH writes only the fields it was givenAhmet Kaan Gümüş · 85b408e
fix: 🧩 a PATCH writes only the fields it was given - every PATCH handler loaded the row and refilled the fields the request omitted from that stale snapshot, so two concurrent partial PATCHes touching different fields lost each other: whoever wrote last silently reverted a field it was never asked to change - field-scoping the write did not fix this — the value bound to the SET still came from a stale read - add domain/field_update.rs: .set(column, Option<T>) skips an absent field entirely, so it is neither written nor bound, and an all-absent PATCH writes nothing at all - convert notes, events, terms, homework, work entries and courses, each with a 20-round concurrent-PATCH regression that fails against the old code on round 0 and passes after - nullable columns stay clearable: an event's schedule, a course's capacity and term, and homework's assigned subset keep the double-option so an explicit null still writes NONE, while an omitted field is left alone - homework's old fallback was worse than a no-op: it could re-narrow the assigned subset over a concurrent widening, behind the guard that exists to stop exactly that - cross-field validation still reads the stored row where it must (event and term ranges need both ends) — read for the check, never written back - HOMEWORK_LOCK was taken after the row read, so it never covered the read-modify-write it looked like it guarded
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
identity2026-07-24
✨ feat(exams): add a reusable school-wide question bankAhmet Kaan Gümüş · 8b07cfa
✨ feat(exams): add a reusable school-wide question bank
Teachers weld a question to one exam today, so reusing it next year means
retyping. This adds a bank of question templates that copy into an exam on
demand: a fresh exam question with its own id, images, and answers, so the
copy never shares state with the template (a bank edit can't rewrite a
graded exam). Bank rows carry no exam tie and never freeze.
Reads and instantiate are school-wide (any teacher+); editing or deleting
a template needs ownership (admins aside). A template's subject is origin
metadata only — the same-course rule is checked at instantiate time
against the target exam's course. Both directions exist: author in the
bank, or save an existing exam question back into it.
Routes: CRUD + image slots under /bank-questions, plus
/exams/{id}/questions/from-bank/{bid} (instantiate) and
/exams/{id}/questions/{qid}/to-bank (save). Blob copies are all-or-nothing
and roll back on failure; a subject delete is guarded against live
templates, and bank writes serialize against it under BANK_LOCK. Copies
record provenance (source_bank / source_exam).2026-07-23
🎨 style(chatbot): rename thread/message off the mail collisionAhmet Kaan Gümüş · 92b232b
🎨 style(chatbot): rename thread/message off the mail collision
The AI chatbot's storage and web layer reused "conversation" and
"chat_message", the latter one underscore away from the human-to-human
mail `message` feature — every reader had to disambiguate two unrelated
tables by eye.
Rename the whole chatbot feature to a `chatbot_*` vocabulary:
conversation -> chatbot_thread (ChatbotThread*, CHATBOT_THREAD_*)
chat_message -> chatbot_message (ChatbotMessage*, CHATBOT_MESSAGE_*)
/chat/conversations -> /chatbot/threads
max_chat_conversations -> max_chatbot_threads
max_chat_message_len -> max_chatbot_message_len
chat_history_turns -> chatbot_history_turns
RATE_LIMIT_CHAT_PER_MINUTE -> RATE_LIMIT_CHATBOT_PER_MINUTE
DTO conversation_id -> thread_id
The out-of-process AI-service wire contract is deliberately untouched:
ai/chat.rs payload types, AI_CHAT_CAPABILITY ("chat.reply"), the serde
field names and the hab/1 ALPN stay as-is — other-language services
match on those literals. ai/chat.rs remains "the chat.reply payloads",
a separate concern from the chatbot feature it feeds.
Clean break, no row migration (pre-customer, FE not yet synced): old
conversation/chat_message rows in the volume are abandoned. Frontend
must adopt the new routes, the thread_id field, and the renamed
settings keys.✨ feat(appointments): teachers publish slots, students book themAhmet Kaan Gümüş · 771936e
✨ feat(appointments): teachers publish slots, students book them Teachers keep a calendar of availability windows; students and parents book one with a reason. Publishing a window is not consent to a specific person and topic, so a booking lands pending until the teacher approves, rejects, or counter-proposes another time — a counter-proposal returns it to pending for the requester to accept or decline. A slot holds one live booking, with occupancy derived under APPOINTMENT_LOCK rather than stored, so rejecting or cancelling frees the slot for someone else. No two approved meetings may overlap for the teacher or the requester. Cancelling refuses a meeting whose window has opened, so every path that could land a booking on a past window is closed at the source: booking a started slot, approving a started window, and proposing a started time all refuse. Otherwise a booking could exist that nobody was able to cancel. Weekly repetition expands eagerly into concrete rows sharing a series id, capped at 52, so cancelling one occurrence is an ordinary delete.
✨ feat(chat): relay chatbot over the AI bridgeAhmet Kaan Gümüş · b0aa0a1
✨ feat(chat): relay chatbot over the AI bridge The backend relays between the frontend and an out-of-process AI service: it owns auth, rate limiting, persistence and payload format, and may inspect an answer before the frontend sees it. No rule or intent tables — conversation is free-form. Two-phase by design. POST persists the pending assistant row *before* dispatching, then returns 202, so a reload never loses an answer; the client either polls the message or opens an SSE stream. Both read the same DTO, so they cannot disagree. Deltas are sliced from the finished text because hab/1 is unary — the event shape exists so real streaming drops in later without a client change. A turn always settles. Every failure after the rows are written marks the row failed with a machine-readable code, a boot sweep flips rows orphaned by a restart, and a pending row older than five minutes reads as timed out — projected at read, never written back, so a slow-but-alive answer is not raced. An over-long answer is clipped and flagged rather than dropped; an empty one fails. Message ids come from a monotonic ULID generator: the two rows one POST writes share a millisecond routinely, and a random tie-break rendered the answer above its own question and handed the service [assistant, user], breaking the documented oldest-first history contract. The conversation cap counts and creates under a lock — SurrealDB BEGIN/COMMIT does not serialize cross-record counts, and 16 concurrent creators over-admitted a cap of 5 to 20 without it. Every authenticated role may chat, parents included. Foreign threads are 404, never 403.
2026-07-22
2026-07-21
feat: 🎨 student answer-image endpoints mirroring question imagesAhmet Kaan Gümüş · 2c83c6f
feat: 🎨 student answer-image endpoints mirroring question images
- new AnswerImage domain keyed by (exam, user, question), stored as an
image/png blob with upsert-overwrite, mirroring QuestionImage
- routes: POST/DELETE/GET /exams/{id}/attempt/answers/{qid}/image (student
own, gated by the save_answer writable-attempt chain) and GET
/exams/{id}/attempts/{user}/answers/{qid}/image (teacher grading)
- answer_image (Option<ImageMetaResponse>) on the student sitting view and
the teacher grading sheet; live monitor and exam_ws untouched
- a drawing-only answer creates a blank text answer row so the drawing
surfaces in both views; removing the drawing grooms that blank row away
- cascade blobs+rows on exam delete, course delete, and retake wipe (rows
in the wipe transaction, blobs swept in start_attempt)
- integration tests: raster wall, own/teacher auth walls, upsert, retake +
exam-delete cascade, drawing-only surfacing and its cleanup✨ feat(questions): student Q&A pool with moderated solutionsAhmet Kaan Gümüş · 0df048b
✨ feat(questions): student Q&A pool with moderated solutions Students ask (one photo, pending-only edits), teacher+ approve into a school-wide pool — approval freezes content so nothing unmoderated slips in after review; rejection is deletion, no rejected state. Anyone above parent offers solutions: text + one photo, author-edited anytime (unmoderated), delete-only moderation. Question rows carry solution_count; deletes cascade solutions and image blobs (zero orphans). Question and solution photos reuse the exam-image raster allowlist and size cap via serve helpers shared out of exams.
2026-07-19
✨ feat(messages): one-to-one mail with per-side foldersAhmet Kaan Gümüş · f4b3828
✨ feat(messages): one-to-one mail with per-side folders Any user writes to any user (the one place a parent acts); only self-send is refused. A single row serves both parties, each owning their copy: the recipient files through inbox/archive/trash with a read flag the sender sees as a receipt, the sender through sent/trash. Folder and read writes are field-scoped so the two writers never clobber each other. Permanent delete works only from the trash and drops the row once both sides are gone. Messages carry an optional free-text label badge, and ?read=false with limit=1 turns the page total into the unread badge.
✨ feat(users): read-only parent role with student tiesAhmet Kaan Gümüş · ec44315
✨ feat(users): read-only parent role with student ties
Parent sits below student in the hierarchy: clears no staff bar and
fails every exact student gate, so it can only observe. Admins tie
students to a parent under /users/{id}/students; the tie alone opens
the student's marks/attendance/pomodoro reports (full, unnarrowed)
plus the parent's own /users/me/students list. A role change off
either end of a tie sweeps it, mirroring the enrollment sweep.✨ feat(pomodoro): server-stamped student focus logAhmet Kaan Gümüş · 73d4367
✨ feat(pomodoro): server-stamped student focus log Students start/finish pomodoro focus sessions; the server stamps both instants, so recorded focus time is honest. Starting discards a dangling unfinished session instead of conflicting — a crashed timer never blocks the next one. Logs return the page envelope plus total_focus_ms (unpaged sum of finished durations); teachers+ read any student's log. Breaks and the work/break rhythm stay in the frontend — the backend stores no timing policy.
✨ feat(exams): images on questions and choice optionsAhmet Kaan Gümüş · dbeb122
✨ feat(exams): images on questions and choice options Teachers pin one illustration to any question (the map above the prompt) and one picture per option on choice questions — the options themselves can be images. Multipart upload per slot, replace by re-upload, frozen with the question once attempts exist. - rows in question_image (deterministic id per slot, UPSERT = replace); blobs beside note files under FILES_PATH, capped by max_file_bytes - raster allowlist png/jpeg/webp/gif — SVG can script and these bytes render inline to students; served with nosniff + private, no-store - students fetch bytes behind the sitting wall (enrollment + started attempt, no early peek); course managers anytime - replacing a question's choices drops its option pictures (the illustration stays) — old pictures belong to the old options - blob cleanup wired into image replace/delete and question, exam, and course deletes (exam cascade result slot shifted 5 -> 6)
2026-07-17
✨ feat(subjects)!: course subjects, required on every exam questionAhmet Kaan Gümüş · 022aaaa
✨ feat(subjects)!: course subjects, required on every exam question
Each course now owns its curriculum as subjects (name + optional
description; course link fixed at creation). Every exam question must
be tagged with a subject of its exam's own course, so exam content is
attributable to a topic.
- POST/GET /courses/{id}/subjects (manage / course-visibility, paged)
- GET/PATCH/DELETE /subjects/{id}; delete is a 409 while any question
still references the subject — re-tag or delete those questions first
- course delete cascades its subjects
BREAKING: question create/update payloads require subject_id, and
questions written before subjects existed are destroyed on boot
(answers first) — nothing truthful to backfill, pre-customer clean
break.2026-07-16
✨ feat(events)!: registration audience replaces hand-picked usersAhmet Kaan Gümüş · 31e155a
✨ feat(events)!: registration audience replaces hand-picked users
Events gain a `registration` audience: a signup list built one seat
at a time — teachers place students (students never register, not
even themselves), staff take only their own seat, never another's.
An optional capacity caps the list (seat count re-checked inside the
insert transaction), and the list freezes the moment the event
starts, both directions. Seats resolve live like every audience:
roster, marking gate, and who-missed report inherit unchanged.
- POST /events/{id}/register {user_id?}: idempotent seat upsert
(enrollment's composite-id trick); 409 when full or started
- DELETE /events/{id}/register/{user}: same self-or-student rule;
a deleted account's leftover seat is any teacher's to free
- event delete cascades signup rows; audience switches leave them
inert (they resurface if the kind returns)
- migration split into DDL + backfill queries: statements in one
batch see the batch-start schema, so a backfill next to a fresh
DEFINE FIELD silently lost the keys it wrote (audience became {})
BREAKING CHANGE: the hand-picked `users` audience kind is gone —
requests naming it are rejected. Existing users-audience events
convert on boot: each listed user becomes a registration row
credited to the event creator and the audience becomes an uncapped
registration list.✨ feat(users): per-user UI preferences (theme, language)Ahmet Kaan Gümüş · 7168ba0
✨ feat(users): per-user UI preferences (theme, language)
Theme (light/dark) and language (tr/en) live on the user row and
return on every user response. PATCH /users/me/preferences is
self-service for any role; PATCH /users/{id}/preferences is the
admin path. Same merge semantics as the profile patch: omitted
keeps, "" clears, anything else validates or the patch is a 400.
Null means "never chose": clients fall back to the device
preference (prefers-color-scheme, browser language), so there is
deliberately no server-side default to stomp device detection.
Pre-feature rows read back null through the option<string> columns
— no backfill needed.2026-07-15
✨ feat(notes): file attachments with school-set size capAhmet Kaan Gümüş · f1b532b
✨ feat(notes): file attachments with school-set size cap
Blobs live on disk under FILES_PATH (same volume as the DB), named by
the row's ULID so user input never shapes a path; the note_file row
keeps only metadata. DB-blob storage rejected: multi-MB PDFs bloat
surrealkv's LSM tree and buffer whole in RAM on every read.
- POST/GET /notes/{id}/files, GET/DELETE /notes/{id}/files/{file_id};
owner-only through the owning note, staff included
- max_file_bytes in settings (1 KiB-25 MiB hard cap, default 5 MiB),
enforced on streamed bytes (413), inside the settings CAS guard;
option<int> so pre-field volumes boot without a backfill
- 10 files per note; deleting a note removes rows first, blobs after,
so a crash strands at worst an unreachable blob2026-07-13
✨ feat(school): editable policy settings + academic termsAhmet Kaan Gümüş · ea8bfeb
✨ feat(school): editable policy settings + academic terms Every school differs; the varying parts become data instead of code: - settings singleton (GET any user, PATCH manager+): exam kinds, attendance statuses, grade-display bands. Absent row = old hardcoded defaults, so existing databases behave unchanged. - core four attendance statuses stay mandatory — the attendance rate is defined over them; school extras tally rate-neutral under a new `custom` bucket in reports. - grade bands are display-only over the canonical 0-100 marks: reports gain grade/average_grade/overall_grade labels, stored marks never change with the display scale. - terms are rows (semester/trimester/quarter all fit); courses link via nullable term_id, term delete unlinks, past dates allowed for mid-year calendar backfill. - settings edits never rewrite stored rows: retired kinds and statuses live on in old records; only new writes validate against the current lists.
2026-07-12
✨ feat(attendance): course sessions, roll call, work log, reportsAhmet Kaan Gümüş · 5b6aac1
✨ feat(attendance): course sessions, roll call, work log, reports
- course_session: a course's lesson (teacher, topic, required starts_at,
optional ends_at); managed under course rights like exams; explicit
teacher_id must hold teacher+; lists ordered by starts_at (timetable)
- session_attendance roll call: one row per session+user by composite id,
course denormalized so reports need no join; students never self-mark —
the session's teacher or a course manager marks enrolled students, and
the teacher's own presence row is manager+ only (no self-declared
presence); session/course deletes cascade roll-call rows
- work_entry staff timesheet (teacher+): check-in/out stamped by the
server clock only, so a client clock or crafted request can't forge
presence; one open stint per user held atomically — INSERT IGNORE on
the deterministic open_{user} id, check-out takes it via DELETE RETURN
BEFORE and re-files under a ULID; manager+ reads any log, corrects
closed stints (ordered instants), deletes entries
- attendance reports at /attendance/me and /attendance/{user} (teacher+),
mirroring the marks report: event tallies + session tallies +
per-course breakdown; rate = (present+late)/(present+absent+late) —
late attends, excused counts against no one; unenrolling hides marks
but never absences (attendance is a historical record)
- RequireManager extractor; check_time_range shared by events/sessions✨ feat(exams): scheduled attempts, live monitor, questions, answers, exam roomAhmet Kaan Gümüş · ade4fed
✨ feat(exams): scheduled attempts, live monitor, questions, answers, exam room
- exam scheduling as one validated unit: mode sync|async + window
(+ per-student duration_ms for async); unscheduled stays offline-graded
- exam_attempt: one row per exam+user by composite id; start = attendance
signal, finish = submission; status/deadline recomputed from the current
schedule on every read (mode frozen once attempts exist, times extend live)
- teacher live monitor: GET /exams/{id}/live snapshot + SSE /live/stream
- exam_question: choice|text authored per exam, kind bundle (choices+correct)
validated as a unit, frozen once attempts start, ULID order
- exam_answer: upsert per question+user via composite id, kind-coherent,
server-clock stamped; pure auto_score over choice questions as a grading
suggestion — final mark stays human via /results
- student exam room WebSocket at /exams/{id}/attempt/ws: state ticks,
autosave acks, finish/expire lifecycle, gates rejected pre-upgrade with
proper HTTP statuses; shares the REST write path
- PersonRef embeds (id + username + display name) in people-bearing
responses, plus teacher+ GET /users/search
- cascades: exam/course deletes sweep attempts, questions, answers, results2026-07-11
✨ feat(courses): courses, enrollment, and course-scoped weighted examsAhmet Kaan Gümüş · cd56c5b
✨ feat(courses): courses, enrollment, and course-scoped weighted exams
Courses become the unit exams and enrollments hang off. Teachers create
them; editing, deleting, enrolling, and adding exams require course
management rights (creator, or manager/admin). Enrollment rows use a
deterministic composite (course, user) id, so enrolling is one atomic
idempotent UPSERT with no find-then-insert race. Deleting a course
cascades its exams, their results, and enrollments in one transaction.
Exams move inside a course (POST /courses/{id}/exams) and gain a weight
(1-100) that says how many times they count into the course average;
kinds grow to homework, quiz, midterm, final, project, and oral —
informational only, weight drives the math. Grading now demands course
management rights and an enrolled target; moving an exam between
courses is deliberately impossible so results can't be stranded.
Routes: courses CRUD, GET /courses/me for the caller's enrollments,
roster listing, enroll/unenroll, and per-course exam creation/listing.✨ feat(profile): optional personal info on user accountsAhmet Kaan Gümüş · baceaf5
✨ feat(profile): optional personal info on user accounts
Every account (any role) gains name, surname, email, phone, and birth
date as optional fields backed by validated newtypes: PersonName keeps
unicode and trims, Email and Phone get pragmatic shape validators, and
BirthDate parses real calendar dates in YYYY-MM-DD form and refuses the
future. Existing rows read back as None via option<string> columns.
Endpoints: PATCH /users/me lets any authenticated user edit their own
info; GET /users/{id} and PATCH /users/{id}/profile give admins the
school-office path for maintaining records. Patch semantics per field:
omitted keeps the current value, an empty string clears it, anything
else is validated and set. UserResponse now carries the new fields.✨ feat(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.