forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to src/constant.rsClear filter

2026-09-25

🧹 chore(rate-limit): raise the shipped budgets 100xAhmet Kaan Gümüş · 51e5c7b
🧹 chore(rate-limit): raise the shipped budgets 100x

Default budgets when the env is unset: auth 1000/min per IP,
API 30000/min per IP, chatbot 2000/min per user, RAG 600/min per
user, keyless overflow 60000/min. An explicit RATE_LIMIT_* still
wins. The per-route enforcement census uses a small census budget
so CI does not hammer 30000 requests per route; production-scale
boundary stays in the in-memory limiter tests.

2026-09-24

✨ feat(limits): publish the holiday PATCH bound, raise the profile section capAhmet Kaan Gümüş · d9d0403
✨ feat(limits): publish the holiday PATCH bound, raise the profile section cap

`UpdateHoliday.name` now carries the same published `max_length` its create
twin does, so a client validates a PATCH against the same bound the server
re-checks — the runtime refusal was already there, only the contract was
silent.

`MAX_PROFILE_COURSES` goes 20 -> 100: the profile course block became one row
per section, and a teacher's sections are their courses multiplied by the
classes they teach, so the course-era figure truncated a real timetable. It
stays a cap on the response, not on membership — `/courses/me` and
`/classes/me` carry the full lists, and the bound is published so a client can
page for the rest.
✨ feat(schedule): holiday calendar, slot topics, and the weekly-plan materializer coreAhmet Kaan Gümüş · 7c481f7
✨ feat(schedule): holiday calendar, slot topics, and the weekly-plan materializer core

Schema (migrations/school/20260924000001_holidays_and_materialize.sql): a
school-wide `holiday` table over instant ranges, an optional `topic` on both
weekly-plan slot tables, and UNIQUE (class_course, starts_at) on
course_session so two lessons of one section cannot start together.

Domain: `holiday` (name/kind/range newtypes, inclusive `overlaps`) and
`calendar` (the school-zone day math hoisted out of web/attendance, which now
imports it). `WeeklySlot` carries an optional topic; `overlaps` is unchanged.

Db: `holiday` CRUD + overlap-paged list + the materializer's unpaged read;
`course_session::insert_many` (one unnest INSERT .. ON CONFLICT DO NOTHING
RETURNING, so the reported rows are the rows actually inserted) plus
`existing_starts`; a duplicate start on the single-session route now answers
409 session_time_taken instead of a 500.

Service: `holiday` pass-throughs and `course_session::materialize` — one
transaction, archived-year wall, row lock on the instance, refusals coded
instance_has_no_weekly_plan / instance_has_no_teacher, a range cap of 366 days
and a candidate cap of 500, holidays and already-scheduled starts skipped and
counted, nothing ever deleted. Dry run is side-effect free.

The HTTP surface, per-section course lists, and the integration suite follow in
later commits.
✨ feat(courses): grade-ladder course templates with per-class overridesAhmet Kaan Gümüş · 450bc8c
✨ feat(courses): grade-ladder course templates with per-class overrides

course_offering per (course x grade_level 0..=12), per-class overrides on
class_course (nullable scalars + *_inherited flags), subjects/weights/
weekly-plan axis tables, instance_resolve with batched twin, resolved
title/description on instance-scoped reads, six new route groups,
integration scenario test, README regenerated. Evolution migrations
squashed into the base schema (20260912000002_courses + 20260916000001_k12_remodel).

Local-Gate: 246daa3fb3ee7b0ff507a95d6ab346bab1333a37 (1556 passed, 455s)

2026-09-23

✨ feat(profile): add gender, address, and emergency contact to the user row Local-Gate: 1f2b0abcf3798a63b2c5365e0d15c9f708f45833 (1523 passed, 430s)Ahmet Kaan Gümüş · f151345
✨ feat(profile): add gender, address, and emergency contact to the user row
Local-Gate: 1f2b0abcf3798a63b2c5365e0d15c9f708f45833 (1523 passed, 430s)
✨ feat: school identity is the uuid; drop the slugAhmet Kaan Gümüş · 2918040
✨ feat: school identity is the uuid; drop the slug

The school slug is gone from every surface: the session cookie prefix,
the /schools/{id} builder routes, FILES_PATH blob dirs, the hab/2 frame
school value, DTOs, and the /limits contract. SchoolId::try_parse is the
one wire parse (hyphenated uuid only); a non-uuid frame school answers
unknown_school. Register gets a public picker via the new unauthenticated
GET /auth/schools returning active [{id, name}]. The control migration
drops school_slug and the slug column, which invalidates every existing
session — old cookie prefixes cannot resolve.
Local-Gate: 3fafffd98aec59c68e2606833b87785d0abf2fee (1510 passed, 425s)

