forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to src/web/courses.rsClear filter

2026-09-25

🐛 fix(clippy): params structs for the d8dad92 list doorsAhmet Kaan Gümüş · 62f10ea
🐛 fix(clippy): params structs for the d8dad92 list doors

-d warnings gate red on main: too_many_arguments on the new filter list
functions (db/service appointment list_for_requester 8/7, db/service exam
list_windowed 9/7), type_complexity on the courses filter resolve,
extra_unused_lifetimes on pomodoro whole_log. RequesterListParams and
WindowedListParams params structs (SettingsParams precedent), the courses
tuple factored into ResolvedCourseFilter, every caller and test call site
migrated; no suppressions.
✨ feat(api): server-side filters on the list doorsAhmet Kaan Gümüş · d8dad92
✨ feat(api): server-side filters on the list doors

A caller no longer has to download a capped collection and narrow it
in the client:

- events, exams: the WindowParams pair is SQL (no whole-table load)
  and gains starts_before/ends_before, so a past/completed view is
  expressible
- sessions: starts_after/starts_before, half-open months
- homework: due_after/due_before (the open/past tabs), class_course
- meals menus: slot (was a post-page JS filter — page counts lied)
- users (admin): roles= comma set; courses: kind, q, taught
- appointments + slots: teacher (or me), starts_after/starts_before,
  status
- pomodoro log: from/to, with the focus total summed in SQL
- messages and boards: q (folded literal substring)
- pool questions: ?status= is a WHERE, not a post-filter
- bank/course-notes id filters: garbage is a 400 naming the field,
  not an empty page

Absent params return today's response byte-shape; page and count
share one WHERE.

2026-09-24

✨ feat(courses): per-section course lists behind the catalogue rowAhmet Kaan Gümüş · 6ecaebc
✨ feat(courses): per-section course lists behind the catalogue row

`CourseSectionRef` and `CourseResponse.sections`: every catalogue row now
carries its sections (instance id, resolved title, class, grade level, hours,
teachers, roster size), truncated to `MAX_COURSE_SECTIONS` while
`class_course_count` keeps the untruncated total. `list_courses`/`get_course`
populate it through one batched builder — seven statements per page, nothing
per row — and a non-manager sees only the sections they reach.

`GET /courses/me` and the profile course block switch from catalogue rows to
one row per section with the section's resolved title. Reach is the union of
the class-roster/homeroom/taught set and the user's own instance enrollments,
so a hand-placed enrollment keeps appearing exactly as it did before.
✨ 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

📝 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.
✨ 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-12

2026-09-11

Merge branch 'layer-split/homework'Ahmet Kaan Gümüş · 746045c
Merge branch 'layer-split/homework'

# Conflicts:
#	src/db/mod.rs
#	src/domain/homework.rs
#	src/domain/homework_file.rs
#	src/domain/homework_result.rs
#	src/domain/homework_submission.rs
#	src/service/mod.rs
#	src/web/homework.rs
🧹 chore: split homework domains into domain/db/service layersAhmet Kaan Gümüş · e37f2b6
🧹 chore: split homework domains into domain/db/service layers

homework, homework_file, homework_result, homework_submission:
- db/<x>.rs: free fns (db first), byte-identical bodies; persistence tests
  ride along; DeleteOutcome + subject_gone file-local in their db modules
- service/homework.rs: HOMEWORK_LOCK moves here from web/homework.rs;
  update (writer lease + orphan guard), delete (writer lease + blob-key
  collection), gate_own_submission, require_open_term, award_badges
- service/homework_submission.rs: submit / delete workflows (reader lease)
- service/homework_file.rs: ensure_can_attach, insert/delete pass-throughs
- service/homework_result.rs: grade (writer lease + re-read + self/existence/
  role/enrollment/audience gates) and ungrade
- web/homework.rs: authz + DTO + blob I/O only; upload/delete-file lease the
  service-owned lock directly (web/exams/images.rs precedent) since the blob
  write sits inside the lease span
