Commits
2026-09-23
✨ feat: school identity is the uuid; drop the slugAhmet Kaan Gümüş · 2918040
✨ feat: school identity is the uuid; drop the slug
The school slug is gone from every surface: the session cookie prefix,
the /schools/{id} builder routes, FILES_PATH blob dirs, the hab/2 frame
school value, DTOs, and the /limits contract. SchoolId::try_parse is the
one wire parse (hyphenated uuid only); a non-uuid frame school answers
unknown_school. Register gets a public picker via the new unauthenticated
GET /auth/schools returning active [{id, name}]. The control migration
drops school_slug and the slug column, which invalidates every existing
session — old cookie prefixes cannot resolve.
Local-Gate: 3fafffd98aec59c68e2606833b87785d0abf2fee (1510 passed, 425s)2026-09-22
🐛 fix: scope manager study questions to the school and publish its nameAhmet Kaan Gümüş · 20e856a
🐛 fix: scope manager study questions to the school and publish its name
An admin with no personal class row was dispatched to rag.chat with zero
scope pairs, so every study question abstained. Managers and admins now
get every class-course pair. A rag.index registration replays notes that
have files, because that index is in-memory and a restart wipes it.
GET /school returns {id, name} to every school session. No slug.2026-09-18
🐛 fix(ai): withdraw a capability a service refuses as unknownAhmet Kaan Gümüş · 0eb20f9
🐛 fix(ai): withdraw a capability a service refuses as unknown A service that advertises `insight.refresh` in its `Hello` and then answers the dispatch with `unknown_capability` has contradicted its own handshake. The door read that advertisement as availability, queued the work with a `202`, and the refusal could only ever be a WARN — the user saw success and nothing happened. `rag.index`, `insight.refresh` and `insight.student` have each bitten this way. Now the registry withdraws the contradicted claim (`Registry::withdraw`): `Worker::offers` — what `pick`, `has_capability` and the snapshots read — is false for it, so routing drops the name and `GET /ai/capabilities` stops listing it. Every door already branches on `has_capability`, so the next call takes the `503` path it already had instead of queuing work nobody will do. The WARN names the service, the capability and the refusal code. Only a permanent, self-contradictory refusal does this. `unknown_capability` is the one code the protocol defines for "no operation by this name" — its example service-defined code (`unsupported_image`) is a verdict about a payload, not a claim about what the worker serves. Transient verdicts (`unavailable`, `timed_out`, `internal`, `capacity`) leave the claim standing, so a busy or restarting service keeps getting the next request. The withdrawal is per connection, never durable: every reconnect inserts a fresh worker built from its `Hello` alone, so a service that fixes itself restores the capability with no operator action. Tests: a refused refresh flips the next `POST /insights/refresh` to 503 and drops the capability from discovery (proved failing before the change); an `unavailable` refusal keeps both the 202 and the listing; a reconnect restores it — plus two registry unit tests. Local-Gate: 8718d07b6fbc70148eebea518febeb7bba764a46 (1486 passed, 474s)
2026-09-17
✨ feat: the podcast job's row and audio now live in the backend - backend-owned row, mp3 ingest, read gates without the serviceAhmet Kaan Gümüş · c44f362
✨ feat: the podcast job's row and audio now live in the backend - backend-owned row, mp3 ingest, read gates without the service
The job record lived only in the podcast service's own volume, so a restart
or a wiped volume lost every in-flight job a caller was polling and the mp3 it
was about to download. The backend now owns both ends of that state:
* `migrations/school/20260917000003_podcast.sql` — `podcast_job`, the job's
own row (user/source/format/state/stage/progress/error_code/audio_*/
duration/eta/created/updated). No `school` column: the school IS the
database, and the row's tenancy is (this database, user_id).
* `POST /podcast/jobs` mints the id, writes the row, THEN dispatches
`podcast.submit` with `{job_id, source_id, format, user_id}`; the service
echoes that id in its receipt (mismatch = 502 + a failed/bad_reply row).
No worker = 503 and no row; a refusal or transport failure tombstones the
row with the reason code — nothing is left claiming `queued`.
* The service reports every transition back through `podcast.report` (the new
client-initiated capability call, School-scoped, wired through
`src/ai/capability.rs`), which validates the echo, the jobs.py transition
table, the retention window and the done-means-audio rule before one
conditional UPDATE keyed on the state it read.
* The finished mp3 arrives as a `BlobUploadRequest` stream (exactly `size`
raw bytes), lands under the school's own blob root at
`podcast/<job-id>.<ext>` (temp+rename, row stamped in the same act, file
removed again if the row write finds the job gone), and `POST`ing a done
report before it is refused `audio_missing`.
* The read doors — `GET /podcast/jobs/{id}`, `.../result`,
`.../audio` — answer from the row with no service round trip: 404 for an
unknown or foreign job (foreign ids read as absent), 409 `not_ready` /
`audio_missing`, 410 past PODCAST_JOB_RETENTION_SECS, and a read-side-only
projection that presents a queued/running row nobody has updated inside its
ETA-scaled window as failed/interrupted — the GET writes nothing and a real
report overwrites it. `podcast.status`/`podcast.result` capabilities are
deleted with their payloads; the old `GET /podcast/audio?path=…` door is
gone (it named a cross-volume path and could not be owner-scoped).
Also: `AppError::Expired` (410) + the two room matches that needed it,
MIN_PROTECTED 323 -> 337 (real swept count), the three clippy fixes on the
committed tree, README regenerated, and the .sqlx entries for both lanes'
queries. This commit completes the tree that 7c96e47 half-staged: that commit
took the shared files (server/protocol/constant/db-mod/ai-capability) while
leaving `src/ai/podcast.rs`, `src/web/podcast.rs` and `tests/podcast.rs` at
their old versions, so main did not compile until this one.✨ 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.
✨ 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).
🔧 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-12
2026-09-11
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
2026-09-05
🔒 fix: the registry refuses an unsatisfiable module set; no AI egress without the ai packageAhmet Kaan Gümüş · 8f2c521
🔒 fix: the registry refuses an unsatisfiable module set; no AI egress without the ai package `Tenants::create`/`set_modules` validate the dependency graph themselves. A school without `chatbot` dispatches no rag indexing and the blob stream refuses `module_disabled`, so a customer who did not buy AI ships no data to the AI services.
✨ 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.
✨ 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: 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 #272026-08-12
🧪 test: pay the api-read err-code coverage debtAhmet Kaan Gümüş · a3cf87f
🧪 test: pay the api-read err-code coverage debt `unavailable`, `not_json` and `too_large` shipped code-read only. Each now has a test that bites when its branch is removed (both were checked against a mutated source): - `unavailable` behaviourally, over real QUIC: `app_with_ai_health` hands the test the `DbHealth` flag, so the socket can be taken down under a running app and put back — the second read answering 200 is what proves the refusal was the flag's doing. - `not_json` and both `too_large` paths at module level: no allowlisted route answers non-JSON or 8 MiB today, so a QUIC-level test would need a seam in the release binary to invent one. Two pure extractions instead — `dispatch_api` (everything after the arm check, so a stub router can be dispatched into without a listener) and `write_answer` (the framing, so the oversize-Ok downgrade can be read back off a buffer). No release behaviour moves: the refusal order is unchanged and the downgrade is the same code. The downgrade test also pins that nothing of the oversize frame reaches the wire before the refusal — `write_frame` size-checks before its first byte.
🤖 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-07-30
chore: 🧹 drop the coordination for replicas we never runAhmet Kaan Gümüş · a9cfe7b
chore: 🧹 drop the coordination for replicas we never run The backend runs as one process against one database, deployed stop-the-world. The machinery that let several of them agree was built ahead of a multi-replica rollout that stayed parked, so none of it was ever load-bearing: the boot lease elected a leader out of a field of one, the ai_worker table announced a worker to nobody, and the chat claim queue only ever claimed its own writes. Boot now migrates and seeds straight-line; a chat turn is dispatched by the handler that accepted it; the 503 gate reads the in-process registry. The retired columns and tables are unset and removed in separate batches, repair before REMOVE. What stays, with its reason corrected rather than removed: cap.rs, field_update.rs, the refcounts, the CAS retry loops and the in-process locks. Those close write skew between concurrent requests inside one process, which two replicas made worse but never caused. A turn orphaned by a restart or a panic is no longer reclaimed. It settles as timed_out within CHATBOT_PENDING_STALE_SECS. The design survives in the ledger if a second process is ever wanted.
2026-07-26
feat: 🗳️ elect the boot, and make a chat turn a claimed jobAhmet Kaan Gümüş · 0787b14
feat: 🗳️ elect the boot, and make a chat turn a claimed job Two things assumed there was only ever one process. Both stop assuming it, and both pay off on a single replica today, where a rolling restart already overlaps two containers. **The boot is elected.** Every process ran the whole migration, backfill and admin seed on startup, so two overlapping ones raced all three. A process now claims `migration_lock:boot` with a deterministic-id CREATE, renews a lease while it works, and stamps a sha256 of the SQL it applied; the others wait for that stamp and only trust it when the fingerprint is their own, so a new binary never serves on the previous one's schema. A leader that loses its lease fails its boot rather than reporting a success it no longer owns, and an abandoned lock is taken over once the lease lapses. Seeding the admin was two writes — create as a student, then promote — and a process killed between them left a student holding ADMIN_USERNAME that no later boot would ever promote, because nothing can tell that row from a stranger who registered the name. The role is now minted with the row. **A chat turn is a claimed job.** The answer used to ride on a `tokio::spawn` belonging to whichever process took the POST, so a restart orphaned it and the turn only settled at the stale horizon. The POST now just writes the pending row; a replica holding a `chat.reply` worker claims it with a conditional update and answers over its own socket. A claim left behind by a dead process expires and is retried, and a configured AI timeout is capped below that horizon so a slow inference is never reclaimed out from under itself. The gate and the dispatcher are deliberately separate: `ai_worker` is a heartbeated table that only answers "could anything, anywhere, serve this", may be stale, and never guards a write; the in-process registry owns the socket and is the only thing that decides who dispatches. hab/1 is untouched. Verified on two live replicas against one SurrealDB: a turn posted to a worker-less replica was answered by its peer, survived a restart of the other replica mid-flight, and was dispatched exactly once.
2026-07-23
✨ feat(ai): QUIC bridge for out-of-process AI servicesAhmet Kaan Gümüş · dc49954
✨ feat(ai): QUIC bridge for out-of-process AI services The AI features live in separate projects, so they need a transport. QUIC: each request rides its own bidirectional stream on the service's single long-lived connection, which puts multiplexing in the transport — no correlation-id bookkeeping, no head-of-line blocking between concurrent requests, one handshake instead of one per request. The backend listens and the services dial in, so a service can sit behind NAT, restart without the backend knowing its address, and scale out by opening a second connection (each connection is an independent worker). Protocol "hab/1", also the ALPN so an incompatible service is refused at the TLS handshake rather than one frame later. Frames are length-prefixed JSON (u32 big-endian) because the services will not be Rust; the length is checked against an 8 MiB cap before any buffer is allocated. The control stream carries Hello/Greeting and then stays open — its closure is the goodbye, so there is no heartbeat frame, and a silent death is caught by the QUIC idle timeout. Routing is least-inflight rather than round-robin: AI request costs are wildly uneven, and taking turns would pile a second long inference onto a busy worker while an idle one sits next to it. Selection and the in-flight increment happen under one lock so concurrent dispatches cannot overshoot a worker's declared max_concurrent, which a Lease releases on drop. Services authenticate with a shared token (constant-time compare); the certificate only proves the backend, and is self-signed at boot unless a PEM pair is configured. Since that regenerates per boot, GET /ai/certificate publishes it (PEM + sha256) for a service to pin — public because a server certificate is handed to every peer in the TLS handshake anyway, and 404 when the bridge is off. A service must re-fetch on every reconnect, not once at startup. Off unless AI_QUIC_ADDR is set, so the API is unchanged for deployments without AI. Set without AI_SHARED_TOKEN it refuses to boot rather than listen unauthenticated.