2026-09-22

fix: send a reconnect's index replay to the new workerAhmet Kaan Gümüş · c1d2674
fix: send a reconnect's index replay to the new worker

A RAG restart leaves the dying connection registered until the 30s idle
timeout. Equal load picked the older id, so the replay that fires on
register was sent to a connection that then timed out, and the school's
notes never re-entered the in-memory index. Equal load now prefers the
newer id. The blob-write stall is also 15s, under the 30s idle timeout,
so a stalled blob resets its stream instead of dropping the connection.
Local-Gate: 295251821acae9b52e92214d17dec1bac2baf67e (1513 passed, 521s)

2026-09-20

✨ feat(users): give students a school-issued student numberAhmet Kaan Gümüş · 777c7df
✨ feat(users): give students a school-issued student number

Every school numbers its students its own way ("1234", "9-B/17"), and the
account carried no field for it: the office kept the mapping outside the
product. The number is now a first-class optional field on the user row,
unique inside the school (per-school uniqueness is the per-school database)
and held by students only.

- migrations/school/20260920000001_student_number.sql: `app_user
  .student_number TEXT NULL`, the partial unique index over its non-NULL
  values, and a CHECK (student_number IS NULL OR role = 'student'). The boot
  sweep applies the file to already-provisioned schools like every other
  school migration.
- domain: `StudentNumber`, a validated newtype (trimmed, non-blank, at most
  MAX_STUDENT_NUMBER_LEN = 32) in the shape of `Username`, plus the one
  spelling of the non-student refusal both the web gate and the database map
  answer; `User` carries `Option<StudentNumber>`.
- db: `create_with_role` binds it into the mint; `set_profile` writes it and
  maps the index's 23505 to the coded 409 and the row's 23514 to the same 400
  the handler gate answers; `set_role_cascade` clears it in the same statement
  that leaves the `student` role. The CHECK is what closes the read-then-write
  race the handler-side gate cannot see: a profile save carrying a number from
  a `student` snapshot while a promotion commits first is refused by the row
  itself, and a test pins exactly that (it writes a teacher holding a number
  without the CHECK).
- web: `POST /users` and both profile doors (`PATCH /users/me`,
  `PATCH /users/{id}/profile`) accept it under the merge semantics the other
  patchable fields have (omitted = keep, blank = clear), with the role gate as
  a 400 and a duplicate as a 409 carrying `code: student_number_taken`.
  `UserResponse` (admin reads, create/patch echoes, `/auth/me`) and `PersonRef`
  (pickers, students lists) carry it; the school-wide public profile
  deliberately does not — an office identifier is not broadcast school-wide.
- /limits publishes `max_student_number_len`; spec_bounds pins both new
  `max_length` annotations and the README's bound count moves to 224.
- tests: the mint and both patch doors — trimmed storage, 33 chars a 400,
  whitespace read as absent, a duplicate a coded 409 on both paths, a
  non-student a 400, blank clearing, a promotion clearing with the role change
  (and a demotion back not restoring it), and the stale-snapshot race at the
  db layer.

Evidence: the partial index refuses a duplicate (23505 naming
app_user_student_number) and admits both rows once dropped inside a
rolled-back transaction; with the 409 mapping removed both write paths answer
500 and the tests fail; with the CHECK removed the race test writes the
forbidden row (role: Teacher, student_number: Some(...)) and fails.
Local-Gate: 2c10aae51c575b7f4207fa310d8938070c0fbb80 (1509 passed, 572s)

2026-09-18

✨ feat(rag): relay rag.summarize and rag.questions over the bridgeAhmet Kaan Gümüş · 69d4295
✨ feat(rag): relay rag.summarize and rag.questions over the bridge

The RAG service has had two study features the backend never dispatched:
a scope summary and a set of generated practice questions, each one-shot
and addressed to exactly one (sınıf, ders) corpus.

- constant.rs: AI_RAG_SUMMARIZE_CAPABILITY / AI_RAG_QUESTIONS_CAPABILITY
  with 25 s deadlines — a waiting door must finish under the 30 s request
  envelope; MAX_RAG_QUESTIONS is published at /limits.
- ai/rag_study.rs: the two payload/reply contracts and their dispatch,
  wire-key pinned.
- web/rag.rs: POST /rag/summarize and POST /rag/questions over the same
  QUIC bridge and the same 503 capability gate as the rest of the nest.
  The asker's (sınıf, ders) pairs come from their memberships; the body
  only names a target inside them (403/400 otherwise). An abstention is a
  complete 200; only role_required/scope_mismatch — the backend's own bug —
  is a 502.

