Commits
2026-09-11
🧹 chore: split note/session/settings into domain/db/service layersAhmet Kaan Gümüş · efea304
🧹 chore: split note/session/settings into domain/db/service layers
Pilot wave of the three-layer split. All query execution for the three
domains now lives in src/db/{note,session,settings}.rs as free fns taking
db first; web handlers call service::<x>::* only; domain keeps pure types.
- service/settings.rs gains the PATCH workflow (apply) and SETTINGS_LOCK —
it spans a multi-call pair (retire names, CAS save, restore), so it is a
service lock, not a db lock. The service takes its own input records
(SettingsPatch/*Input) so wire DTOs stay in web and list validation keeps
its original order, including the try_kept grandfathering that needs the
stored list.
- Note/Session/Settings fields the db layer mints or CAS-binds become
pub(crate); Settings::record_id becomes pub(crate).
- Unit tests rode with their fns: note delete cascade → db/note, session
purge → db/session, settings load/save/CAS → db/settings, the whole
settings edit workflow suite → service/settings.
- Doc links re-pointed (user, class_blueprint, bank_question, exam,
note_file, tests/regress_roles); NoteId::generate's stale
'Note::list_for_user' link now names db::note::list_for.
- Known residual for a later wave: web/notes.rs:411 file.delete() is
note_file-domain persistence (note_file splits in C3).2026-09-08
🧪 fix: request-id bound reaches /limits; registry-read probe no longer depends on span threadAhmet Kaan Gümüş · 282db82
🧪 fix: request-id bound reaches /limits; registry-read probe no longer depends on span thread MAX_REQUEST_ID_LEN sat in src/lib.rs, so the one bound a client can actually hit on a header it sends reached neither GET /limits nor the OpenAPI spec. Moved to src/constant.rs, published as `request.max_request_id_len`, and added to README's /limits sample. probe_registry_reads_per_request counted SurrealDB spans through a thread-local subscriber (`set_default`). tracing caches a callsite's interest process-wide the first time any thread reaches it: under parallel tests that thread is a sibling with no subscriber, so the SDK's callsites were disabled for the whole process before the probe asked and it panicked UNMEASURED (0 in 7 of 8 runs against noisy siblings). It now installs a counting Subscriber globally, with `Interest::sometimes` and an `enabled` that admits only surrealdb callsites on its own thread, so it stores nothing and no sibling test lands in the figure.
2026-09-07
🔒 fix: telemetry privacy sweep, in-flight gauge guards, request-id validation, tenant gauge on createAhmet Kaan Gümüş · ae0957a
🔒 fix: telemetry privacy sweep, in-flight gauge guards, request-id validation, tenant gauge on create - No account name reaches an exported log record: the admin seed (domain/user.rs), the ADMIN_USERNAME refusal and the builder seed (domain/builder.rs) log the event without the `username` field. - The forbidden-key list moves to tests/common (`FORBIDDEN_TELEMETRY_KEYS`, `is_forbidden_key`), gains `username`/`email` and the header prefixes, and is used by both the HTTP-edge and the AI-bridge guard tests. The telemetry suite now also exports tracing EVENTS through an in-memory log exporter and holds log records to the same rule. - `http.server.active_requests` and `ai_requests_inflight` are closed by a `Drop` guard, so a dropped request future (client hang-up, outer timeout) no longer leaks the gauge upwards. A cancelled request is recorded as 499. - A caller-supplied `x-request-id` is only kept when it is at most 64 chars of `[A-Za-z0-9._-]`; anything else is dropped and a UUID is minted, so a client cannot write free text onto `http.request.id` of every span. - `tenant_cache_size` is reported by `Tenants::create` and by the bootstrap insert, not only by the lazy-dial path. - The keepalive logs its first `up` verdict, which its comment already claimed. Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s
✨ feat: AI bridge telemetry — request spans, worker gauges, handshake failure countersAhmet Kaan Gümüş · 405cf96
✨ feat: AI bridge telemetry — request spans, worker gauges, handshake failure counters The QUIC bridge was the one request path with no observability: an AI-originated api read takes the router before every layer, so it produced no span, no metrics and no request id, and a dispatch out to a worker produced only interpolated log lines. Outbound dispatch now opens an `ai.request` span (capability, worker id, school slug, request id) and records inflight, duration by capability, and the timeout counter; failures mark the span ERROR. The handshake counts every rejection under a fixed `reason` vocabulary — transport, timeout, no_control_stream, malformed_hello, bad_version, bad_token, bad_capabilities, welcome_failed — and the worker gauge is set from the registry on register and on disconnect. The inbound api read is wrapped in an `http.request` span and the same request metrics the HTTP edge records, keyed on the route *template* the allowlist matched (`ai::api::route_template`), never the concrete path. The peer address is gone from the bridge's log lines: those become OTLP logs, and telemetry names no client address. Nothing here carries a payload, a message, file bytes or a user id. Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s
✨ feat: real /health, error and panic telemetryAhmet Kaan Gümüş · c00f83a
✨ feat: real /health, error and panic telemetry
`/health` (and its `/` mirror) now answers what the process can actually do —
`{status, db, ai:{enabled,workers}}`, 200 when the database is up and 503 with
`"db":"down"` when it is not. It is exempt from the db guard alongside
`/limits`: a probe refused by the outage it exists to report names nothing.
Every `AppError` arm now records a stable snake_case class on the request span
(`error.type`) and counts itself into `errors_total` with that class and the
status. One log line per refusal, by severity: 5xx at error! with the
underlying error (which the arm's own Display hides), 429 and the reconnect
503 at warn!, the caller's 4xx at debug! — no path, no user, no body anywhere.
`record_response` no longer overwrites `error.type` with the status code.
Panics are no longer a dropped connection: a process-wide hook logs
`exception.type/message/stacktrace` and counts `panics_total`, and a
`CatchPanicLayer` inside the trace layer answers the same `{"error":"internal
server error"}` 500 every other internal error answers, tagging its span
`panic`.
Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s✨ 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: builder sells modules per school, one at a time or in batchesAhmet Kaan Gümüş · c78e41a
✨ feat: builder sells modules per school, one at a time or in batches
`GET|PATCH /schools/{slug}/modules`, `POST|DELETE /schools/{slug}/modules/{module}`;
a batch names modules or whole packages, resolves to one set, is validated
against the dependency graph once and written once, or not at all. Public
`GET /modules/catalog` lists modules, packages and requirements; a school
reads its own set at `GET /modules`. Schools can be created with a narrowed
set.✨ 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.
📝 docs: multi-school model in the README, builder seed in composeAhmet Kaan Gümüş · 78fe8c7
📝 docs: multi-school model in the README, builder seed in compose New `## Multi-school (SaaS)` section; the auth prose, quick tour, first-admin bootstrap and layout follow the per-school databases and the builder API.
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.
🔀 chore: merge main (term archive) into rag/output; rag deletes respect an archived termAhmet Kaan Gümüş · b8069dc
🔀 chore: merge main (term archive) into rag/output; rag deletes respect an archived term
Conflict in course_notes.rs delete_one resolved as require_open → rag cascade → note delete. DELETE /course-notes/{id}/rag/{output_id} now answers 409 on an archived term like the other course-note writes.🗄️ 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.
✨ feat: course-note file bytes stream to AI services over QUICAhmet Kaan Gümüş · 6d3456a
✨ feat: course-note file bytes stream to AI services over QUIC
A service opens a client-initiated bidi stream and writes one
`BlobRequest {id, file, on_behalf_of?}` — told apart from an `ApiRequest`
by its required `file` (vs `path`), api read tried first so every frame
that parsed before still does. The backend answers one header frame
`BlobResponse` tagged by `status`: `ok {id, name, content_type, size}`
then exactly `size` RAW bytes (streamed off disk, no length prefix, the
8 MiB frame cap does not apply) then FIN; or `err {id, code, message}`
followed by nothing.
Authorization is the api-read principal model plus the very guard
`download_file` carries: `on_behalf_of` re-read live, then the file's
note and that note's course through `can_view_course`. Scope is
`course_note_file` only, so a personal note's file id reads `not_found`.
Codes: `not_found`, `forbidden`, `unknown_user`, `unavailable`.
`RagIndexPayload` gains `author` so a service knows who to read as.
Ref #27✨ feat: course-note RAG outputs readable and deletable over HTTPAhmet Kaan Gümüş · b91417d
✨ feat: course-note RAG outputs readable and deletable over HTTP
Part 1 stored what the `rag.index` service produces for a course note but
nothing could read it. Add `GET /course-notes/{id}/rag` (paged, open to
anyone who can view the course) and `DELETE /course-notes/{id}/rag/{output_id}`
(teacher+ with management rights, 204), the delete scoped to the note in the
path so a sibling note's output is a 404 rather than a cross-note delete.
Outputs stay derived data: deleting one suppresses nothing, the next note or
file change may regenerate it.
Ref #27✨ feat: course-notes readable by AI services over api-readAhmet Kaan Gümüş · 001c898
✨ feat: course-notes readable by AI services over api-read
The RAG service answers about lessons, so it needs the teacher's own
course material — until now the api-read allowlist stopped at personal
notes, leaving /course-notes unreachable to every service.
Adds /course-notes, /course-notes/{id} and /course-notes/{id}/files to
AI_API_ALLOWLIST (the read scope in README and the `ai` tag follow).
The blob route /course-notes/{id}/files/{file_id} stays out: frames
carry JSON under an 8 MiB cap. Reads are still GET-only and run with
the on_behalf_of student's own reach — a course they are not enrolled
in answers 403 from the handler, not from the bridge.
Ref #272026-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-13
📝 feat: generate README endpoint table from the served OpenAPI specAhmet Kaan Gümüş · bf8046e
📝 feat: generate README endpoint table from the served OpenAPI spec tests/doc_sync.rs renders the 275-row table from /api-docs/openapi.json (auth floor from declared 403s, else the handler's Require* extractor, asserting exactly one floor per operation), drift-gated in the suite; UPDATE_DOCS=1 regenerates. Static rows are router-verified and plain .route() registrations must reach the table or the suite fails. Curated prose folded into handler doc comments; CLAUDE.md convention updated (table generated; full suite = cargo nextest run).
2026-08-12
🤖 feat: let ai services read the api over quicAhmet Kaan Gümüş · b0af858
🤖 feat: let ai services read the api over quic A service now opens a bidirectional stream of its own, writes one ApiRequest and reads one ApiResponse: the bridge validates it and dispatches it into the real router, so a service asks for school data over the same handlers the REST API serves instead of getting a second copy of them. The router is handed over *before* the outer layers, because a synthetic QUIC request is not a browser request from an IP: it has no address to bill the per-IP limiter (it would drain the shared unknown-client budget), and ETag/CORS are browser concerns. That skips the db guard too, so this path runs the same liveness check and REQUEST_TIMEOUT_SECS deadline itself. Validation order is pinned, since it decides what is refused before the router ever sees it: method (absent or GET) → the AI_API_ALLOWLIST path → the principal, loaded live from the database so a stale id cannot act as a deleted user. Anything the router itself answered — 401, 403, 404 included — rides back as Ok with that status; the Err codes are bridge-level refusals only: malformed, method_not_allowed, path_not_allowed, unknown_user, unavailable, not_json, too_large. The control-stream handshake and the backend→service dispatch are untouched, and a service that never opens a second stream sees no difference at all.
2026-08-05
🖍️ fix: close a whiteboard whose creator was demotedAhmet Kaan Gümüş · 26e7470
🖍️ fix: close a whiteboard whose creator was demoted A board's creator demoted to `parent` left a room nobody could command. The whiteboard is shut to that role outright, so the creator was answered 404 on their own board; clear, lock, close and delete are the creator's alone, so every other participant was answered 403; and `Board::list_for_user` is the crate's only enumeration, so no manager or admin could so much as find the id. Meanwhile the participants kept drawing (the room re-derives membership per frame and they still pass) into a board only the 50 000-stroke lifetime cap could ever retire — and `Board::delete`, the sole releaser of `board_count` and the sole deleter of `board_stroke`, was unreachable forever. The demotion now stamps `closed_at` on every board the account created, in `set_role`'s own transaction and with the same compare-and-set `Board::close` uses, so an already-closed board keeps its first stamp. Written before the roster strip, so the strip's `RETURN AFTER` carries the closed row the caller fans out — as a `closed` frame beside the `participants` one, which is what turns the open sockets read-only. Closed and not deleted: the marks are the other participants' work too, so the board, its history and its epochs stay readable and only writes are refused (`board_closed`, terminal). The cost is accepted — the creator's `board_count` seat stays taken, which is correct while the row it counts still exists, and the strokes stay on disk. The concurrent half needs nothing: `Board::create` claims the creator's own user row (`cap::claim_and_create` on `board_count`), the very record this transaction writes `role` on, so a board opened while the demotion runs collides in the store and one side re-sends — it cannot slip past the sweep.
📝 fix: stop a demotion confiscating the owner's own notesAhmet Kaan Gümüş · 528403a
📝 fix: stop a demotion confiscating the owner's own notes Every note and note-file route required `student`, on top of a query already scoped to the owner. A demotion to `parent` therefore locked the account out of its own notes: `GET /notes`, `PATCH`, `DELETE` and all four file routes answered 403 to the owner. Nothing else in the crate reads a note, `set_role` has no note arm and no route cascades one, so the `note` rows, the `note_file` rows and their on-disk blobs were left reachable and deletable by nobody, forever — with no per-user note cap to bound the pile. Notes are purely personal, own-scoped data: no school content, no second reader. A role change must not confiscate them, so the role bar drops to `CurrentUser` and the owner scoping that was always underneath it is now the whole authorization. Nobody but the owner reaches a note or its files; a stranger's id stays a 404, exactly as before. The note-file routes were already safe to widen — every one of them re-derives the owner by reading the note first and only then resolves the file under that note, so a file is never reachable by id alone. The utoipa 403s on the nine routes go with the bar (there is no 403 left to answer), and the `notes` tag plus the README intro, roles section, permission matrix and route table now say ownership rather than role.
👤 fix: show a person under the name they chose, everywhereAhmet Kaan Gümüş · 4e4a808
👤 fix: show a person under the name they chose, everywhere
`PersonRef::new` built `display_name` from `name` + `surname` only and never
read the stored `display_name`, so anybody who chose one was still rendered
under their legal name by every route that embeds a person — messages,
`/users/search`, course creator/teachers, rosters, exam results, appointments,
meals, payments, the question pool. Meanwhile `GET /users/{id}/profile` served
the chosen name, and `GET /users/{id}` is admin-only, so the profile was the
one surface telling the truth.
The rule was written twice: `ProfileResponse` did the three documented steps
(stored, else the join, else null) and borrowed only the join half from
`PersonRef`, which had the other half missing. Two hand-kept copies of one
documented rule is how it drifted, so the resolve now lives once, in
`PersonRef::new`; the profile calls it whole. The test that was missing is the
one that fails on drift: a display name differing from the join, asserted on a
`PersonRef` route and against the profile's own answer, at all three steps.
Second, unrelated to the resolve but on the same doc: `profile_of` claimed only
`stats.courses` and `stats.classes` cross a gate the reader would fail. Eight
more do — `pomodoro_focus_ms`, `pomodoro_focus_ms_total`,
`lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`,
`exam_sat_total`, `high_mark_total` mirror data behind `ensure_can_observe`,
and for an exactly-teacher reader they are wider than the reports themselves.
The disclosure stays (motivational counters, no object named); the comment,
the schema description, the tag and the README now say so accurately.🔒 fix: stop the review gate answering for an exam the caller cannot seeAhmet Kaan Gümüş · 73eb272
🔒 fix: stop the review gate answering for an exam the caller cannot see
`reviewable_exam` read `allow_review` before it had established the caller
has anything to review, so `GET /exams/{id}/review/*` answered 403 iff the
exam existed, was published, and had review off — and 404 otherwise. Any
authenticated caller, an unenrolled student or a parent, could read a flag
`GET /exams/{id}` refuses them outright (`can_view_course` answers 403 there
before `allow_review` is ever serialised).
The mark check moves ahead of the flag: an outsider now reads 404 whichever
way the flag is set, and only a caller the exam already marked — enrolled or
since dropped, who therefore sat it — ever sees the 403. Nothing is loosened;
the answer only gets narrower, and the 409 gates behind it are untouched.
Also documents, and pins with a test, the staff identity `GET
/appointments/slots` hands a parent: deliberate, since a conference cannot be
booked off an anonymous calendar.⏱️ fix: stop a start/finish loop buying the pomodoro badgesAhmet Kaan Gümüş · 37ee719
⏱️ fix: stop a start/finish loop buying the pomodoro badges
`PomodoroSession::finish` moved `pomodoro_finished_total` (and the focus-ms
total, and the study streak) once per call, with no minimum duration and no
per-day cap. Finishing is self-service: a stint is two requests, no second
person and no elapsed time, so 200 `POST /pomodoro` + `POST /pomodoro/finish`
pairs — about ninety seconds inside the 300/min default — drove the counter to
200 and minted `pomodoro_finished_10`, `_50` and `_200`. Those awards are
irrevocable: nothing anywhere deletes a `badge_award` row, and no route deletes
a `pomodoro_session`, so the phantom stints stood in the profile forever too.
This is the farm `PoolQuestion::approve` already reasons about from the other
end ("a bare insert is self-service … so a counter moved there is farmable");
`pomodoro_finished` was the one badge counter that rule was never applied to.
A stint now counts only if it ran at least `MIN_COUNTED_POMODORO_MS` (5 min)
and is within that UTC day's `MAX_COUNTED_POMODORO_PER_DAY` (16). Five minutes
is well under a conventional 25-minute pomodoro on purpose — a student who
breaks off early still focused, and the counter must not punish that — while
sitting four orders of magnitude above a scripted round-trip, which is the only
distance that matters: the cheat now costs the wall clock it claims. Sixteen a
day is above any honest school day (sixteen full pomodoros is over six hours of
pure focus) and caps the minimum-length farm at eighty minutes of real waiting
per day, so `pomodoro_finished_200` takes at least thirteen calendar days to buy
instead of ninety seconds. Both boundaries are inclusive on the counting side:
exactly the minimum counts, and the sixteenth of the day counts.
The verdict rides the same transaction that closes the stint (no read-then-
write) and is **stamped** on the row as `counted`, not re-derived: thresholds
are compiled in and will move, and any future debit must read the same value
the credit did. The day bucket (`pomodoro_counted_day` / `_today`, midnight UTC
via `Timestamp::day_number`) rolls in its own statement ahead of the verdict,
reading the day column it also sets — the pre-statement resolution rule that
already forces the streak pair apart. Both new user columns and the session's
`counted` are `option<>`, so no backfill is owed. A stint below the bar is
still recorded, still listed and still in `total_focus_ms`: the rule bounds
what counts, never what is kept.
Stale data: none to repair (the live volume carries no non-zero profile
counters), and an inflated counter could not be repaired anyway — lowering it
does not take back the badges it bought.
Tests: the farm repro (200 pairs move nothing and mint no badge), both sides of
the minimum, the day quota and its midnight-UTC roll, and the streak suite
re-pinned on stints that count. Mutation-proved: neutralising the two
thresholds turns four of them red, the farm one at (200, 132).🥗 fix: stop the canteen billing meals that were already servedAhmet Kaan Gümüş · 0894a5e
🥗 fix: stop the canteen billing meals that were already served
A menu dated 2020 was publishable, bookable and BILLABLE under the shipped
defaults. `check_cutoff` was the only gate a booking passed, and it returns
early twice: with `meal_cancel_cutoff_minutes` unset (the default) and with a
slot carrying no `serving_minute` (the default for all three shipped slots).
`POST /meals/menus` was also the one create path in the crate with no
`check_not_past`. So a manager published `2020-01-01_lunch`, a student booked
it, and `MealLedger::charge_for` wrote a real, permanent charge line for food
nobody could be served.
Both halves, because the create-side check alone does not close it: a menu
published legitimately last week, for a day that has SINCE passed, stays on
the volume and stays addressable. `check_not_past("date", date.day_end())`
refuses publishing a day already over (400, measured against the end of the
day so today publishes at any hour), and `check_day_not_past` refuses a
booking on one (409).
That guard is deliberately NOT part of `check_cutoff` and takes no settings:
the cutoff is policy about the serving *hour* and is unenforced by design when
the school has set none — the decision that keeps the canteen online — while
this is the calendar day itself being over, which no configuration makes
untrue. Today's menu on a slot with no serving hour books exactly as before.
It binds `book` alone: cancelling stays open on a past day, since a cancel
reverses a charge and money already taken has to stay reachable — the same
reason manager+ bypasses the cutoff. Nothing bypasses the past-day guard, and
nothing needs to: only students and their parents book at all.
`MenuDate::try_new` also stops disagreeing with chrono. `"+1".parse::<u32>()`
is `Ok(1)`, so `2026-+1-01` passed the calendar-day check and minted a SECOND
record id for the 1st of January — its own capacity and seat counter, missing
from every `?from=&to=` read (`+` sorts below `0`) and unbookable besides,
since the serving-instant parser could not read it back. The date is now
parsed by chrono and compared to the text it came from, so the two parsers
agree by construction rather than by two checks that can drift.
Test dates in the meal suites move beyond the calendar (2026-09 → 2099-09):
under the new rule a fixture dated next month is a suite that expires. The two
tests that used a past date as a shortcut to "the cutoff has closed" now reach
the cutoff the way a deployment does — today's menu, served at 00:00 UTC, with
the knob set.
Live volume: zero menus, zero bookings, zero ledger lines, so no residue to
repair. The defect was future-affecting only.🖍️ fix: tell a closed board's room it is closed, not pausedAhmet Kaan Gümüş · fcaf9ca
🖍️ fix: tell a closed board's room it is closed, not paused
A board can hold `locked` and `closed_at` at once — `set_locked` carries no
`WHERE closed_at = NONE` and `close` carries no lock test, so lock→close and
close→lock both land — and the module's two refusal classifiers disagreed
about that state. A stroke re-read the board and tested the lock first, so
`why_refused` answered BOARD_LOCKED ("the creator has paused drawing") for a
permanently read-only board; a clear tested `closed_at` first and answered
BOARD_CLOSED for the same board. Over the socket that is `locked` vs
`board_closed`, and the room is told to wait for a pause that can never lift:
there is no reopen route, and `close` is a one-way CAS.
Closed outranks locked, and the precedence now lives in one place —
`state_refusal` — that both classifiers read, rather than in two hand-kept
chains of the kind that drifted here. The clear path keeps its identity
check between the terminal answer and the pause, so a non-creator still gets
the `403` and a closed board still answers everyone the same.
`set_locked` is deliberately left ungated: locking a closed board is a no-op
on something already read-only, and refusing it would break the second half
of a close-then-lock a client may legitimately send in either order.🎯 fix: stop a corrected mark leaving a high mark nothing can take backAhmet Kaan Gümüş · c1a0c3b
🎯 fix: stop a corrected mark leaving a high mark nothing can take back The credit and the refund on `high_mark_total` read different values. The credit was decided in Rust from the *incoming* mark and buried on the first-write branch, so a regrade of the same sitting moved it never; the refund reads the mark actually *stored* on the deleted row. A sitting graded 95 and corrected to 40 therefore kept a credit the delete could not find — grade high, regrade low, delete, repeat, and the counter climbed without bound off one exam, minting `high_mark_10` and `high_mark_25` permanently, since an award is never revoked. It cut the other way too: a genuine 95 on one exam was eaten by a second exam graded low, regraded high and deleted, whose refund found a stored high mark it had never been credited for. Fixed as a delta rather than a stamp on the row. `$before` already had to be read inside the transaction to decide the claim branch, so reading the sitting's previous *mark* there instead of its id costs nothing and needs no new column and no backfill — `HIGH_MARK_MIN` is a threshold on a value the row already stores, so a stamp would only duplicate it. The counter then moves by the difference between the two sides of the line: +1 crossing up, -1 crossing down, nothing when both marks sit on the same side, which keeps an ordinary correction off the student's row entirely as before. Credit and refund now read the same value, and the counter can no longer exceed the number of stored marks at or above the cut. Both regrade directions, a correction above the line, the inflate loop and the cross-exam theft are pinned in `exam_result`'s tests; all five go red against the old shape. The integration pin that asserted a regrade must not move the counter asserted the defect — it contradicted both the README and the refund — and now asserts the crossing.
📚 docs: move the doc surfaces these fixes changedAhmet Kaan Gümüş · c62e54a
📚 docs: move the doc surfaces these fixes changed utoipa annotations, lib.rs tag descriptions and README (intro, route table and the relevant sections) for everything this sweep changed: the review gate's new 409, the narrowed homework roster, the canteen's authorise-before-lookup and cutoff rules, the payments ceilings, the last-admin floor and the live-role filter on the student lists. /limits gains payment.max_assign_writes, payment.max_applied_lines and meal.max_booking_attempts.
docs: 📝 make six doc surfaces say what the code now doesAhmet Kaan Gümüş · 2e0b57a
docs: 📝 make six doc surfaces say what the code now does The batch that gated `lessons_held_total` on the lesson having started, made un-grading refund both counters, taught `Course::delete` to prune blueprints, held both meal date bounds to the calendar and turned a half-configured TLS pair into a boot error moved only README. The utoipa annotations and the tag descriptions still carried the old rules, and one README bullet list stated two opposite decrement rules 24 lines apart.
fix: 🍽️ make a meal credit retry-safe on requestAhmet Kaan Gümüş · 4fe4487
fix: 🍽️ make a meal credit retry-safe on request `POST /meals/credits` minted a fresh ulid per call, so the ledger's identity-based idempotence — the rule that keeps a double-clicked booking from billing twice — could never bite here. A response lost after the commit (proxy timeout, closed tab) left the client resending the identical body, and the money was taken a second time with no route able to edit or delete either line. It now takes the optional `request_key` its twin `POST /payments/credits` already takes, same validator and same grammar, folded into the line's id as `<student>_k_<key>`. The student is part of the id, so a key cannot reach another account; the same key for a different amount is a 409, checked on what the append gave back rather than on a read before it, so two retries racing get the same answer. Omitting the key keeps the old behaviour: two identical posts are two credits. Also carries the rustfmt reflow of the cancel-fence test added earlier.
fix: 🍽️ give a menu on an impossible day a cutoffAhmet Kaan Gümüş · 5fdba75
fix: 🍽️ give a menu on an impossible day a cutoff `MenuDate` accepted any month 1..=12 and day 1..=31 on the grounds that a 31st of February is a typo nobody can act on. It is not: the menu is publishable and fully actionable — seats, charges, dishes, attendance marks — while `served_at` cannot parse the day, so `check_cutoff` found no serving instant and passed. Every booking and cancel on it skipped the deadline, for students and parents alike, however large `meal_cancel_cutoff_minutes` was. Both halves: the date must now be a real calendar day (leap years included), and a serving instant that cannot be computed fails closed instead of opening the deadline — which is what the rows already stored on a live volume run into, since validation cannot reach them. A school with no cutoff configured closes nothing either way.
fix: 🍽️ stop a cancel from freeing a seat it never readAhmet Kaan Gümüş · bd941b9
fix: 🍽️ stop a cancel from freeing a seat it never read `release_seat` flipped on `status = 'booked'` alone, while the revival on the book side fences on the attempt. A cancel that read attempt N and spent a round trip re-reading the menu could therefore flip attempt N+1: a seat a `POST` had just been answered `201` for was cancelled, its capacity handed back, and nothing refunded — the ids bound to that transaction are N's, whose reversal already exists — leaving the newer charge standing with its own `(booking, N+1)` reversal id unwritable by any route. The flip now carries `AND attempt = $attempt`, and a cancel that finds the seat booked again answers 409 rather than 200 with a `booked` row: the newer seat is one nobody on this request asked to free.
docs: 📝 stop the chatbot tag documenting a retired claim queueAhmet Kaan Gümüş · a48a457
docs: 📝 stop the chatbot tag documenting a retired claim queue The emitted OpenAPI still promised that a pending row is a claimed job picked up by whichever process holds a `chat.reply` worker, that a restart no longer strands an accepted turn, and that an unfinished claim is retried after 90 seconds. The code is the opposite: the round trip runs in a task the 202 leaves behind, and `claimed_by`/`claimed_at` were dropped from the schema. README.md was already correct; only the spec lied, and it is the surface a client reads. The tag now says what happens — an orphaned turn settles `failed`/`interrupted` by projection or by the boot sweep, accepted because there is no peer to take it over — and records the serialization a turn now has against its thread's deletion.
fix: 💳 stop telling a bursar a reversed charge was paidAhmet Kaan Gümüş · 26a740d
fix: 💳 stop telling a bursar a reversed charge was paid A reversal is a `+amount` child of the line it undoes, so it fills exactly the room a payment would: `applied_to` folds it in and a reversed charge reads as full to the last minor unit. `POST /payments/credits` against one therefore answered "the charge is already paid in full" — about a charge where not one minor unit ever arrived. It was reversed, and a bursar reading that goes hunting for money that does not exist. The stored outcome is right and does not move: a reversed charge is no longer owed and takes no payment. Only the diagnostic changes. The reversal's id is derived from its target's, so telling the two refusals apart is one read, taken on the refusal path alone. `refund` passes `None` and spends no read: a credit is never reversed, so a full fold there can only mean the refunds. Doc surfaces move with it: the route's 409, its handler doc, the `payments` tag description, and the README route table and section.
fix: 📅 stop offering a slot booking will refuseAhmet Kaan Gümüş · 2202807
fix: 📅 stop offering a slot booking will refuse `GET /appointments/slots` listed every slot whose `ends_at` was still ahead, but `Appointment::book` refuses any slot whose `starts_at` has passed. The two windows disagreed, so a slot already underway sat on the student's bookable calendar as an entry that could only answer 409 — either published inside `check_not_past`'s 60-second grace, or simply started while the page was open. The listing moves to `book`'s bound: `starts_at > $from`. `book`'s rule is the real constraint, so the calendar stops advertising what booking refuses rather than booking loosening to match. The 60-second publish skew grace deliberately does not reach the listing either — `book` does not grant it, and a slot published a moment after its own start is unbookable from birth. Two source claims were false and are corrected with it: `book`'s comment said `list_upcoming` hid these slots, and the route doc called them "every slot still open in the future".
fix: 🏫 stop a deleted course from sticking in a blueprintAhmet Kaan Gümüş · b0f72a5
fix: 🏫 stop a deleted course from sticking in a blueprint A grade template holds its courses as a list on its own row, so nothing in `Course::delete`'s cascade could reach it: the id stayed, and the repair every doc surface named — `PATCH` the template back as it stands — is a 400 for naming a course that does not exist. The pump's own prune only fires while walking a section, so at a grade with no sections the id was permanent. The cascade now sweeps `class_blueprint` in the same transaction that detaches the course from the sections. Table scan, deliberately unindexed: one row per grade label, and a course delete is rare — and the per-element index the WHERE would want (`FIELDS courses[*]`) is the one this store answers with no rows at all. `prune` stays for the window the sweep cannot cover (a course deleted after a pump read the list it walks) and for ids written before this existed; its comment no longer argues the sweep should not exist.
2026-08-04
fix: 🧭 name the ceiling a class refusal actually hitAhmet Kaan Gümüş · 82c0ee2
fix: 🧭 name the ceiling a class refusal actually hit The refusal codes shipped one commit ago read the same on both axes, but two of them mean opposite things depending on which side is being attached: a class at its ceiling is out of course places when a course arrives and out of seats when a student does. So adding a student to a full section answered class_at_course_ceiling next to a sentence about students, and a section carrying too many courses answered class_roster_too_large. The two tests covering it pinned the wrong answer, one of them while asserting the prose was right. The ceiling codes now live on the axis, so each names what it hit, and the member route gains the two it needed. Its documentation was wrong in the other direction too: it derived the manual code set from the pump's, which quietly promised codes only a pump can answer — a deleted class or course is a 404 there, never a 409. Each route now states its own set, and the spec guard compares those sets rather than searching the whole document for the strings, which is why it never caught any of this.
feat: 🏷️ answer a manual class refusal with the pump's own codeAhmet Kaan Gümüş · 574b977
feat: 🏷️ answer a manual class refusal with the pump's own code Attaching a course or adding a member by hand refused with an English sentence, while the very same conditions reached through a blueprint pump had just become machine codes. One cause, two shapes — and the client that has to word them is bilingual. The vocabulary now has one home on the pump's own refusal type, the blueprint's skip list reads it from there, and the two manual routes carry it as a code beside the sentence they already sent. Prose is unchanged and no other route gains the field. Coding these also exposed a claim this series had been making wrongly: a pump attaches a course it has just proved alive, so it can never report a stale link. Only a member add walks the section's existing courses, and only it can answer that one.
feat: 🩺 say which sections are out of step with their blueprintAhmet Kaan Gümüş · 0684656
feat: 🩺 say which sections are out of step with their blueprint A pump is best-effort, so it can leave a grade half stocked — and the skip list saying which half lived in one response body and nowhere else. A manager who closed the tab had no way back to it. The status read answers it from the store: the template, how many sections carry the label, and what each section is missing. A course attached by hand counts as present, because that is exactly what the pump does with it. It also writes down the recovery nobody had been told: re-sending the same list re-runs the pump, and a section can be re-stocked on its own. A class moved to another grade keeps what the old template gave it — which this read now shows rather than leaving to be discovered.
feat: 🔍 filter the class index by gradeAhmet Kaan Gümüş · cf0a010
feat: 🔍 filter the class index by grade A blueprint keys on a grade label and its pump is best-effort, so a manager can be handed a skip list naming three sections at grade 9 — and had no way to list the sections at grade 9. The label the office typed is the only thing tying them together, and nothing read it. Matched verbatim, like the pump it exists to debug: a filter that trimmed or folded would disagree with the thing it is meant to explain. An empty value asks for the sections carrying no grade at all, which is what an empty grade already means everywhere a class is written.
feat: 🏗️ stock a new section from its grade's blueprintAhmet Kaan Gümüş · 67ced09
feat: 🏗️ stock a new section from its grade's blueprint Editing a template reached every section already at the grade, but making a section reached no template — so a blueprint described every section except the ones created after it, and the office had to remember a second call each time. A create now applies its grade's blueprint, after the homeroom demotion rollback and never before it: the rollback deletes the class, and that delete refuses while the class holds courses. The 201 body carries the class, what could not be stocked, and which grade's template stocked it — null when none covers the grade, which is also what a stocking that faulted reports, because a 500 here would strand a section whose id nothing else returns.
feat: 📊 say how many sections a blueprint pump reachedAhmet Kaan Gümüş · 81c5490
feat: 📊 say how many sections a blueprint pump reached A grade label is free text and matched exactly, so a section typed "9 " carries a grade no blueprint for "9" will ever find. The pump answered that with an empty skip list, which reads exactly like every section having taken the whole template. It now says how many sections it walked, so nothing reached is a zero a manager can see rather than a silence. Normalising the label was the other way out and is not taken: the label is the blueprint's own record id, schools spell their ladders differently on purpose, and nothing would repair the labels already stored.
fix: 🔒 stop a deleted blueprint from stranding the rows it taggedAhmet Kaan Gümüş · b1c8e7a
fix: 🔒 stop a deleted blueprint from stranding the rows it tagged Delete swept the course list the handler had read and then removed the row, so a pump adding a course in between left class_course rows tagged with a blueprint that no longer existed — reachable by nothing, since the sweep is the only thing that reads the tag. Delete now takes a compare-and-set on that list, removes the row first and only then sweeps by the tag itself, so a racing addition is swept too; the pump answers blueprint_deleted rather than landing an orphan, claiming the blueprint inside its own transaction; and BLUEPRINT_LOCK closes what neither could, since SurrealDB does not serialise the pump's cross-record read against this delete. The residue is a process crash between the delete and the sweep, which no lock survives: inert rows, a detach each, counters exact. The pump's created-row slot was hand-counted (7, or 9 on an axis with a pivot claim). The guard would have shifted it silently on the only path that uses the guard, so the statement list is built as a list and the slot is read off its length.