- service/course.rs: re-pointed to service::homework::HOMEWORK_LOCK and
  db::homework_file::file_keys_for_course (lock order EXAM_LOCK then
  HOMEWORK_LOCK unchanged)
- web/courses.rs create/list handlers call service::homework
- regression: regress_homework_orphans re-pointed to db:: paths

cargo check --all-targets clean; cargo test --lib 577 passed 0 failed;
regress_homework_orphans 8/8, partial_patch_homework 3/3
🧹 chore: split subject and term into domain/db/service layersAhmet Kaan Gümüş · 6533a0a
🧹 chore: split subject and term into domain/db/service layers

domain/subject.rs keeps SubjectId/SubjectName/SubjectDescription/Subject + getters
and the pure validation tests; domain/term.rs keeps TermId/TermName/gone_error/
archived_error/ref_move/Term + getters.

db/subject.rs: create (cap::touch_and_create), read, list_by_ids, list_for_course,
update (FieldUpdate), delete (guarded transaction). db/term.rs: create, read,
list_all, update (ordered range guard), delete (refcount-guarded), archive,
unarchive, stamp. Persistence race tests ride along byte-identical.

service/subject.rs: pass-throughs + the moved id resolvers in_course/must_exist
(was web::subjects helpers). service/term.rs: pass-throughs + require_open
(was Term::require_open), resolve (was web::terms::resolve_term), require_writable
(the archived-refusal gate update/delete handlers inlined), delete's linked-409
mapping (was web::terms).

Web: subjects.rs/terms.rs handlers call service only; the archived gate stays
ordered before the range pre-flight by calling service::term::require_writable
between read and write. Callers re-pointed crate-wide: web/courses.rs,
web/classes.rs, web/homework.rs, web/exams/{mod,questions}.rs, web/bank_questions.rs,
db/{course,exam,exam_attempt,exam_question}.rs (tests + doc links),
service/{course,exam_attempt}.rs, domain/{class_group,bank_question,homework,
homework_file,homework_result,homework_submission}.rs (tests + doc links),
tests/regress_course_{child_orphans,delete}.rs.

Purity verdicts: domain/{timestamp,monotonic_id,text_fold,role}.rs have zero
production query execution (text_fold's only .query( is inside a #[cfg(test)]
folding test) — they stay domain-only, no db/service modules.

cargo check --all-targets 0 warnings; cargo test --lib 577 passed 0 failed;
integration: 13 subject/term/question/homework route tests green.
Merge branch 'layer-split/exam'Ahmet Kaan Gümüş · e0fb40e
Merge branch 'layer-split/exam'

# Conflicts:
#	src/db/mod.rs
#	src/domain/course_session.rs
#	src/domain/exam.rs
#	src/domain/exam_question.rs
#	src/service/mod.rs
#	tests/regress_course_child_orphans.rs
Merge branch 'layer-split/enrollment'Ahmet Kaan Gümüş · c4e9b2c
Merge branch 'layer-split/enrollment'

# Conflicts:
#	src/db/mod.rs
#	src/domain/event.rs
#	src/service/mod.rs
🧹 chore: split course_session into domain/db/service layersAhmet Kaan Gümüş · 0ddaa5d
🧹 chore: split course_session into domain/db/service layers

domain/course_session.rs keeps the pure surface: CourseSessionId (its ULID
mint stays per the monotonic_id precedent), SessionTopic, the entity with
pub(crate) fields, getters, and the topic-bound validation test.

db/course_session.rs takes the query executors whole: create (the
cap::touch_and_create claim that bumps the course row in the same
transaction), read, list_for_course, the field-scoped update, and the
cascading delete transaction; the orphan-race persistence test rides along.

service/course_session.rs takes resolve_session_teacher out of the web
layer — the scheduling role floor (a student cannot teach a lesson) —
plus the thin doors the web layer now calls instead of the removed
inherent methods. No locks: course_session never held one; the range
guard rides inside the UPDATE's WHERE.