README endpoints table regenerated; AI bridge prose extended with both
contracts and the honest RAG-side limits.
Local-Gate: 852ea13260383ac5c071fce412db110becbcbdde (1505 passed, 473s)
🐛 fix(insight): size the report deadline under the request envelopeAhmet Kaan Gümüş · 8ce2e1d
🐛 fix(insight): size the report deadline under the request envelope

Two verifier flags, one cause: the report door waits on its dispatch inside
one HTTP request, and the request-timeout middleware (30 s) drops the handler
future wherever it stands — mid-write included — answering its own 503 whose
"the write may or may not have applied" prose is wrong for a door that knows
nothing was stored, while a drop inside the store window stranded a
`.report-<uuid>.tmp`.

`AI_INSIGHT_REPORT_TIMEOUT_SECS` drops 300 → 25, so the service loses the
race on purpose and the door's own error path fires first: the honest
"nothing was stored" 503, and no temp is ever opened. The constant's comment
now states the relationship and that raising it needs the ceiling raised
with it; the row reads before the dispatch share the same envelope, which is
why the margin is not spent elsewhere.

Pinned as a compile-time assertion beside the report contract tests: a
raised deadline without a raised ceiling fails the build, proven by flipping
the value to 30 (E0080, the message) and reverting.
Local-Gate: c92220e9d9b886dc45b86b88c2ff7ecc6a54ce7a (1497 passed, 443s)
📄 feat(insight): render and serve a school-level report documentAhmet Kaan Gümüş · 541d9b7
📄 feat(insight): render and serve a school-level report document

`insight.report` is the third outbound ZEKA dispatch, and the first that
carries its data: the service may not read a school database, so the backend
reads its own `zeka_*` rows (four new school-wide bulk reads, projected
straight into the serde rows the storage surface already writes) and sends
them in the request. The service renders, the backend stores.

* `POST /insights/runs/{run_day}/report` — manager+, synchronous: build the
  payload, dispatch with `AI_INSIGHT_REPORT_TIMEOUT_SECS`, store the returned
  HTML under the school's own blob directory (`zeka_report/<day>.html`, temp
  name + rename, never a partial file), answer `200` with what was stored.
  A run day with no ledger row is a legal request; the service's `notes` say
  what it found. Its typed refusals map per class: `bad_request` 400,
  `insufficient_rows` 409 `report_empty`, `document_too_large` 413,
  `internal` 500, anything else 409 `report_refused`. An empty document is
  refused, never persisted — a blank page must not read as a report.
* `GET /insights/runs/{run_day}/report` — manager+, streams the stored
  document (`text/html; charset=utf-8`, nosniff, private no-store);
  `409 report_missing` when nothing was generated, a day the ledger has never
  heard of included.

Both doors share one path (one `routes!(generate_report, serve_report)`), so
no nest or `MODULE_PREFIXES` change; `MIN_PROTECTED` 338 → 340 (derived).
`pump` moves from the podcast nest to `web` as a shared blob-stream helper.

Known gap, reported rather than widened here: the wire `RecommendationRow`
carries no `dismissed_at`, so the service's dismissal gate cannot fire on
this payload.
✨ feat(insight): name the requester and fill a school-wide refresh rosterAhmet Kaan Gümüş · 0f55f34
✨ feat(insight): name the requester and fill a school-wide refresh roster

Every `insight.*` dispatch now carries `requested_by` — the caller the door
authenticated, which the service passes as `on_behalf_of` so its per-student
reads (`/marks/{user}` and the rest) answer as that teacher or manager instead
of the synthetic `ai` principal those reads refuse with a 403.

`insight.refresh` also always fills `user_ids`: a caller-named list passes
through exactly as given, while an empty body is filled from the school's own
student roster (every user holding the `student` role), because the service's
own roster discovery reads homework `assigned` lists, which a live school
rarely fills — so an empty body used to sweep nobody. The payload's new
`roster_source` records which roster the list was, and the refresh log names it
so the run ledger's counts are explainable. A school with no students dispatches
an empty list and answers 0 honestly; a roster past
`MAX_INSIGHT_REFRESH_STUDENTS` is refused rather than clipped.
Local-Gate: 644eaaee78ddae2e35af223da2719c3a55697a86 (1488 passed, 466s)

2026-09-17

📝 docs: rewrite the Turkish comments and doc comments in EnglishAhmet Kaan Gümüş · 7fec874
📝 docs: rewrite the Turkish comments and doc comments in English

