Commits
2026-09-24
✨ 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-23
✨ feat: school identity is the uuid; drop the slugAhmet Kaan Gümüş · 2918040
✨ feat: school identity is the uuid; drop the slug
The school slug is gone from every surface: the session cookie prefix,
the /schools/{id} builder routes, FILES_PATH blob dirs, the hab/2 frame
school value, DTOs, and the /limits contract. SchoolId::try_parse is the
one wire parse (hyphenated uuid only); a non-uuid frame school answers
unknown_school. Register gets a public picker via the new unauthenticated
GET /auth/schools returning active [{id, name}]. The control migration
drops school_slug and the slug column, which invalidates every existing
session — old cookie prefixes cannot resolve.
Local-Gate: 3fafffd98aec59c68e2606833b87785d0abf2fee (1510 passed, 425s)2026-09-17
✨ 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).
✨ feat: publish the rag.chat payloads and a GET /ai/capabilities probeAhmet Kaan Gümüş · 94cffa0
✨ feat: publish the rag.chat payloads and a GET /ai/capabilities probe Add the rag.chat capability's wire contract (scoped question -> answer with citations), the max-scope-pairs and rate-limit constants, and an authenticated discovery route listing each capability's connected worker fleet. Document the payloads and the rag.index reply's file<->doc_id echo in the README.
2026-09-16
✨ feat: archive an academic year, attribute shared-exam marks, index the new FKsAhmet Kaan Gümüş · b3f7395
✨ feat: archive an academic year, attribute shared-exam marks, index the new FKs
Follow-ups on the K12 remodel:
- `POST /academic-years/{id}/archive` (Manager+): stamps `archived_at`
idempotently, making the existing `academic_year_archived` guard reachable —
every write into an archived year now 409s while reads stay 200. No
unarchive; no PUT.
- Marks and the report card attribute an exam via its `exam_audience` rows, not only its
owner instance: a shared exam's mark now stands in every addressed class section's
report instead of vanishing when the owner instance isn't in the student's
list. Owner-only exams are unchanged (the owner audience row always exists).
- `GET /instances/me` now serves the full visibility set (live member ∪
instance teacher ∪ class-section homeroom), so a teacher's own list is meaningful.
- Migration `20260916000002_k12_indexes.sql` adds the indexes the remodel's
drop/recreate left out: `enrollment(app_user)` (dropped with its table),
`course_membership(app_user)`, and `exam_audience(class_course)` (read by
every per-instance exam read).
Tests: the archived-year e2e now archives via the route; new regressions pin
the sweep's `term.exam_count` release (the term becomes deletable) and the
blueprint sweep's blob unlink, each with a mutation witness; new shared-exam
attribution tests (fail-pre-fix/pass-post-fix for both reads) and the
`/instances/me` union.
Gates: check --all-targets (offline cache regenerated), doc_sync,
spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1376/1376.✨ 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
🐛 fix: board roster tests write board_participantAhmet Kaan Gümüş · 2ba3280
🐛 fix: board roster tests write board_participant The junction FKs to app_user, so fabricated UserId::generate() and UPDATE board SET participants (dropped column) 23503/fail in CI.
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
🧪 test: port e2e, rate_limit, ai_bridge, ai_protocol to the Postgres harnessAhmet Kaan Gümüş · e0e3597
🧪 test: port e2e, rate_limit, ai_bridge, ai_protocol to the Postgres harness e2e: spawn_server_with_ai re-pointed at init_test_tenants; the board helpers read and seed through runtime sqlx (stroke ids, payloads, epoch, participants roster); promote writes app_user; ULID literals became common::ABSENT_ID. rate_limit: the durable-window trio stands on one control database's rate_limit table (two UserRateLimiters, pools dialed before the clock freezes); fold reads are query_scalar; the down-database leg takes the fold's table away and hands it back instead of flipping the deleted health flag; embedded-engine caveats deleted. ai_bridge/ai_protocol: bootstrap renames plus the chatbot history seed inserted over sqlx; the down-socket test outages the school registry table and recovers, keeping both original assertions. src/rate_limit.rs: rebuilt the wave-1-deleted epoch-roll unit test (a_wall_epoch_roll_charges_no_request_twice + its admits helper) over the control database, driving sync_once's epochs directly.
2026-09-11
🧹 chore: split profile, badge, builder into domain/db/service layersAhmet Kaan Gümüş · 7f616c0
🧹 chore: split profile, badge, builder into domain/db/service layers
C3 identity lane. Moves, not rewrites:
- badge: BadgeStats::load / BadgeAward::list_for / sync (UPSERT with the
earned_at = NONE idempotency stays whole) -> db::badge, with the
award-key mint and the persistence tests; BadgeStat/BadgeStats/earned/
BadgeAward (pure rules) stay in domain::badge; service::badge wraps
list_for/sync for the web layer.
- profile: ProfileStats::load (+ PomodoroTotals, persistence tests) ->
db::profile; newtypes + getters stay; service::profile::load wraps.
- builder: find_by_username/read/create(create_session)/find_by_token/
delete_by_token -> db::builder; the idempotent seed ensure ->
service::builder (ensure_admin precedent); both tests ride their fns.
- preferences, key: fully pure (validated newtypes, composite-id
helpers) — stay domain-only, no db/service modules created.
Entity fields the split constructs from are now pub(crate) (Builder,
BuilderSession, ProfileStats), matching the user split.
Callers re-pointed crate-wide: web/{users,exams/mod,questions,homework,
sessions,auth,extractor,builder,tenant_state}, service/exam_attempt.rs
(badge::sync after start), database.rs (control seed), tests/
{builder_api,e2e,integration}; cross-lane compile fixups in
domain/pomodoro.rs and domain/session_attendance.rs (their lanes
re-point on merge). constant.rs doc link -> crate::db::badge::list_for.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
✅ test: isolation probes across two schools; the builder seed is both-or-neitherAhmet Kaan Gümüş · 1b12ff7
✅ test: isolation probes across two schools; the builder seed is both-or-neither Ten verifier probes: lists show only the caller's school, foreign ids 404 on paths and are refused in bodies, school rows never reach the control database, suspension closes login, live cookies and both WebSocket rooms until resume, cookies cannot cross the builder/school line, uploads are school-scoped, and two hyphenated schools stay apart on a real server.
Merge branch 'worktree-agent-a93ac88fd41c12daf'Ahmet Kaan Gümüş · 933e1e3
Merge branch 'worktree-agent-a93ac88fd41c12daf' # Conflicts: # src/lib.rs
✨ feat: builder API — the vendor creates, suspends, enters and deletes schoolsAhmet Kaan Gümüş · 1ab298d
✨ feat: builder API — the vendor creates, suspends, enters and deletes schools
`POST /builder/login|logout`, `GET /builder/me`; `POST|GET /schools`,
`GET|PATCH|DELETE /schools/{slug}`, `POST /schools/{slug}/admin-password`,
`POST /schools/{slug}/enter`. Builder sessions live in the control database
behind their own strict per-IP login tier; deleting a school drops its
database and its files subtree.✨ feat: AI bridge speaks hab/2; every frame names its schoolAhmet Kaan Gümüş · cedd07f
✨ feat: AI bridge speaks hab/2; every frame names its school The shared AI fleet now serves every school: `Request`, `ApiRequest` and `BlobRequest` carry `school`, responses echo it, api-reads and blob opens resolve that school's database and files, and rag answers land in the same school. New refusals `unknown_school` / `school_suspended`; hab/1 is rejected at ALPN and at `Hello`.
✨ 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.✉️ feat: messages go upward only; students and parents can search staffAhmet Kaan Gümüş · 1d423c0
✉️ feat: messages go upward only; students and parents can search staff A student or parent may only write to a teacher, manager or admin (`Role::may_message`); staff still write to anyone. `POST /messages` answers 403 below that bar, and only new sends are gated — stored student↔student rows stay readable and filable. `GET /users/search` opens to every signed-in role: a caller below teacher sees only the staff they may message (the restriction sits in the query, so `total` stays right), and asking for `role=student` or `role=parent` from there is a 403. This is the recipient picker the messaging rule needs. Closes #23, closes #24.
2026-08-13
🧪 test: name the race-window staging class on keep-site sleepsAhmet Kaan Gümüş · e1471df
🧪 test: name the race-window staging class on keep-site sleeps 8 sleeps classified non-convertible (negative assertions / mid-held- transaction staging) and marked in place; zero durations changed.
chore: rename ponytail: comment marker to corner-cut:Ahmet Kaan Gümüş · ed88733
chore: rename ponytail: comment marker to corner-cut: Marker convention renamed after uninstalling the ponytail plugin; semantics unchanged (deliberate corner-cut, known ceiling + upgrade path). Token-only rename, 26 comment lines, no code change.
2026-08-04
feat: 🏗️ stock a new section from its grade's blueprintAhmet Kaan Gümüş · 67ced09
feat: 🏗️ stock a new section from its grade's blueprint Editing a template reached every section already at the grade, but making a section reached no template — so a blueprint described every section except the ones created after it, and the office had to remember a second call each time. A create now applies its grade's blueprint, after the homeroom demotion rollback and never before it: the rollback deletes the class, and that delete refuses while the class holds courses. The 201 body carries the class, what could not be stocked, and which grade's template stocked it — null when none covers the grade, which is also what a stocking that faulted reports, because a 500 here would strand a section whose id nothing else returns.
feat: 🧑🏫 invite a whole class or club to a boardAhmet Kaan Gümüş · 0e3eae0
feat: 🧑🏫 invite a whole class or club to a board
A board roster was one id at a time, so opening a canvas for a class
meant typing thirty of them and the cap refused an ordinary club.
POST /boards/{id}/invite names a group instead — a class section, a
course (a club is a course), or an event's roster, resolved through the
audience machinery events already had. The ids expand once, into the
same flat participants array: a snapshot, not a subscription. Live
resolution would have made is_participant, the room's door and
list_for_user cross-table queries, and would have taken per-person
removal away from the creator, which is most of what a board roster is
for. The board stores no source, so re-inviting is both how a roster is
topped up and the one thing that undoes a removal.
Additive only; removal stays PATCH. The participant cap moves 50 -> 200
and is all-or-nothing — a partial invite would silently pick which half
of a class gets to draw. Ineligible members (gone, or below student, or
already there) drop silently, because one of them must not fail the
invite for the other twenty-nine.
The gate is not a new permission: a roster is visible to everyone on the
board, so inviting a group discloses it, and each source carries the
gate its own listing route carries. Bulk invite is therefore teacher+;
a student can still build a board by hand but cannot pour a class into
one.
resolve_participants now batches its lookup. It read one row per id,
which at the new cap made a read-modify-write PATCH of a class-filled
board — the ordinary client shape now — two hundred sequential reads.2026-08-02
fix: 🔩 close the leaks a five-domain hunt turned upAhmet Kaan Gümüş · a3fe8cf
fix: 🔩 close the leaks a five-domain hunt turned up Five hunters swept exams, homework/attendance, identity, money/scheduling and messaging/courses; a three-lens verifier panel then refuted three of the first fixes, and those corrections are folded in here. Leaks and races closed: - exam self-review gated on *any* mark, so a seq-1 grade opened the answer key forever — a student mid-retake read `correct` and `is_correct` off the sheet they were still writing. All four review reads now 409 while the caller's latest sitting is in progress. - roll call could land after its session was deleted, and the orphan was unremovable (its delete route 404s on the vanished session) while the attendance report went on counting it. The write now proves its parent exists in the same transaction, the way ExamResult::grade does. - a teacher could counter-propose and then approve their own proposal, committing the requester to a time only the teacher ever named; and even after that, re-proposing between the requester's read and their accept moved the meeting under them. Approve refuses while a proposal stands, and accept now pins the window it is answering. - two concurrent chatbot posts on one thread cross-attributed their answers — both replied to the second prompt, the first was never answered. The prompt id rides the request instead of being re-derived from write order. - a whiteboard participant demoted to `parent` kept drawing, and kept *reading* the live canvas for up to 15s. Every frame is authorized before delivery now, and a demotion sweeps the account off rosters. - a demotion to `parent` stranded event signups no one could free. Promotions are left alone (staff free their own seats) and closed lists are never rewritten. - the rate-limit bucket map was unbounded past 10k live keys and then scanned O(n) under the global mutex on every request. Eviction is bounded and never frees an exhausted bucket — the first attempt did, which traded a memory bug for an auth-bypass, so it is pinned by a test that floods at the victim's own spend. - session and event cascades ran as loose queries; a concurrent write slipped between them and orphaned rows, and for notes a blob nothing could ever reclaim. All three are one transaction now. - sixteen id generators still used Ulid::new(), whose random low bits scramble same-millisecond rows under the "newest first" the docs promise; five listings had no tie-break at all, so offset paging could skip or duplicate a row. Also: $session is a protected SurrealDB 3 variable — binding it fails the whole query as a bare 500, which is what hid the attendance fix. Accepted, documented, not fixed: one bank template instantiated into two exams copies `correct` into both, and the review gate is per-exam.
fix: 🔩 close the bug hunt across meals, classes and capsAhmet Kaan Gümüş · 7198cea
fix: 🔩 close the bug hunt across meals, classes and caps A three-domain hunt, its fixes, and a verifier panel that refuted two of them. Kept as one commit because the pieces interlock — cap.rs, the settings pair and the pump all move together, and no smaller cut compiles. Money can no longer be lost or stranded. Both seat transitions carry their ledger line inside their own transaction: the claim writes the charge, the flip writes the reversal. Before, a crash between the two left a seat held with no bill, or a bill with no seat, keyed to an attempt no later request could ever reach. A lost cancel could refund a live seat. The menu revision was bumped in a query of its own, so a booking reading in the gap claimed against a capacity or a price the menu had already left. Deleting a menu now takes its marks and its dishes with it, in the transaction that deletes the row. The id is deterministic on (date, slot), so anything left behind came back on the next publish — the kitchen reading "served" for a student who never came. A seat is always releasable: manager+ cancels any booking and is not bound by the cutoff, so a promoted student's seat no longer wedges its menu forever, and a debt that outlived its owner's role can be settled. Canteen money follows /payments and is manager+, not teacher+ — what a family owes the school is not classroom information. The class pump claims its pivot in-transaction. An attach racing a course delete used to commit a link to a row that was gone, and nothing could then detach it or delete the class. A hand enroll now disowns a pumped row, so a sweep cannot take back a roster decision an operator made by hand. The role sweep is one transaction. Rosters are ordered by when a student was added, which is what they always claimed. Both class axes have a ceiling, and each refuses on the other's, because a pump writes one row per member per course in a single transaction. Settings edits are serialized: retire is idempotent, so an undo log cannot tell the attempt that flipped a name from one that found it already flipped, and the loser un-retired what the winner had legally retired — leaving a kind gone from the list, gradable, and unremovable for good. Grading now checks the school's list, not only the counter. Three caps that read a snapshot integer now read the live column. A clear marker is charged to the board's lifetime counter and boot repairs the boards that predate it. Blank canvases refuse the clear, and the room reports that as its own code: the refusal text had drifted into the substring the WebSocket read as "closed", which told a live room it was permanently read-only. Verified against the real volume: both boot backfills, the slot-name rule and its grandfather clause, and the new money gate.
2026-08-01
2026-07-31
fix: 🖍️ name the board roster the same on the way in as on the way outAhmet Kaan Gümüş · 43bbae8
fix: 🖍️ name the board roster the same on the way in as on the way out
POST /boards read the invite list from `participant_ids` while the board
response and PATCH /boards/{id} both call it `participants`. Serde ignored
the unknown key, so a client that posted back a board it had just read got
a 201 for a board it was silently alone on — no error, no roster, a seat
spent. The create field is now `participants` like the other two; the repo
is pre-customer and the real volume holds zero board rows, so it is a clean
break with no alias and nothing stored to migrate.
Both board request bodies also deny unknown fields now, which makes the
next misspelling a 422 instead of a silent drop. That is deliberate local
deviation: no other REST DTO in this crate does it, and only these two have
already proven what ignoring a key costs.
Board::delete goes through transaction_with_retry. It was a bare query +
check() around a five-statement cascade that writes the stroke rows, the
board row and the creator's board_count; a stroke claim touching the same
board row aborts it, and check() retired that retryable round as a 500. No
statement can legitimately answer "already exists" — the DELETEs are
idempotent and the UPDATE is field-scoped — so re-sending is sound, and a
forced-abort probe confirmed the aborted round leaves the board, its
strokes and the seat untouched. No statement moved: RETURN stays slot 4.fix: 🚫 keep parents off the whiteboard entirelyAhmet Kaan Gümüş · 860b4ce
fix: 🚫 keep parents off the whiteboard entirely A parent is the school's read-only observer, but every board route was `CurrentUser` only — so a parent could open a board and draw on it. The cut that does the work is in `resolve_participants`: a parent id is refused as a participant, so a parent is never on a roster. That alone makes `board_for` and the room's door answer the outsider's 404 on every id-scoped route. `POST /boards` and `GET /boards` take `RequireStudent` (a 403 there leaks nothing — no board exists to hide), while the read path and the socket door re-check the role and answer 404, never 403, which would confirm the board is there. Refusing the door is also what stops a parent drawing: no socket, no `stroke` frame, and no per-stroke role read on the hot path. A board row written earlier that still lists a parent is inert — that parent now sees a 404 for it like any stranger.
feat: 🖌️ open the live board room over a WebSocketAhmet Kaan Gümüş · b9f3988
feat: 🖌️ open the live board room over a WebSocket
`GET /boards/{id}/ws` is the drawing half of the whiteboard: one socket per
participant, persist-then-publish so the fan-out can never carry a mark the
database refused, and a join that replays the current epoch only — a clear
bumps the epoch, it never deletes.
A `Lagged` receiver is the one failure that would corrupt a canvas silently,
so it says so and re-serves the whole current epoch rather than diffing from
a cursor whose gap is exactly what is unknown.
Every gate runs before the upgrade, so a stranger gets a 404 status and not
an instant close, and the roster is re-read on every stroke, clear and lock:
a frame is the prompt, the row is the authority.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-25
style: 🏷️ rename the echoed exam-room seq to client_seqAhmet Kaan Gümüş · 61bd820
style: 🏷️ rename the echoed exam-room seq to client_seq `seq` already means the attempt number everywhere else in this domain — it is the key of an exam sitting, and the room's own `state` frame ships it as `attempt`. A second `seq` on the neighbouring frames read as the same thing. Wire rename only, and the field shipped minutes ago, so nothing is depending on the old spelling yet.
feat: 🏷️ echo the client's seq on exam-room saved and error framesAhmet Kaan Gümüş · 9e25eac
feat: 🏷️ echo the client's seq on exam-room saved and error frames `question_id` is not an identity. A student who saves q1, times out, and saves q1 again has two sends outstanding for the same question, and the first reply settles the second send — the badge read "Saved" for an answer the server never accepted. That shipped. The answer frame now takes an optional `seq`, echoed verbatim on both the `saved` and the `error` reply. The server never reads it: uniqueness and monotonicity are the client's problem, and a repeated value is echoed as sent. Errors carry it even where `question_id` is not attributable, which is exactly the case a client could not match before. Omit it and every frame is byte-identical to before — the key is absent, never null. `deny_unknown_fields` stays, since that is what made a correlation id unsendable until now.
fix: 🔒 cap the echoed question_id, and de-flake the exam-room testAhmet Kaan Gümüş · f62fb74
fix: 🔒 cap the echoed question_id, and de-flake the exam-room test cd6c1e4 started echoing `question_id` back in the per-question error frame, but the field was an unvalidated `String` and axum's default WebSocket message limit is 64 MiB, so a client could make the server echo ~64 MiB to itself. It is now length-checked against `MAX_QUESTION_ID_LEN` (64 — real values are 26-char ULID keys) before any lock or database work, and rejected *unattributed* so nothing of the oversized id is reflected. `exam_room_expires_mid_session` was flaky for a real reason, not a tight sleep: the fixture sampled `GET /time`, then made five more HTTP calls including a full argon2 login — costlier since 684f18b — and all of it had to fit inside the 2.6 s window it had just set. On a loaded run the setup outlived the exam and the attempt hit a closed window, 409. Setup now happens outside the window and the teacher shortens `ends_at` after the answer lands, which drives the same live-schedule path the extension test already covers, in the other direction. 20 runs, 20 passes.
🎨 style: cargo fmt the tree before the audit fixesAhmet Kaan Gümüş · b4a5a00
🎨 style: cargo fmt the tree before the audit fixes Pure reformatting, no behaviour change: rustfmt wrapping plus its alphabetical `use`-list reordering across the files that had drifted. Kept separate so the correctness commits that follow carry only logic.
fix: 🔎 Turkish search folding for users, per-question exam-room errorsAhmet Kaan Gümüş · e0f9d63
fix: 🔎 Turkish search folding for users, per-question exam-room errors - User::search folded its needle with Rust to_lowercase and its columns with SurrealQL string::lowercase; both turn İ into i + U+0307, so searching "ilker" never found "İLKER". It now runs both sides through the shared text_fold table, like the question bank already does - exam-room error frames carry question_id when the failure belongs to one save — a validation reject or an unknown question, raised inside the save past the sitting gates. The client could not tell which save failed and had to fail every one in flight - auth, conflict, malformed-frame and database errors stay unattributed on purpose: they doom the next save too, and a failed database is not a per-question fact. An absent question_id keeps its old meaning - Subject::update is field-scoped: the handler holds no lock across its read and write, so a whole-row save reverted a concurrent edit of the other field - annotate the three whole-row saves that genuinely cannot be raced (exam update holds EXAM_LOCK across the read; the two image upserts build their struct in place under a deterministic slot id)
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-23
🔥 feat(exams): drop the live-monitor SSE stream for poll-onlyAhmet Kaan Gümüş · bacd9ed
🔥 feat(exams): drop the live-monitor SSE stream for poll-only
Remove `GET /exams/{id}/live/stream`. The teacher monitor now polls the
one-shot `GET /exams/{id}/live` (kept, untouched) on a 2s interval — the
SSE feed ran at the same cadence, so it added no freshness, only a second
snapshot build per watcher and a permanently-dead-on-first-error path in
the client.
Drops the `exam_live_stream` handler, its route + utoipa block, the
`EXAM_LIVE_STREAM_INTERVAL_SECS` constant, and the now-unused SSE imports
(Sse/Event/KeepAlive/IntervalStream/Stream). Removes the two e2e stream
tests + the `next_matching_snapshot` helper and the integration
route-auth cases. README route table and prose updated; KB re-ingested.🎨 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(chat): relay chatbot over the AI bridgeAhmet Kaan Gümüş · b0aa0a1
✨ feat(chat): relay chatbot over the AI bridge The backend relays between the frontend and an out-of-process AI service: it owns auth, rate limiting, persistence and payload format, and may inspect an answer before the frontend sees it. No rule or intent tables — conversation is free-form. Two-phase by design. POST persists the pending assistant row *before* dispatching, then returns 202, so a reload never loses an answer; the client either polls the message or opens an SSE stream. Both read the same DTO, so they cannot disagree. Deltas are sliced from the finished text because hab/1 is unary — the event shape exists so real streaming drops in later without a client change. A turn always settles. Every failure after the rows are written marks the row failed with a machine-readable code, a boot sweep flips rows orphaned by a restart, and a pending row older than five minutes reads as timed out — projected at read, never written back, so a slow-but-alive answer is not raced. An over-long answer is clipped and flagged rather than dropped; an empty one fails. Message ids come from a monotonic ULID generator: the two rows one POST writes share a millisecond routinely, and a random tie-break rendered the answer above its own question and handed the service [assistant, user], breaking the documented oldest-first history contract. The conversation cap counts and creates under a lock — SurrealDB BEGIN/COMMIT does not serialize cross-record counts, and 16 concurrent creators over-admitted a cap of 5 to 20 without it. Every authenticated role may chat, parents included. Foreign threads are 404, never 403.
✨ feat(ai): QUIC bridge for out-of-process AI servicesAhmet Kaan Gümüş · dc49954
✨ feat(ai): QUIC bridge for out-of-process AI services The AI features live in separate projects, so they need a transport. QUIC: each request rides its own bidirectional stream on the service's single long-lived connection, which puts multiplexing in the transport — no correlation-id bookkeeping, no head-of-line blocking between concurrent requests, one handshake instead of one per request. The backend listens and the services dial in, so a service can sit behind NAT, restart without the backend knowing its address, and scale out by opening a second connection (each connection is an independent worker). Protocol "hab/1", also the ALPN so an incompatible service is refused at the TLS handshake rather than one frame later. Frames are length-prefixed JSON (u32 big-endian) because the services will not be Rust; the length is checked against an 8 MiB cap before any buffer is allocated. The control stream carries Hello/Greeting and then stays open — its closure is the goodbye, so there is no heartbeat frame, and a silent death is caught by the QUIC idle timeout. Routing is least-inflight rather than round-robin: AI request costs are wildly uneven, and taking turns would pile a second long inference onto a busy worker while an idle one sits next to it. Selection and the in-flight increment happen under one lock so concurrent dispatches cannot overshoot a worker's declared max_concurrent, which a Lease releases on drop. Services authenticate with a shared token (constant-time compare); the certificate only proves the backend, and is self-signed at boot unless a PEM pair is configured. Since that regenerates per boot, GET /ai/certificate publishes it (PEM + sha256) for a service to pin — public because a server certificate is handed to every peer in the TLS handshake anyway, and 404 when the bridge is off. A service must re-fetch on every reconnect, not once at startup. Off unless AI_QUIC_ADDR is set, so the API is unchanged for deployments without AI. Set without AI_SHARED_TOKEN it refuses to boot rather than listen unauthenticated.
2026-07-21
🐛 fix(db): retry boot connect, refuse while socket downAhmet Kaan Gümüş · bebca49
🐛 fix(db): retry boot connect, refuse while socket down Two failures survived 6627128, which only classified errors from queries in flight *at* the drop — queries arriving after it produce no error at all, so there was nothing to classify. Boot did one connect() and exited on refusal. The runtime then restarted the process, it failed again in ~100ms, and a few seconds of startup skew burned the whole restart budget: 6 deaths in 0.6s in the field log, then down for 12h. Now retries 1s doubling to 5s, forever — only the dial, since bad credentials never heal by waiting. A query issued while the socket is down does not fail. The SDK's router_reconnect loops on 1s retries and stops draining route_rx, so the query parks until the database returns and only then executes. Reproduced: POST /auth/login gave no response at 25s, and the keepalive went silent 4m17s before firing two pings in the same millisecond on heal. Those two pings rule out a plain timeout middleware — a parked query still runs, so a timeout-sourced 503 would let a client retry double-apply a mark or an exam answer. Instead the keepalive (now 5s) publishes DbHealth and db_guard refuses at the edge, before anything is queued, which is what keeps Retry-After: 1 honest. The 30s request timeout is only a backstop for requests racing detection; those answer DbTimeout — same 503, no Retry-After, "may or may not have applied". WS and SSE are unaffected: both return their response immediately and stream afterwards. Known gap: exam_ws socket-loop queries run after the upgrade response, so db_guard does not cover them; they still park and heal on reconnect. Verified in podman against the existing volume: boot with the database down backs off and stays alive, requests during an outage answer 503 in 0.3ms, recovery needs no restart.
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-15
✨ feat(notes): file attachments with school-set size capAhmet Kaan Gümüş · f1b532b
✨ feat(notes): file attachments with school-set size cap
Blobs live on disk under FILES_PATH (same volume as the DB), named by
the row's ULID so user input never shapes a path; the note_file row
keeps only metadata. DB-blob storage rejected: multi-MB PDFs bloat
surrealkv's LSM tree and buffer whole in RAM on every read.
- POST/GET /notes/{id}/files, GET/DELETE /notes/{id}/files/{file_id};
owner-only through the owning note, staff included
- max_file_bytes in settings (1 KiB-25 MiB hard cap, default 5 MiB),
enforced on streamed bytes (413), inside the settings CAS guard;
option<int> so pre-field volumes boot without a backfill
- 10 files per note; deleting a note removes rows first, blobs after,
so a crash strands at worst an unreachable blob✨ feat(web)!: gate enrollment, exams, grading, roll call to studentsAhmet Kaan Gümüş · 32949bd
✨ feat(web)!: gate enrollment, exams, grading, roll call to students Only Role::Student may enroll, sit exams, be graded, or appear on a class roster; teachers and above run those, they never take part. The manager+ teacher-presence roll call is unchanged. Two enforcement layers: - Enroll-time: `enroll` rejects a non-student target (400). Enrollment is student membership -- the choke point the rest ride on. - Action-time: `ensure_student` guards the exam sit paths (start, room WS door, answer save; 403) and the grade + roll-call targets (400), checked against the live role -- a post-enroll promotion can't smuggle staff in, and a stale enrollment goes inert instead of active. The answer tail re-judges the role per save (`ensure_student_now`, beside the enrollment wall on the path REST and the exam room share), so a promotion mid-exam also cuts an already-open room socket -- the door check is never the last word for a connection that outlives the role. Passive reads (own attempt/result, question view, finish) stay ungated: a non-student has no attempt to read and finish only submits saved work. Event attendance stays open -- events are school-wide, not classes. Behavior change: a user can be both course creator and enrollee only across a demotion now (staff create, students enroll), so the catalog-dedup regression drives that overlap via set_role. Docs updated per the surfaces checklist (utoipa 400/403 + endpoint docs, lib.rs exams/courses tags + intro, README matrix/route table/prose). Adds regression tests: only_students_can_be_enrolled, promotion_out_of_student_freezes_the_seat, and (e2e, over a live socket) exam_room_promotion_mid_exam_closes_the_sheet.
✨ feat(web)!: paginate every list endpointAhmet Kaan Gümüş · f3d2b0a
✨ feat(web)!: paginate every list endpoint
Every array-returning GET now accepts `?limit=&offset=` and returns a
`{ items, total, limit, offset }` envelope instead of a bare array.
Paging is opt-in: omitting `limit` returns the full list (limit echoes
null), so callers that need the whole set — an exam's questions during a
sitting, roster/grade pickers — are never silently truncated. `total`
always carries the unpaged count, so a frontend can render "100 of 256"
and drive a pager without a second request.
Windowing is a slice over the already-ordered domain list (the domain
layer is untouched); endpoints that embed people run that join over the
page alone. `limit` must be 1..=500 and `offset` >= 0 (else 400); an
offset past the end yields an empty page, not an error.
Covers all 17 list GETs, including /courses/me, /work/me, /work/{user},
and /users/search — whose hard 10-row cap is dropped in favour of the
same paging. Not paged: /exams/{id}/attempt/{questions,answers}, the
marks & attendance report objects, /exams/{id}/live, and /settings.
Shared machinery lives in web::page (Page<T>, PageParams, paginate).
Docs updated across the OpenAPI spec (utoipa query params + Page_*
response schemas), the Swagger UI it feeds, and the README (a Paging
section plus a `· paged` tag on every list row).
BREAKING CHANGE: list endpoints return a pagination envelope, not a bare
JSON array — clients must read `.items`. /users/search no longer caps at
10 results.✅ test(exams): live monitor pushes changes on a held-open streamAhmet Kaan Gümüş · 9aca0b4
✅ test(exams): live monitor pushes changes on a held-open stream The split coverage proved each snapshot correct (one-shot /live) and the SSE wire format parseable (first streamed event), but never that a status *change* surfaces in a *later* event on one held-open connection — the exact contract a frontend EventSource leans on. Add an e2e test: teacher opens /live/stream, reads snapshot #1 (student in_progress, submitted 0), the student finishes, then a later event on the same connection must show submitted. Fails by timeout if the stream ever cached its first snapshot or stopped re-reading each tick. Plus a `next_matching_snapshot` SSE reader that frames events off the wire.
2026-07-14
✨ feat(exams)!: move weight off exams onto their kindAhmet Kaan Gümüş · 3681441
✨ feat(exams)!: move weight off exams onto their kind
Weighting is school policy, not per-exam data: each settings
exam_kinds entry is now {name, weight} (1-100, defaults all 1) and
mark reports resolve weights at read time, so editing a kind
reweights every exam of that kind at once; an exam keeping a
since-removed kind counts as 1.
BREAKING CHANGE: exams lose `weight` on the wire and in storage,
settings `exam_kinds` become objects. No data migration (pre-customer
clean break) — delete ./data/hezarfen.db and reboot.🐛 fix: bind room writes to their sitting, wall unenrolled sittersAhmet Kaan Gümüş · 3375565
🐛 fix: bind room writes to their sitting, wall unenrolled sitters Four bugs, each reproduced by a failing test first: - A stale exam room's answer/finish acted on the *latest* attempt, so a lingering socket from a finished sitting could scribble on — or instantly submit — a retake it never hosted, burning a limited sitting. Messages now refuse any sitting but the room's own. - The sitting's content endpoints (GET /attempt/questions, POST /attempt/answers) skipped the enrollment wall that guards the room door and the attempt start, so an unenrolled ex-student kept the question list and a writable answer sheet forever. Both are 403 now; finishing stays open, exactly like under a closed rejoin door. - PATCH /settings merged over a snapshot and wrote the whole row back, so concurrent edits of different fields silently reverted each other. Saves are compare-and-set against the merged-from snapshot now, re-merging on refusal (409 only when still contended). - Work-entry duration_ms overflowed i64 on absurd manager-corrected instants — a panic in debug, a wrapped negative in release, and a row that 500d every later read. The subtraction saturates now.
2026-07-13
🐛 fix(exams): stamp walk-outs per sitting, wipe retakes atomicallyAhmet Kaan Gümüş · 6eb0a28
🐛 fix(exams): stamp walk-outs per sitting, wipe retakes atomically Three bugs in the attempts/rejoin build, each a wrongful lockout or data loss once allow_rejoin is off: - A room's teardown stamped left_at on the *latest* attempt, so a stale socket from a finished sitting marked a fresh retake as left, locking the student out of a room they never entered. Rooms now bind to the sitting they were opened for: state frames and the walk-out stamp re-read that attempt by id, never "latest", so a superseded room announces its own terminal state and closes. - Closing one of two tabs counted as leaving while the student was still connected. ExamPresence (AppState) counts sockets per attempt; only the last socket out stamps the walk-out. - The retake answer-wipe ran before the attempt create, so a lost double-start race could delete answers freshly saved into the winner's sitting — or destroy a graded sheet with no retake ever created. Wipe + create now run in one transaction and a failed create rolls the wipe back. (SurrealDB counts BEGIN/COMMIT as response slots: the CREATE result is slot 2.) Regression tests: e2e rooms for the retake stamp and the second tab, domain tests for the atomic wipe and the lost race (verified red against the old ordering), presence unit test. README rejoin paragraph aligned with the per-sitting semantics.
✅ test(exams): open lifecycle, retake limits, rejoin doorAhmet Kaan Gümüş · d341bdf
✅ test(exams): open lifecycle, retake limits, rejoin door Integration: open exams sit anytime without a deadline, retakes wipe the sheet and respect a live-edited limit (0 = unlimited), open + duration_ms caps each sitting, sync retakes inside the window feed the monitor's attempt/attempts_used/left_at. E2E: walk-out stamps left_at and a closed rejoin door blocks re-entry and REST saves (finish stays allowed) until the teacher reopens it; open-mode room runs untimed and re-enters on attempt #2 with a blank sheet.
2026-07-12
✨ feat(authz): wall course reads behind enrollment and ownershipAhmet Kaan Gümüş · ed007d9
✨ feat(authz): wall course reads behind enrollment and ownership
Students could read any roster, roll call, and event attendance; any
teacher could read any exam's results, statistics, live monitor,
answer sheets, and answer key (correct included), plus full
marks/attendance reports of any user.
- can_view_course = enrolled | creator | manager+; the /courses and
/exams catalogs filter per caller (list_created, list_for_courses)
- course sub-reads (roster, results, statistics, live, questions,
answer sheets) require course-management rights
- roll-call and event rosters become teacher+ views; students keep
/attendance/me and /marks/me
- /marks/{user} and /attendance/{user} narrow to the courses the
caller manages; manager+ still sees the full report