web/sessions.rs and web/courses.rs re-point every CourseSession call and
the shared resolve_session_teacher import to service::course_session;
call sites in domain/session_attendance.rs (incl. tests) and doc links in
domain/event.rs go to db::course_session. tests/ import fixes only.
🧹 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).

2026-09-07

✨ feat: OpenTelemetry bootstrap — OTLP traces/metrics/logs, request spans, request idsAhmet Kaan Gümüş · 057a7fa
✨ feat: OpenTelemetry bootstrap — OTLP traces/metrics/logs, request spans, request ids

Telemetry is off unless OTEL_EXPORTER_OTLP_ENDPOINT is set, mirroring the
AI bridge's "off unless configured" shape. With it unset the process logs
exactly as before; every instrument binds to the noop meter provider, so
call sites never branch on whether telemetry is on.

Privacy is the design constraint (KVKK): a span carries the method, the
route TEMPLATE, the status, a random request id and the school slug —
never a user, an IP, a URL path, a body, a header or a cookie.
tests/telemetry.rs fails the build if a forbidden attribute key appears.

New variables (all documented in .env.example):
  OTEL_EXPORTER_OTLP_ENDPOINT   presence turns export on
  OTEL_EXPORTER_OTLP_PROTOCOL   grpc (default) | http/protobuf
  OTEL_EXPORTER_OTLP_HEADERS    read by the SDK
  OTEL_SERVICE_NAME             read by the SDK, defaults hezarfen_backend
  OTEL_TRACES_SAMPLER(_ARG)     read by the SDK, parent-based always-on
  LOG_FORMAT                    pretty (default) | json; anything else refuses to boot
  DEPLOY_ENV                    deployment.environment.name

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

2026-09-05

✨ feat: per-school modules; a disabled module answers 403 on every route in its nestAhmet Kaan Gümüş · 5d7f87c
✨ feat: per-school modules; a disabled module answers 403 on every route in its nest

Twenty-one modules, one per router nest, with an explicit dependency graph
derived from the record links (exams need courses and subjects, marks need
exams, …) and four packages for the catalog. The enabled set lives on the
school's control row and rides the tenant resolution that already happens
once per request; every nest carries a route_layer gate, the four child
creates inside /courses are gated by their own module, and the AI blob
stream refuses `module_disabled` when course notes are off.
✨ feat: 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: archive academic terms; an archived year is read-onlyAhmet Kaan Gümüş · c4232e6
🗄️ feat: archive academic terms; an archived year is read-only

`Term.archived_at` (nullable, no backfill) plus `POST /terms/{id}/archive`
and `POST /terms/{id}/unarchive` (manager+, idempotent: a repeat archive
keeps the original stamp). While a term is archived its own PATCH/DELETE,
linking a new course or class to it, and every write to a course or
class on it — enrollment, teacher assignment, class membership and
attach/detach/blueprint apply, sessions and roll call, subjects, exams
with their questions, images, attempts and answers, the exam-room
WebSocket door and `finish` frame, grading, homework and submissions,
course notes and files — answer `409` with `code: "term_archived"`.
Reads stay open. The guard is a pre-flight read of the term row: an
archive landing in the same instant as a write lets that one write
through (documented as the third accepted race).

Out of scope on purpose: personal notes, messages, pomodoro, meals,
payments, boards, appointments, chatbot, question pool/bank, events,
blueprint templates, the staff work log, and the role-demotion and
subject-delete integrity sweeps.

Coverage: 155 write routes classified (59 guarded, 93 out of scope);
e2e over real TCP covers archive → refused writes → open reads → the WS
handshake 409 → unarchive; the class refusal-code pin gains
`term_archived`; README prose, tag text and endpoint table regenerated.

Closes #22.

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

📝 fix: close the homework orphan window and the subset roster leakAhmet Kaan Gümüş · 420deef
📝 fix: close the homework orphan window and the subset roster leak