The Rust repo's own language is English; Turkish had leaked in from the
sibling AI services. Translate every comment and doc comment to English
using the code's own vocabulary (şube -> class section, dönem -> term,
sınıf öğretmeni -> homeroom teacher, ortak sınav -> shared exam, karne ->
report card, …). Quoted Turkish letters/words that are themselves the
data under test (the text-fold examples in `text_fold`/`settings`, the
non-ASCII filename sample) are kept.

The README endpoint table is generated from those doc comments, so it is
regenerated. AGENTS.md records the convention going forward: Turkish
survives only where it is the data under test or user-visible content.
✨ feat: ZEKA no longer touches the database directly - the insight.* storage surfaceAhmet Kaan Gümüş · 7c96e47
✨ feat: ZEKA no longer touches the database directly - the insight.* storage surface

No AI service may hold a school database credential, so the nine reads and
writes ZEKA performed against its own zeka_* tables become named operations
the backend serves: insight.summary|recommendation|segment|profile|run.upsert,
insight.pending.list, insight.retention.sweep, insight.departed.purge and the
deployment-scoped insight.schools.list.

They ride a new client-initiated capability call (CapabilityRequest ->
CapabilityResponse, mirroring Request/Response field for field) and are
mounted as HTTP doors on the same functions (manager+; the school directory is
the builder's, outside the school gate). Every statement runs inside the
school the frame named, in one transaction per batch.
merge: 🔀 lane/insight + lane/podcast — the zeka insight nest and the podcast relayAhmet Kaan Gümüş · e66cef0
merge: 🔀 lane/insight + lane/podcast — the zeka insight nest and the podcast relay

Both lanes append to constant.rs/lib.rs/ai+web mod.rs in disjoint regions; the two
conflicts were adjacent-line appends, resolved by keeping both sides. tests/integration.rs
MODULE_PREFIXES carries both new nest rows (renamed 23 -> 25) from lane/insight.
✨ feat: ZEKA's insight capabilities — its school schema, the dispatch contract, and the /insights nestAhmet Kaan Gümüş · b0b5e0c
✨ feat: ZEKA's insight capabilities — its school schema, the dispatch contract, and the /insights nest

`hezarfen_zeka` already dials the QUIC bridge correctly and declares three
capabilities the backend did not know (`insight.student`, `insight.class`,
`insight.refresh`), and it writes nine `zeka_*` tables the school schema did
not contain — so nothing could route to it and nothing could read what it
computed. This lands all three missing pieces.

* the migration: `migrations/school/20260917000002_zeka.sql`, the service's
  DDL copied verbatim (every FK resolved against the existing school schema:
  `app_user`, `course`, `subject` and `exam_question (exam, id)`).
* `src/ai/insight.rs`: the payload contract for the three capabilities,
  mirroring the service's TypedDicts, plus the two dispatches the backend can
  route today — `compute_student` and `refresh`. `insight.class` stays
  contract-only: its request names a course the service would have to
  enumerate a roster for, and the bridge's read allowlist carries no member
  listing yet (`hezarfen_zeka/service/docs/BACKEND-GEREKSINIMLERI.md` item 3).
* `src/web/insights.rs`: the nest. `POST /insights/students/{id}` and
  `POST /insights/refresh` (manager+) queue a detached dispatch and answer
  `202` — the service writes its own rows, so a client polls the read routes;
  `503` when no worker offers the capability and nothing is queued.
  `GET /insights/me`, `GET /insights/students/{id}` (teacher+ narrowed to the
  students they reach through a shared instance, or a parent holding a live
  link; anyone else reads `404`, never `403`) and `GET /insights/runs`
  (manager+) read the tables back. The service's output contract's own gates
  hold on the read side: the attention list never reaches the student it is
  about, a card's `about` never reaches a student caller, dismissed/expired
  cards and `confidence: none` segments are filtered out.

Gated on `Module::Chatbot` like the other two AI nests, with its tag prose in
`src/lib.rs`, the README endpoints table regenerated, and the `.sqlx` cache
refreshed for the seven new statements.
✨ feat: the podcast relay — four podcast.* capabilities and their audio streamAhmet Kaan Gümüş · 5a5a483
✨ feat: the podcast relay — four podcast.* capabilities and their audio stream

The backend had no dispatch site for podcast.submit/status/result/cancel, so the service's registration was unreachable. New AI_PODCAST_*_CAPABILITY constants, ai::podcast payload types + dispatch, and a /podcast nest gated on the chatbot module: POST /podcast/jobs (202 receipt), GET /podcast/jobs/{id}, GET /podcast/jobs/{id}/result, POST /podcast/jobs/{id}/cancel. Each door answers 503 with no worker declaring its capability, and relays the service's own refusal code as a status (not_found → 404, not_ready/llm_unavailable → 409, busy → 503, timed_out → 504, transport/protocol/bad_reply → 502).

The produced audio never crosses the bridge: podcast.result answers audio_id as a path relative to PODCAST_OUTPUT_ROOT, which the deployment points at the school's own directory under FILES_PATH, and GET /podcast/audio?path= streams it in bounded 64 KiB chunks out of the school-scoped State's files_path. That door refuses absolute paths, ./.. segments, backslashes, colons and symlinks resolving out of the school's directory with 400, and 401 without a session.

tests/podcast.rs drives all four capabilities over a real QUIC bridge against a fake service, plus the 503s (no worker and no bridge), the refusal→status mapping, the module gate, the session gate, and every audio-door refusal against a file that really exists. README endpoints table regenerated with UPDATE_DOCS=1.

Known pending, owned by lane/insight: tests/integration.rs's hand-written MODULE_PREFIXES needs a (Module::Chatbot, "/podcast") row, so the route-mount gate stays red for /podcast until that row lands.
✨ 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.
🔧 chore: give ResolvedTenant its core home and make constant.rs a leafAhmet Kaan Gümüş · d0dce85
🔧 chore: give ResolvedTenant its core home and make constant.rs a leaf

Two structural defects a knowledge-graph pass over src/+tests/+migrations
surfaced. Both were verified against the real `use` lines before being called
defects — a module cycle is legal Rust, so only the layering facts count.
No behavior change: every moved item is byte-identical in name, type, value,
element order and doc text.

- `ResolvedTenant` was *declared* in `src/web/tenant_state.rs` but *built and
  returned* by `Tenants::resolve` (`src/tenant.rs`), so the core tenant
  registry imported the web layer. The struct moves to `src/tenant.rs`; its
  `impl FromRequestParts` stays in the web module (same crate, local type).
  That deletes the crate's only core→web import edge, and with it the three
  module cycles running through `state.rs` and `ai::server`.
- `constant.rs` is documented "Validation limits, in one place" but imported
  four domain enums to hold non-limit vocabularies: `ROLES` → `domain/role.rs`,
  `THEMES`/`LANGUAGES` → `domain/preferences.rs`, `SENDER_FOLDERS`/
  `RECIPIENT_FOLDERS` → `domain/message.rs`, and the 34-row `BADGES` catalogue
  → `domain/badge.rs`. Each now lives in the module that owns its type, so
  `constant.rs` imports nothing from `crate::domain` and ten
  `constant ↔ domain` cycles disappear. `AI_PRINCIPAL_KEY` and
  `PALETTE_COLOR_*` stayed put.

Measured on the same corpus: 20 → 7 reported import cycles — all ten
constant↔domain and all three tenant↔web cycles gone. The surviving seven are
intra-layer domain cycles plus the ai↔web pair; the AI bridge is a peer
front-end reusing web authorization helpers, which is deliberate, not an
inversion.

Tests: the published-or-excluded guard in `limits_completeness` read only
`src/constant.rs`, so the five moved tables silently left its scan — the one
place this move weakened coverage. It now covers them by name, and its
`references()` check no longer counts a bare `use` line as "published", which
the first witness attempt proved had made the guard vacuous. Witnessed by
mutating BADGES and then ROLES out of `/limits`: each FAILs naming the moved
table, and each restore is sha256-identical.

Gates: no SQL touched (.sqlx and migrations clean), prepare DB unchanged;
SQLX_OFFLINE=true cargo check --all-targets, clippy -D warnings,
limits_completeness, spec_bounds all green; cargo nextest run 1386/1386 across
47 binaries (doc_sync included).

2026-09-16

✨ feat: the class×course instance is the academic anchor (K-12 remodel)Ahmet Kaan Gümüş · ae84034
✨ feat: the class×course instance is the academic anchor (K-12 remodel)

`course` was a school-wide singleton: enrollment, exams, sessions,
roll-call and homework all keyed on it, so two class sections teaching the same
course shared one roster, one exam set and one timetable. This moves the
academic anchor to `class_course` — the per-class instance — and rebuilds
the academic model around Turkish K-12.

Schema (migrations/school/20260916000001_k12_remodel.sql): `class_course`
becomes an instance (ders_saati, counts_toward_karne, enrollment_count,
class_course_teacher); enrollment re-keys to (class_course, app_user);
exam carries class_course + term (+ exam_audience for shared exams);
course_session / session_attendance / homework re-key; `class_member` is a
soft-leave history table (uuid PK, joined_at/left_at, partial unique index
on the live stint); `academic_year` sits above `term`; `class_group` links
a year, not a term; new `course_membership` (clubs/study), `karne_snapshot`;
settings gain branches/excuse_kinds/absence limits/timezone; profile gains
branch. Drops/recreates the identity-changing tables (pre-customer; the
migration resets every counter on a kept table that pointed at a dropped
one).

Layers: domain/db/service/web rewritten to the instance seam, with
`ensure_instance_teacher` gating instance writes (D10), the report card computed per
instance and weighted by ders_saati, an absence report, `/instances`
and `/academic-years` nests, and `/classes/{id}/instances`. Capacity and
the seat-claim 409 are gone; detach sweeps the whole instance subtree and
unlinks its blob keys.

Gates: cargo check --all-targets, SQLX_OFFLINE check (cache regenerated),
doc_sync, spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1370/1370.

2026-09-14

🗃️ feat: pre-prod schema: person join key, drop school password copyAhmet Kaan Gümüş · 804bd3c
🗃️ feat: pre-prod schema: person join key, drop school password copy

app_user no longer stores password_hash (login already verifies
control person). School rows carry person uuid + created_at.
class_blueprint is uuid-keyed; exam child rows composite-FK to
(exam, question); pool/solution images are child tables;
graded_at/marked_at/enrollment timestamps added.

Left alone: occupancy/refcount counters (cap locks, not lies),
ledger source, menu derived id, school.slug PK, fee_plan JSONB.

2026-09-12

🧪 test: port T4 regress/partial-patch suites to the Postgres harnessAhmet Kaan Gümüş · f553d14
🧪 test: port T4 regress/partial-patch suites to the Postgres harness

- fixture SQL → runtime sqlx (kind_ref/slot_ref upserts, settings JSONB,
  point-row UPDATEs, count/scalar helpers); ULID idioms re-pointed
- SurrealDB DEFINE EVENT injections → PG-native: RAISE triggers (roles/
  classes/blueprints pending), pg_sleep window trigger (exam delete),
  lock-queueing probe (attendance), row-snapshot probe (badge awards)
- EXTRA: drop DB_KEEPALIVE_INTERVAL_SECS/DB_PING_TIMEOUT_SECS + their
  /limits EXCLUDED pins; drop stale BOARD_OPEN_GUARD pin (wave-2 leftover)
- production fixes pinned by these suites: exam_result grade claim mints
  an absent kind_ref (absent = in service); field_update run() emitted a
  double WHERE (every guarded PATCH 500'd); attendance event mark now
  locks the event row (orphan race); admin floor takes the admin-set row
  locks (cross-target demotions raced); profile focus sum cast to BIGINT
- delete the two appointment store-property tests: their subject was the
  SurrealDB engine's write-skew; Postgres closes it by constraint
- .sqlx refreshed for the changed query macros
🗃️ feat!: port boards, notes and rag to sqlx/PostgresAhmet Kaan Gümüş · c928ecf
🗃️ feat!: port boards, notes and rag to sqlx/Postgres

- board/note/course_note/rag_output db layers: static query!/query_as! against
  the union-schema prepare DB; PagedList/FieldUpdate for the runtime builders
- file caps via the cap claim CTE at each call site; board create claims
  app_user.board_count, delete releases it in the same tx
- BOARD_ROSTER_LOCK deleted: invite is one guarded atomic-array union
  (coalesce(array_agg(DISTINCT unnest(participants || $n))) with a
  cardinality cap on the row version the UPDATE acts on)
- stroke dual-counter claim: one UPDATE bumps both counters, lifetime cap +
  open guard + epoch in the WHERE; zero rows re-read via cap::full_kind
- board clear: pre-image read under SELECT ... FOR UPDATE, refusal precedence
  preserved (closed > not-creator > locked > blank), guarded epoch bump,
  marker insert, one tx (CLEAR_REFUSED THROW now Rust-level refusals)
- rag_output.payload JSONB (sqlx::types::Json), sources uuid[] cascade via
  $n = ANY(sources); note/course_note delete cascades sweep rag_output
  in-tx (real FKs refuse dangling derived rows)
- board rosters: uuid[] + GIN, membership reads $n = ANY(participants)
- dead SurrealQL-shaped constants removed (BOARD_OPEN_GUARD, BOARD_STROKE_TABLE,
  counter/file-count field constants); uuid::Uuid imports for my domain files

2026-09-11

✨ feat: optional student label on pomodoro sessionsAhmet Kaan Gümüş · 54ec62d
✨ feat: optional student label on pomodoro sessions

POST /pomodoro/start accepts an optional {label} body (trimmed, blank
stored as absent, >100 chars rejected). The label rides the finish
re-file, is returned on start/finish and in both log endpoints, and is
published as pomodoro.max_label_len on GET /limits. SCHEMAFULL field
added; pre-feature rows read as no label.
Merge branch 'layer-split/bank'Ahmet Kaan Gümüş · 164e756
Merge branch 'layer-split/bank'

# Conflicts:
#	src/db/mod.rs
#	src/domain/bank_question.rs
#	src/domain/pomodoro.rs
#	src/domain/pool_question.rs
#	src/service/mod.rs
#	src/web/bank_questions.rs
#	src/web/exams/mod.rs
🧹 chore: split profile, badge, builder into domain/db/service layersAhmet Kaan Gümüş · 7f616c0
🧹 chore: split profile, badge, builder into domain/db/service layers

C3 identity lane. Moves, not rewrites:

- badge: BadgeStats::load / BadgeAward::list_for / sync (UPSERT with the
  earned_at = NONE idempotency stays whole) -> db::badge, with the
  award-key mint and the persistence tests; BadgeStat/BadgeStats/earned/
  BadgeAward (pure rules) stay in domain::badge; service::badge wraps
  list_for/sync for the web layer.
- profile: ProfileStats::load (+ PomodoroTotals, persistence tests) ->
  db::profile; newtypes + getters stay; service::profile::load wraps.
- builder: find_by_username/read/create(create_session)/find_by_token/
  delete_by_token -> db::builder; the idempotent seed ensure ->
  service::builder (ensure_admin precedent); both tests ride their fns.
- preferences, key: fully pure (validated newtypes, composite-id
  helpers) — stay domain-only, no db/service modules created.

Entity fields the split constructs from are now pub(crate) (Builder,
BuilderSession, ProfileStats), matching the user split.

Callers re-pointed crate-wide: web/{users,exams/mod,questions,homework,
sessions,auth,extractor,builder,tenant_state}, service/exam_attempt.rs
(badge::sync after start), database.rs (control seed), tests/
{builder_api,e2e,integration}; cross-lane compile fixups in
domain/pomodoro.rs and domain/session_attendance.rs (their lanes
re-point on merge). constant.rs doc link -> crate::db::badge::list_for.

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

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.
🐛 fix: blob stream resets on write stall, client-stream routing without a Value cloneAhmet Kaan Gümüş · bc43602
🐛 fix: blob stream resets on write stall, client-stream routing without a Value clone

A blob body that makes no progress for AI_BLOB_WRITE_STALL_SECS is reset
rather than parking the copy task and an open fd for the connection's life.

Ref #27
✨ feat: rag_output table + rag.index dispatch for course notesAhmet Kaan Gümüş · d42a1c3
✨ feat: rag_output table + rag.index dispatch for course notes

The backend now owns the RAG side of a course note: a new `rag_output`
table stores whatever an AI service produced for a note, and the backend
asks for it — the AI service still writes no human data, and the api-read
bridge stays GET-only.

`rag.index` is dispatched fire-and-forget (tokio::spawn) after a note is
created, edited, or gains/loses a file, so no HTTP handler waits on, or
fails because of, an AI service; with no worker carrying the capability
the trigger is a silent no-op. The request carries the note's text plus
attachment METADATA only (file bytes deliberately off the wire — open
with the service owner). Rows are derived data, so they cascade: the note
delete drops its outputs, and a file delete drops every output built from
it even when no service is connected.

HTTP GET/DELETE routes over the rows are part 2.

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

chore: rename ponytail: comment marker to corner-cut:Ahmet Kaan Gümüş · ed88733
chore: rename ponytail: comment marker to corner-cut:

Marker convention renamed after uninstalling the ponytail plugin;
semantics unchanged (deliberate corner-cut, known ceiling + upgrade path).
Token-only rename, 26 comment lines, no code change.

2026-08-12

🤖 feat: allowlist the GET paths ai services may readAhmet Kaan Gümüş · 317ef9c
🤖 feat: allowlist the GET paths ai services may read

Deny-by-default: the bridge will only ever dispatch a service's read into
the router when the path matches AI_API_ALLOWLIST segment for segment. No
prefix match, no wildcard tail, so a new route family is unreachable to
the services until it is listed on purpose.

v1 is JSON-only and scoped to what a study companion needs: identity and
profile, notes, homework reads, and the marks/attendance/pomodoro
reports. Byte-serving routes (note files, submission files, avatars,
question images) are left out — the frames carry JSON.

The entries are router paths kept by hand, so integration.rs pins each
one to a GET in the emitted OpenAPI document: a route rename now breaks
the test instead of silently shrinking the services' scope.
🤖 feat: add service-only Role::AiAhmet Kaan Gümüş · 3a01d26
🤖 feat: add service-only Role::Ai

The principal an out-of-process AI service carries over the QUIC bridge.
Declared first in the enum so the derived Ord puts it under every role: it
clears no `at_least` bar and fails every exact `== Role::Student` /
`== Role::Parent` gate. Absent from ROLES, which is what makes it
unassignable — `try_from_str` searches that table, so "ai" is rejected like
any unknown word, and /limits keeps listing the five human roles. Role still
carries no serde derive, so nothing deserializes it off the wire.

`User::ai_principal` builds it in memory only, on the literal record key
`ai_service` that no minted ULID can collide with, with an empty password
hash that verifies against nothing. Never written to the database.

The web DTO gains the variant because the mapping is exhaustive, so "ai"
appears in the OpenAPI Role schema — documented there as never assignable.

2026-08-05

⏱️ 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).
🧱 feat: shared primitives for parent-collision claimsAhmet Kaan Gümüş · 558c39a
🧱 feat: shared primitives for parent-collision claims

SurrealDB 3.2.3 conflict-checks write sets only, so a child write that
merely reads its parent survives that parent's delete window. Three
helpers now carry the bump-then-restore idiom instead of each caller
hand-spelling it:

- touch_and_create: a bare CREATE under a deletable parent
- role_claim: a child whose parent is a user whose role may change
- create_counting: claim_and_create with a 0/1 bump, so a row can land
  without moving the tally

New ceilings: MAX_MEAL_BOOKING_ATTEMPTS, MAX_FEE_PLAN_ASSIGN_WRITES,
MAX_LEDGER_APPLIED_LINES, USER_ROLE_CLAIM_FIELD.
fix: 🎖️ give the grade credit back when a grade is deletedAhmet Kaan Gümüş · 6197fc3
fix: 🎖️ give the grade credit back when a grade is deleted

Both grade sites credit on the branch that finds no row, and a deleted row
reads as no row — so ungrade-then-regrade credited a second time off one
stored mark. Looped, one teacher and one student minted marks_given_250 and
high_mark_25 from a single exam, or from a homework with no submission behind
it at all, and an award once earned is never revoked.

Each delete now refunds inside its own transaction and only for rows it really
removed: marks_given_total to each removed row's own grader (a manager may
un-grade what a teacher graded), and high_mark_total off the removed mark's
BEFORE image. Floored at zero, so a row predating the columns cannot push one
negative. HomeworkResult::remove takes the transaction_with_retry upgrade its
sibling already wanted — the new counter is what makes it necessary, since the
grader's row is written by exam grading too — and with it the hand-kept slot 1
becomes the usual trailing-RETURN count.

