Commits
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)
🎧 feat(podcast): the history lists the caller's own episodesAhmet Kaan Gümüş · 6ed7e12
🎧 feat(podcast): the history lists the caller's own episodes GET /podcast/jobs answers the caller's own jobs, newest first, paged via ?limit=&offset= with the shared page envelope — the door a produced episode was missing: without it a finished job is reachable only by remembering which note produced it. Every row is the backend's own podcast_job record plus the title of the course note it narrates, read over the page alone (a second statement, not a join inside the paging statement: the count that pages the list must count jobs). A note that is gone leaves source_title null; duration_secs and finished_at stay null until the episode finishes. The read-side staleness projection applies here exactly as it does on the per-id door, and writes nothing. Tenant scoping is the door's own school database; nobody reads anyone else's jobs.
2026-09-17
🎧 feat(podcast): the submit door resolves the note's PDF and hands the service its blob keyAhmet Kaan Gümüş · 5f9e97c
🎧 feat(podcast): the submit door resolves the note's PDF and hands the service its blob key `podcast.submit` now carries `source_key` — the blob key of the note's newest `application/pdf` attachment, resolved by the backend before the job row is written. The service extracts the source with pymupdf, so it needs the file itself: a note id alone names nothing it can open. - `db::course_note_file::newest_pdf` reads the note's newest PDF (UUIDv7 id order is mint order), and the key it hands on is the row's own id — the same key the attachment's blob is stored under in the school's blob directory. - `POST /podcast/jobs` refuses `409 source_missing` before anything is written when the note has no PDF attachment, or when that attachment's blob is not present on this host — instead of queueing a job the service can only fail later in its `kaynak` stage. - The payload keeps `source_id` for the record and the report echo; a report now matches the row's note id, never a fixed literal. - `tests/podcast.rs`: the submitting tests mint a real course note with a PDF (teacher cookie, real doors) and witness the dispatch's `source_key`, both refusal shapes (no row written, nothing dispatched), and that the newest PDF — not the newest file — is the source. Pre-fix those four witnesses fail with `202` + a queued row, which is the behaviour this change removes. - `.sqlx`: one new query entry, regenerated on a scratch prepare DB. Local-Gate: 5d93323e202eaafb074ee46e3eaa1c0b38229725 (1473 passed, 443s)
📝 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.
docs: correct the bridge's tenancy claim — school is stamped, echo not verifiedAhmet Kaan Gümüş · ee1f8f9
docs: correct the bridge's tenancy claim — school is stamped, echo not verified The bridge correlates replies by frame id only (ai::server dispatch matches Response.id and never compares the school field), so the docs' claim that it 'refuses an answer that does not echo the school' was false. State the true posture: request-side stamping plus the service's own honesty.
fix: 🧪 [TEST] the podcast capability constants are declared, not published limits - limits_completeness demands every pub const in constant.rs be either in GET /limits or in EXCLUDED with a reason; the podcast lane never owned this fileAhmet Kaan Gümüş · d079eff
fix: 🧪 [TEST] the podcast capability constants are declared, not published limits - limits_completeness demands every pub const in constant.rs be either in GET /limits or in EXCLUDED with a reason; the podcast lane never owned this file
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.
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 #272026-08-19
✨ feat: course notes uploadable by responsible teacher+Ahmet Kaan Gümüş · 6b1748c
✨ feat: course notes uploadable by responsible teacher+
Mirror of the personal-note stack scoped to a course: course_note +
course_note_file tables, /course-notes routes (POST/GET list?course=,
GET/PATCH/DELETE /{id}, POST/GET /{id}/files, GET/DELETE /{id}/files/{fid}).
Write = can_manage_course (creator, assigned teacher, manager+; live
Teacher role floor). Read = can_view_course (manage or enrolled).
Blob-first upload, cap via cap::claim_and_create (MAX_COURSE_NOTE_FILES),
create-vs-deleted-course refused via cap::touch_and_create, course delete
cascades note/file rows and unlinks blobs.
Tests: 8 integration cases (authz matrix, demoted creator, cross-course
file IDOR, cap 409/413, blob cleanup, cascade 404), race-contract cases
in regress_course_child_orphans, domain unit tests. README Endpoints
table regenerated via doc_sync; Layout updated.2026-08-13
📝 feat: generate README endpoint table from the served OpenAPI specAhmet Kaan Gümüş · bf8046e
📝 feat: generate README endpoint table from the served OpenAPI spec tests/doc_sync.rs renders the 275-row table from /api-docs/openapi.json (auth floor from declared 403s, else the handler's Require* extractor, asserting exactly one floor per operation), drift-gated in the suite; UPDATE_DOCS=1 regenerates. Static rows are router-verified and plain .route() registrations must reach the table or the suite fails. Curated prose folded into handler doc comments; CLAUDE.md convention updated (table generated; full suite = cargo nextest run).
2026-08-12
🤖 feat: let ai services read the api over quicAhmet Kaan Gümüş · b0af858
🤖 feat: let ai services read the api over quic A service now opens a bidirectional stream of its own, writes one ApiRequest and reads one ApiResponse: the bridge validates it and dispatches it into the real router, so a service asks for school data over the same handlers the REST API serves instead of getting a second copy of them. The router is handed over *before* the outer layers, because a synthetic QUIC request is not a browser request from an IP: it has no address to bill the per-IP limiter (it would drain the shared unknown-client budget), and ETag/CORS are browser concerns. That skips the db guard too, so this path runs the same liveness check and REQUEST_TIMEOUT_SECS deadline itself. Validation order is pinned, since it decides what is refused before the router ever sees it: method (absent or GET) → the AI_API_ALLOWLIST path → the principal, loaded live from the database so a stale id cannot act as a deleted user. Anything the router itself answered — 401, 403, 404 included — rides back as Ok with that status; the Err codes are bridge-level refusals only: malformed, method_not_allowed, path_not_allowed, unknown_user, unavailable, not_json, too_large. The control-stream handshake and the backend→service dispatch are untouched, and a service that never opens a second stream sees no difference at all.
2026-08-05
🖍️ fix: close a whiteboard whose creator was demotedAhmet Kaan Gümüş · 26e7470
🖍️ fix: close a whiteboard whose creator was demoted A board's creator demoted to `parent` left a room nobody could command. The whiteboard is shut to that role outright, so the creator was answered 404 on their own board; clear, lock, close and delete are the creator's alone, so every other participant was answered 403; and `Board::list_for_user` is the crate's only enumeration, so no manager or admin could so much as find the id. Meanwhile the participants kept drawing (the room re-derives membership per frame and they still pass) into a board only the 50 000-stroke lifetime cap could ever retire — and `Board::delete`, the sole releaser of `board_count` and the sole deleter of `board_stroke`, was unreachable forever. The demotion now stamps `closed_at` on every board the account created, in `set_role`'s own transaction and with the same compare-and-set `Board::close` uses, so an already-closed board keeps its first stamp. Written before the roster strip, so the strip's `RETURN AFTER` carries the closed row the caller fans out — as a `closed` frame beside the `participants` one, which is what turns the open sockets read-only. Closed and not deleted: the marks are the other participants' work too, so the board, its history and its epochs stay readable and only writes are refused (`board_closed`, terminal). The cost is accepted — the creator's `board_count` seat stays taken, which is correct while the row it counts still exists, and the strokes stay on disk. The concurrent half needs nothing: `Board::create` claims the creator's own user row (`cap::claim_and_create` on `board_count`), the very record this transaction writes `role` on, so a board opened while the demotion runs collides in the store and one side re-sends — it cannot slip past the sweep.