upload_submission_file streamed the whole multipart body before taking
HOMEWORK_LOCK, and HomeworkSubmission::upsert had no parent gate, so a
DELETE /homework/{id} inside that multi-second window let the late write
recreate submission, file, blob and badge credit under vanished
homework — all unreachable afterwards. Both halves are fixed: the gate
re-runs under the lease, and the upsert now moves a value on the
homework row.

HomeworkResult::grade gets the same treatment, in the order its own
ponytail asked for: transaction_with_retry first, then the parent gate.
delete_course now takes HOMEWORK_LOCK as well as EXAM_LOCK.

HomeworkResponse.assigned returned the full subset roster to every
assigned student, while the course roster itself is teacher+ only — the
opposite of what the code comment says it intends. It is now narrowed to
the viewer.

HomeworkFile::delete moves to transaction_with_retry like its siblings.
fix: 📚 hold the exam lease while a course cascade sweeps sittingsAhmet Kaan Gümüş · 340ff4f
fix: 📚 hold the exam lease while a course cascade sweeps sittings

delete_course takes the same cascade delete_exam does — its courses'
exams and their attempts — and had the same hole: an attempt is the one
exam child whose write cannot collide with the sweep, because its claim
lands on the student's row rather than the exam's.

Narrower than the exam twin, since the delete is refused while anyone is
enrolled: a start would have to pass its enrollment gate and then have
that enrollment removed under it. Same hole, same lease. Nothing on this
path takes another lock, so it adds no ordering pair.

No test of its own — the window needs an unenroll landing inside a
start's own lease, which no sequence of HTTP calls can arrange. The
mechanism is the one regress_exam_delete already pins.

2026-08-04

feat: 🎖️ earn badges on both sides of the classroomAhmet Kaan Gümüş · 46c76f5
feat: 🎖️ earn badges on both sides of the classroom

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

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

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

Every counter moves inside the transaction of the write that causes it.
The streak needs two statements rather than one because sibling SET
clauses read the row's before-state, so `longest` would lag `current`
forever; the pair sits in one transaction, and `max` keeps it monotone
under every interleaving, verified on a real 3.2.3 server. No backfill
and no migration mark: every counter starts at zero at this deploy.

2026-08-02

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

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

Defects closed:

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

Features:

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

Forcing functions, because a hand-kept copy drifts:

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

Verified by a three-lens verifier panel — which caught the `banked_as`
half of the answer-key leak by executing a probe, after the first fix
had been reported complete — and by a podman boot against the existing
volume: both new fields defined, the marker written, boot 2 skipping the
scan, and the live API answering on the new routes.
fix: 🔩 make ownership a live grant, not a permanent oneAhmet Kaan Gümüş · 8c0ba1e
fix: 🔩 make ownership a live grant, not a permanent one

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

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

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

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

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

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

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

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

Left standing: `set_role` still writes the role before its sweeps and
they are not one transaction. Every sweep is idempotent and, now that
rights are re-read live, grants nothing in the meantime.
feat: 🧑‍🏫 give a class section a homeroom teacher and open it to studentsAhmet Kaan Gümüş · e590b84
feat: 🧑‍🏫 give a class section a homeroom teacher and open it to students

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

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

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

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

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

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

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

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

Known and left: can_manage_course still trusts Course.creator without
re-reading the live role, so a demoted creator keeps course-management
reads — its own series. set_role writes the role before its sweeps and
they are not one transaction; every sweep is idempotent and grants
nothing, so a re-sent PATCH repairs the residue.
fix: 🔩 close the bug hunt across meals, classes and capsAhmet Kaan Gümüş · 7198cea
fix: 🔩 close the bug hunt across meals, classes and caps

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

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

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

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

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

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

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

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

2026-08-01

2026-07-27

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

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

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

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

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

Every guard is mutation-proven; backfills are one-time, = NONE-guarded,
ordered after the destructive sweeps, and verified against the live
volume.
fix: 🪢 guard writes in the database, not the processAhmet Kaan Gümüş · 6c87eca
fix: 🪢 guard writes in the database, not the process

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

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

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

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

2026-07-25

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

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

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

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

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

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

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