The rule in constant.rs said the opposite; it now states which routes refund
and why, and names the cascades as the one leak left open.

2026-08-04

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

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

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

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

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

Thirteen badges a student earns by doing the work, so the profile has
something to be proud of rather than just a photo and a bio.

Nothing awards a badge by hand and nothing takes one away. A badge is
earned when a counter crosses a threshold, and it is permanent: withdraw
the submission that earned it and the count falls while the badge stays,
because a stamped `earned_at` is the motivational payload and a badge
that evaporates is worse than no badge. The catalog is hardcoded, so
changing a threshold is a deploy and the evaluator stays a pure function
of the counters. It rides GET /limits as a group like every other bound;
labels and icons are the frontend's, keyed by badge id.

The counters are the real work. Homework, exam and attempt tables are
indexed for the questions the rest of the API asks, so counting a single
student's history meant a full table scan — the numbers are therefore
tallied at write time, in the same transaction as the write that causes
them. Existing accounts are seeded once from their real history, gated by
a mark whose skip is proven rather than assumed, so nobody starts at zero
for work they already did.

Withdrawing your own submission decrements, and that is the only
decrement in the codebase: withdrawal is student-callable, so without it
submit/delete/submit would farm the counter. Cascades never decrement —
history a teacher erased is still history the student lived. The cost is
that a re-run seed, which can only count rows that still exist, comes out
lower than the live tally; documented where someone would otherwise
"repair" it.

Deadlines move, so the on-time verdict is now stored on the submission
beside the count it fed. Judging it again at withdrawal read whatever the
deadline had become since, which drifted the tally in both directions —
far enough that on-time could exceed submitted.

Attendance counters were dropped: those tables already carry per-user
indexes, so there is no scan to fix, the status list is school-editable,
and roll-call corrections would need a decrement that fights permanence.