forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on ebffd41acbeb31d10b21d6eeb70a9dbaaaa29b10Filtered to src/lib.rsClear filter

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: announce an exam to sibling instances (shared-exam write surface)Ahmet Kaan Gümüş · 1824c34
✨ feat: announce an exam to sibling instances (shared-exam write surface)

b3f7395 gave `exam_audience` a read role; this gives it its writes. An exam
is owned by the instance it was created on and can now be addressed to
further instances — one sitting, one mark, standing in every addressed
section's exam list, marks report and the report card.

- `POST /exams/{id}/audience` announces the exam to another instance: the
  target must teach the exam's own catalog course and sit under the same
  academic year (400 otherwise), the owner itself is refused (400), an
  archived target year is a 409, and a repeat announce is a no-op 200.
  The write needs management rights over the exam's **owner** instance —
  the target instance's teachers have no say.
- `GET /exams/{id}/audience` lists the set (owner first, then announcement
  order), visible exactly as the exam is; drafts stay a 404 to everyone but
  an addressed instance's manager. `DELETE /exams/{id}/audience/{instance}`
  withdraws one; the owner's pair is not withdrawable (400) and a pair that
  holds no row is a 404.
- Grading, statistics, results and the live monitor now accept teacher+
  rights over any instance the exam is addressed to, so an announced-to
  section's teacher grades its own students; the monitor's roster read is
  deduped by student and ordered, so a sitter in two addressed sections
  appears once.
- `sweep_instance_subtree` clears both directions of `exam_audience` before
  the rows they name — an exam a sibling announced *here* referenced the
  `class_course` row the caller deletes and refused the delete with a 23503.

Tests: regress_exam_delete.rs pins the announce/withdraw surface end to end
(owner-first order, the same-year and same-course 400s, the 409, the no-op)
and the sweep's answer-image blobs — the drawing row's bytes land on disk
and are gone with the row, with a mutation witness.

Gates: prepare_db, SQLX_OFFLINE=true check --all-targets (cache: 1 dropped,
7 added, all audience-shaped), doc_sync, spec_bounds, limits_completeness,
clippy -D warnings all green; cargo nextest run 1385/1385 across 47 binaries.
✨ 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.
✨ feat: an admin mints a school account directlyAhmet Kaan Gümüş · 57de5b3
✨ feat: an admin mints a school account directly

POST /users creates the person plus the school's app_user in one call, born
with the role the caller names (student by default) — no self-registration
and no register-then-promote two-step. Reuses the register credential rules:
a username new everywhere mints the person, an existing person attaches only
when the password matches (409 otherwise), a name already taken in the school
is a 409, and the reserved staff-reading names are a 400.

2026-09-15

🆔 fix: one id convention — every id is a v7 uuid, none is a v4Ahmet Kaan Gümüş · d40e4c9
🆔 fix: one id convention — every id is a v7 uuid, none is a v4

The crate mints UUIDv7 from the process-wide monotonic generator, but four
sites still minted a v4:

- ChoiceId (an exam choice's stable id) and the blob names of answer
  images, bank-question images and homework files: now next_uuid(), like
  their siblings (question_image already was)
- test_suffix()'s 5-hex tail is not an id — it is the random half of a test
  database's name — so it draws from the OS rng: a v7's leading hex digits
  *are* the mint time, which is exactly what two processes minting in the
  same millisecond share
- the request-id layer installed tower-http's MakeRequestUuid (a v4); it
  now mints through the crate's own generator, same wire shape

The manifest drops uuid's v4 feature, and a guard test scans src/ so a
stray v4 fails the suite. (tower-http's request-id feature still enables
uuid/v4 in the dependency graph; nothing here calls it.)
🐛 fix: a school's registry row and its database are never one writeAhmet Kaan Gümüş · 8e58afe
🐛 fix: a school's registry row and its database are never one write

Three consequences of that one fact — partial states the code could leave
behind and nothing could repair.

**A school is `provisioning` until its schema exists** (new control
migration). The row commits before the database does (`CREATE DATABASE` cannot
join that transaction), so a boot cut short in between used to advertise a
school that answered every request with a `500`; the next boot's
`reconcile_provisioning` now finishes it. While it is being made, the school's
own doors refuse it (`403`) and the two builder routes that need its database
(`enter`, `admin-password`) answer `409` instead of a table-less 500.
`provisioning` is the boot's word alone — the PATCH parser still refuses it,
and a client can never ask for it.

**`Tenants::drop` dropped the database last**, after destroying the memberships
and the entitlements: a transient failure left a school that still stood with
every one of its people locked out and nothing able to put them back. The
database goes first (it is the half that can fail on its own — `DROP DATABASE`
cannot join a transaction either) and everything after it is one transaction,
so a failure leaves "database gone, registry rows intact", which re-running the
same call completes.

**`PATCH /schools/{slug}` wrote name and status as two statements**; a failure
between them left half a patch. Both fields are one statement now, with
`COALESCE` over the row being written — an omitted field keeps its stored value
and a concurrent patch of the other field cannot be reverted.

Local: cargo nextest run --no-fail-fast → 1375 passed. clippy clean.
Live: a seeded `provisioning` row comes back `active` with a 70-table database
and the boot logs the finish; lifecycle probe 200/400/201/204 on the running
server; 8-boot template race 8/8 up, 0 refusals; 4-boot race on a fresh control
database 4/4 up.

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.
🗃️ feat: VPS deploy workflow + exe-relative migrations + CORS anywhere modeAhmet Kaan Gümüş · b2780eb
🗃️ feat: VPS deploy workflow + exe-relative migrations + CORS anywhere mode

- .github/workflows/main.yml: im-style deploy on push to main — pinned
  ubuntu-24.04 runner, Postgres sidecar (max_connections=500) for the
  per-test-database suite, clippy -D warnings + full nextest gate,
  --release build under SQLX_OFFLINE, SSH release-dir swap + systemd user
  unit restart, /health gated on THIS build's process (MainPID exe) with
  rollback, independent after-the-fact verify.
- deploy/hezarfen.service: the shipped user unit; secrets and deployment
  knobs live in ~/hezarfen/hezarfen.env on the server (never in-repo).
- migrations_path: fall back to migrations/ beside the executable when the
  compile-time CARGO_MANIFEST_DIR path is absent — a deployed binary was
  looking for its schema on the build machine and aborting boot.
- CORS_ALLOWED_ORIGINS=*: anywhere-mode, every origin mirrored WITH
  credentials ("allow CORS to anywhere for now"); SameSite=Lax stays the
  cross-site guard. Default mirror mode unchanged; test pins star mode.

2026-09-12

2026-09-11

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

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

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

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 #27

2026-08-19

✨ feat: course notes uploadable by responsible teacher+Ahmet Kaan Gümüş · 6b1748c
✨ feat: course notes uploadable by responsible teacher+

Mirror of the personal-note stack scoped to a course: course_note +
course_note_file tables, /course-notes routes (POST/GET list?course=,
GET/PATCH/DELETE /{id}, POST/GET /{id}/files, GET/DELETE /{id}/files/{fid}).

Write = can_manage_course (creator, assigned teacher, manager+; live
Teacher role floor). Read = can_view_course (manage or enrolled).
Blob-first upload, cap via cap::claim_and_create (MAX_COURSE_NOTE_FILES),
create-vs-deleted-course refused via cap::touch_and_create, course delete
cascades note/file rows and unlinks blobs.

Tests: 8 integration cases (authz matrix, demoted creator, cross-course
file IDOR, cap 409/413, blob cleanup, cascade 404), race-contract cases
in regress_course_child_orphans, domain unit tests. README Endpoints
table regenerated via doc_sync; Layout updated.

2026-08-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.