Two duplicated `maximum = 500` literals are now pinned to
`MAX_PAGE_LIMIT`, which `constant.rs` previously only asked a human to
keep in step.
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

2026-07-24

✨ feat(exams): let students review their own graded examAhmet Kaan Gümüş · 4db4ff2
✨ feat(exams): let students review their own graded exam

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

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

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

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

2026-07-22

✨ feat(deletes): guard course, exam-kind, and term removalAhmet Kaan Gümüş · 9191711
✨ feat(deletes): guard course, exam-kind, and term removal

Three referential-integrity guards, all 409 instead of silently taking
dependent data with them:

- DELETE /courses/{id} refuses while anyone is enrolled. The cascade
  used to delete the enrollments along with the course, so a roster
  could vanish on a misclick; the check and the delete are held under
  ENROLL_LOCK so a concurrent enroll cannot slip in behind it.
- PATCH /settings refuses to drop an exam kind whose exams already
  carry marks. Weights resolve live, so removing the kind would
  re-weight every one of those marks to 1 without touching a row. The
  check is re-run per CAS retry against the snapshot the save is
  conditioned on, under an EXAM_LOCK writer lease so grading cannot
  land the first mark mid-flight. An unmarked kind still leaves freely.
- DELETE /terms/{id} refuses while any course links it, rather than
  unlinking those courses. Guarded by a new TERM_LOCK, taken by the
  course writes that assign a term. Lock order: never held together
  with ENROLL_LOCK; if a path ever needs both, ENROLL_LOCK first.

No rows change; existing courses with a roster and terms with linked
courses simply need emptying before deletion. Frontend must surface
the new 409 on all three.
🐛 fix(exams): reject a duration over its windowAhmet Kaan Gümüş · ea17828
🐛 fix(exams): reject a duration over its window

An `async` exam accepted any `duration_ms` inside the global 1min–24h
bounds, even one longer than its own `starts_at`..`ends_at` window. Such
a schedule saved happily and was then silently truncated at attempt
time: a teacher who set 90 minutes inside a 60-minute window saw a
90-minute exam echoed back, while every student actually got 60. The
lie only surfaced once students were already sitting it.

`ExamSchedule::try_new` now rejects that up front with a 400
(`duration_ms: must fit within the starts_at..ends_at window`), so the
impossible schedule never reaches the database at all. Runtime
enforcement was already correct — `ExamAttempt::deadline()` caps the
personal deadline at `ends_at` — and is untouched; this only stops the
teacher from being told something the exam will not honour.

The bound is inclusive on purpose. A duration exactly equal to the
window is a legitimate "the whole slot is yours" exam, and because
`update_exam` re-validates the entire stored schedule on every PATCH, an
exclusive bound would have made an existing row like that unpatchable
for completely unrelated edits (title, kind, attempt limit). Only
`async` can reach the check: `sync` takes no duration and `open` has no
window.

The unit test `schedule_invariants_hold` used to assert the buggy
behaviour, so it flips to the fix plus the inclusive boundary. Two
integration tests happened to be built on now-illegal schedules and were
moved onto legal ones without losing what they cover.

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(courses): manager-assigned course teachersAhmet Kaan Gümüş · 5ff771b
✨ feat(courses): manager-assigned course teachers

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

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

The rights split in two:

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

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

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

A demotion below teacher sweeps the user off every course they were
assigned to, mirroring how promotion drops enrollments.

2026-07-19

✨ feat(courses)!: embed the creator as a person refAhmet Kaan Gümüş · c996ce4
✨ feat(courses)!: embed the creator as a person ref

CourseResponse.creator was a bare user id, so the frontend catalog
resolved names by downloading users separately — a call that broke
with the blank-q rule and left students seeing raw ULIDs. Courses now
join the creator on like sessions and enrollments already do: one
person_map over the page's creators, PersonRef::resolve degrading to
the bare id if the row is gone.

BREAKING: course payloads return creator as {id, username,
display_name} instead of a string.