forge
Explore
Log in

Don't you dare go Hollow

Scope manager study questions to the school and publish its name

Browse files at this commit

20e856a55c0278c5cbec6e81d09cf64e2a18d09eAhmet Kaan GümüşParent: 777c7df
  • fix
    • scope manager study questions to the school and publish its name
Show full message
🐛 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.
.sqlx/query-a7556b35313487c902861391f5575d79c52ba5c429f24759b08164865f79f24b.jsonadded+74 -0
@@ -0,0 +1,74 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: CourseNoteId\", course AS \"course: CourseId\",\n author AS \"author: UserId\", title AS \"title: CourseNoteTitle\",\n content AS \"content: CourseNoteContent\"\n FROM course_note\n WHERE EXISTS (\n SELECT 1 FROM course_note_file\n WHERE course_note_file.course_note = course_note.id\n )\n ORDER BY id DESC",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: CourseNoteId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "course_note",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "course: CourseId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "course_note",
24+ "name": "course"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "author: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "course_note",
35+ "name": "author"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "title: CourseNoteTitle",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "course_note",
46+ "name": "title"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "content: CourseNoteContent",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "course_note",
57+ "name": "content"
58+ }
59+ }
60+ }
61+ ],
62+ "parameters": {
63+ "Left": []
64+ },
65+ "nullable": [
66+ false,
67+ false,
68+ false,
69+ false,
70+ false
71+ ]
72+ },
73+ "hash": "a7556b35313487c902861391f5575d79c52ba5c429f24759b08164865f79f24b"
74+}
README.mdmodified+5 -2
@@ -1446,6 +1446,7 @@ window filtering, before paging; negative values are a `400` naming the field.
1446 | POST | `/rag/threads/{id}/messages` | student | Ask the corpus a question: `{content}`, at most the school's `max_chatbot_message_len`. Answers `202 {message_id, status: "pending"}` the moment both rows are written — the answer itself lands later, in the reserved assistant row. `503` when no AI service offers `rag.chat`, and nothing is written; `429` + `Retry-After` over the per-user send limit. |1446 | POST | `/rag/threads/{id}/messages` | student | Ask the corpus a question: `{content}`, at most the school's `max_chatbot_message_len`. Answers `202 {message_id, status: "pending"}` the moment both rows are written — the answer itself lands later, in the reserved assistant row. `503` when no AI service offers `rag.chat`, and nothing is written; `429` + `Retry-After` over the per-user send limit. |
1447 | GET | `/rag/threads/{id}/messages/{mid}` | student | Poll one turn. The non-SSE fallback for `/stream`, reading the same row — including the projection that presents a long-stale `pending` as `failed`, so the two can never disagree about a turn's state. |1447 | GET | `/rag/threads/{id}/messages/{mid}` | student | Poll one turn. The non-SSE fallback for `/stream`, reading the same row — including the projection that presents a long-stale `pending` as `failed`, so the two can never disagree about a turn's state. |
1448 | GET | `/rag/threads/{id}/messages/{mid}/stream` | student | Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a single `done` carrying the finished message, or one `error`. The stream closes after `done`/`error` — one stream per turn, not per thread. |1448 | GET | `/rag/threads/{id}/messages/{mid}/stream` | student | Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a single `done` carrying the finished message, or one `error`. The stream closes after `done`/`error` — one stream per turn, not per thread. |
1449+| GET | `/school` | student | The school the session cookie is bound to: its uuid and display name. |
1449 | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). |1450 | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). |
1450 | POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. |1451 | POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. |
1451 | GET | `/schools/{slug}` | builder | One school by slug. |1452 | GET | `/schools/{slug}` | builder | One school by slug. |
@@ -4182,8 +4183,10 @@ The HTTP doors are `POST /rag/summarize` and `POST /rag/questions`, with a flat
4182 body: `ders` (required, non-empty), `sinif`, `pages`, `span_ids`, `scope_label`,4183 body: `ders` (required, non-empty), `sinif`, `pages`, `span_ids`, `scope_label`,
4183 and for questions `n` (default 5, at most 20), `difficulty` (default `orta`) and4184 and for questions `n` (default 5, at most 20), `difficulty` (default `orta`) and
4184 `seed_question`. Authorization is the nest's own scope derivation, applied4185 `seed_question`. Authorization is the nest's own scope derivation, applied
4185-twice: the caller's `(sınıf, ders)` pairs come from their live memberships and4186+twice: the caller's `(sınıf, ders)` pairs come from the same derivation as
4186-the body only **names a target inside them** — a pair the caller does not hold is4187+`rag.chat` (a manager or an admin gets every class-course pair in the school;
4188+everyone else, their live memberships) and the body only **names a target
4189+inside them** — a pair the caller does not hold is
4187 a `403`, and omitting `sinif` for a ders taught at more than one grade is a4190 a `403`, and omitting `sinif` for a ders taught at more than one grade is a
4188 `400`, because choosing a corpus for the caller would answer from material they4191 `400`, because choosing a corpus for the caller would answer from material they
4189 never named. The door maps the service's `soru`/`cevap`/`zorluk` onto this API's4192 never named. The door maps the service's `soru`/`cevap`/`zorluk` onto this API's
src/ai/rag.rsmodified+114 -0
@@ -11,6 +11,13 @@
11 //! unreadable answer all leave the previously stored11 //! unreadable answer all leave the previously stored
12 //! [`RagOutput`](crate::domain::rag_output::RagOutput) rows exactly as they12 //! [`RagOutput`](crate::domain::rag_output::RagOutput) rows exactly as they
13 //! are. A slightly stale index beats no index.13 //! are. A slightly stale index beats no index.
14+//!
15+//! A service restart wipes an in-memory index and does not replay it.
16+//! [`spawn_index_replay`] runs when a worker that offers `rag.index`
17+//! registers, and calls [`index_course_note`] for every course note that has
18+//! files, in every active school. The spawn returns immediately: the QUIC
19+//! handshake must not wait on it. A chatbot, zeka, or podcast registration
20+//! does not offer `rag.index`, so it does not replay.
14 21
15 use serde::{Deserialize, Serialize};22 use serde::{Deserialize, Serialize};
16 23
@@ -218,9 +225,96 @@ pub fn spawn_index(state: &AppState, tenant: &ResolvedTenant, note: CourseNote)
218 tokio::spawn(async move { index_course_note(&state, &tenant, &note).await });225 tokio::spawn(async move { index_course_note(&state, &tenant, &note).await });
219 }226 }
220 227
228+/// Whether a worker that just registered should have the course-note index
229+/// replayed. Only `rag.index` does. `rag.chat`, the chatbot, zeka, and the
230+/// podcast worker do not — their registration must not walk every school.
231+pub(crate) fn should_replay_index(capabilities: &[String]) -> bool {
232+ capabilities
233+ .iter()
234+ .any(|capability| capability == AI_RAG_INDEX_CAPABILITY)
235+}
236+
237+/// [`replay_indexed_notes`] off the handshake path. Returns as soon as the
238+/// task is spawned. `state.ai` must already be the bridge that just
239+/// registered the worker; `state.db` may still be the control database —
240+/// each school is swapped in before [`index_course_note`].
241+pub(crate) fn spawn_index_replay(state: AppState) {
242+ tokio::spawn(async move {
243+ replay_indexed_notes(state).await;
244+ });
245+}
246+
247+/// Re-dispatch [`index_course_note`] for every course note that has files, in
248+/// every active school. One note at a time: a replay is a catch-up, not a
249+/// stampede, and the worker's own concurrency cap is what bounds a single
250+/// dispatch.
251+async fn replay_indexed_notes(state: AppState) {
252+ let directory = match crate::db::insight::active_schools(state.tenants.control()).await {
253+ Ok(directory) => directory,
254+ Err(err) => {
255+ tracing::warn!("rag.index replay could not list active schools: {err}");
256+ return;
257+ }
258+ };
259+ for slug in directory.schools {
260+ replay_school(&state, &slug).await;
261+ }
262+}
263+
264+async fn replay_school(state: &AppState, slug: &str) {
265+ let slug = match crate::tenant::Slug::try_new(slug) {
266+ Ok(slug) => slug,
267+ Err(err) => {
268+ tracing::warn!("rag.index replay skipped an unreadable school slug: {err}");
269+ return;
270+ }
271+ };
272+ let tenant = match state.tenants.resolve(&slug).await {
273+ Ok(tenant) => tenant,
274+ Err(err) => {
275+ tracing::warn!("rag.index replay skipped `{slug}`: {err}");
276+ return;
277+ }
278+ };
279+ if !tenant.modules.contains(Module::Chatbot) {
280+ tracing::debug!("rag.index replay skipped `{slug}`: the school has no chatbot module");
281+ return;
282+ }
283+ let notes = match crate::db::course_note::list_with_files(&tenant.db).await {
284+ Ok(notes) => notes,
285+ Err(err) => {
286+ tracing::warn!("rag.index replay could not list course notes in `{slug}`: {err}");
287+ return;
288+ }
289+ };
290+ if notes.is_empty() {
291+ tracing::debug!("rag.index replay: `{slug}` has no course notes with files");
292+ return;
293+ }
294+ tracing::info!(
295+ school = %slug,
296+ notes = notes.len(),
297+ "replaying rag.index for course notes with files"
298+ );
299+ // `index_course_note` writes through `state.db`, which on the request
300+ // path is the shadow school's database. The root handed in here is the
301+ // control database, so the school handle has to be swapped in first.
302+ let school_state = AppState {
303+ db: tenant.db.clone(),
304+ ..state.clone()
305+ };
306+ for note in &notes {
307+ index_course_note(&school_state, &tenant, note).await;
308+ }
309+}
310+
221 #[cfg(test)]311 #[cfg(test)]
222 mod tests {312 mod tests {
223 use super::*;313 use super::*;
314+ use crate::constant::{
315+ AI_CHAT_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY,
316+ AI_RAG_CHAT_CAPABILITY,
317+ };
224 use serde_json::json;318 use serde_json::json;
225 319
226 #[test]320 #[test]
@@ -267,4 +361,24 @@ mod tests {
267 .unwrap();361 .unwrap();
268 assert!(bare.files.is_empty());362 assert!(bare.files.is_empty());
269 }363 }
364+
365+ /// Chatbot, zeka, podcast, and even `rag.chat` must not replay. A worker
366+ /// that offers `rag.index` alongside something else still does.
367+ #[test]
368+ fn index_replay_runs_only_when_the_worker_offers_rag_index() {
369+ assert!(should_replay_index(&[AI_RAG_INDEX_CAPABILITY.to_string()]));
370+ assert!(should_replay_index(&[
371+ AI_CHAT_CAPABILITY.to_string(),
372+ AI_RAG_INDEX_CAPABILITY.to_string(),
373+ ]));
374+ assert!(!should_replay_index(&[AI_CHAT_CAPABILITY.to_string()]));
375+ assert!(!should_replay_index(&[AI_RAG_CHAT_CAPABILITY.to_string()]));
376+ assert!(!should_replay_index(&[
377+ AI_INSIGHT_STUDENT_CAPABILITY.to_string()
378+ ]));
379+ assert!(!should_replay_index(&[
380+ AI_PODCAST_SUBMIT_CAPABILITY.to_string()
381+ ]));
382+ assert!(!should_replay_index(&[]));
383+ }
270 }384 }
src/ai/rag_chat.rsmodified+1 -1
@@ -134,7 +134,7 @@ pub struct RagChatReplyPayload {
134 ///134 ///
135 /// The request is built from what the session already proves — `asker` and135 /// The request is built from what the session already proves — `asker` and
136 /// `asker_role` are read from the live session by the caller, never taken from136 /// `asker_role` are read from the live session by the caller, never taken from
137-/// a body, and `scope` from the asker's own memberships — and the reply is137+/// a body, and `scope` from [`crate::service::rag_scope`] — and the reply is
138 /// mapped into what a message row can hold: the answer text, the abstention,138 /// mapped into what a message row can hold: the answer text, the abstention,
139 /// and the citations whose corpus `doc_id` resolves to a course-note file the139 /// and the citations whose corpus `doc_id` resolves to a course-note file the
140 /// asker may view.140 /// asker may view.
src/ai/server.rsmodified+47 -4
@@ -23,7 +23,7 @@ use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency};
23 use crate::ai::tls;23 use crate::ai::tls;
24 use crate::constant::{24 use crate::constant::{
25 AI_BLOB_WRITE_STALL_SECS, AI_HANDSHAKE_TIMEOUT_SECS, AI_MAX_FRAME_BYTES, AI_PROTOCOL,25 AI_BLOB_WRITE_STALL_SECS, AI_HANDSHAKE_TIMEOUT_SECS, AI_MAX_FRAME_BYTES, AI_PROTOCOL,
26- REQUEST_TIMEOUT_SECS,26+ AI_RAG_INDEX_CAPABILITY, REQUEST_TIMEOUT_SECS,
27 };27 };
28 use crate::database::Database;28 use crate::database::Database;
29 29
@@ -32,6 +32,7 @@ use crate::domain::monotonic_id::next_uuid;
32 use crate::domain::user::{User, UserId};32 use crate::domain::user::{User, UserId};
33 use crate::error::AppError;33 use crate::error::AppError;
34 use crate::module::Module;34 use crate::module::Module;
35+use crate::state::AppState;
35 use crate::telemetry::Metrics;36 use crate::telemetry::Metrics;
36 use crate::service::course::can_view_course;37 use crate::service::course::can_view_course;
37 use crate::tenant::{ResolvedTenant, Slug, Tenants};38 use crate::tenant::{ResolvedTenant, Slug, Tenants};
@@ -122,6 +123,11 @@ struct Inner {
122 /// process's instruments are built with the router, after the listener is123 /// process's instruments are built with the router, after the listener is
123 /// bound.124 /// bound.
124 metrics: OnceLock<Metrics>,125 metrics: OnceLock<Metrics>,
126+ /// Root [`AppState`] with `ai` cleared, armed by [`AiBridge::arm_api`].
127+ /// A `rag.index` registration replays the course-note index through it.
128+ /// `ai` stays `None` here so this lock does not cycle back into the
129+ /// bridge that holds it; the replay fills the bridge in on a clone.
130+ replay: OnceLock<AppState>,
125 }131 }
126 132
127 impl Inner {133 impl Inner {
@@ -187,6 +193,7 @@ impl AiBridge {
187 request_timeout: config.request_timeout,193 request_timeout: config.request_timeout,
188 endpoint,194 endpoint,
189 metrics: OnceLock::new(),195 metrics: OnceLock::new(),
196+ replay: OnceLock::new(),
190 });197 });
191 tracing::info!(198 tracing::info!(
192 "AI bridge listening on {bound} (protocol {AI_PROTOCOL}, cert sha256 {fingerprint})"199 "AI bridge listening on {bound} (protocol {AI_PROTOCOL}, cert sha256 {fingerprint})"
@@ -376,6 +383,7 @@ impl AiBridge {
376 tenants: Tenants,383 tenants: Tenants,
377 files_path: std::path::PathBuf,384 files_path: std::path::PathBuf,
378 metrics: Metrics,385 metrics: Metrics,
386+ state: &AppState,
379 ) {387 ) {
380 // Not warned about on a second call: the instruments are the same388 // Not warned about on a second call: the instruments are the same
381 // process-global ones either way, so re-arming changes nothing.389 // process-global ones either way, so re-arming changes nothing.
@@ -392,6 +400,17 @@ impl AiBridge {
392 {400 {
393 tracing::warn!("the AI bridge api path was already armed — keeping the first router");401 tracing::warn!("the AI bridge api path was already armed — keeping the first router");
394 }402 }
403+ // `ai` cleared: storing the caller's state as-is would cycle
404+ // AppState -> bridge -> this lock -> AppState, and the replay fills
405+ // the bridge back in on a clone. A worker that registered in the
406+ // boot window, before this arm, already missed its own kick.
407+ let mut rooted = state.clone();
408+ rooted.ai = None;
409+ if self.inner.replay.set(rooted).is_err() {
410+ tracing::warn!("rag index replay was already armed — keeping the first state");
411+ } else if self.has_capability(AI_RAG_INDEX_CAPABILITY) {
412+ spawn_index_replay_if_armed(&self.inner);
413+ }
395 }414 }
396 415
397 /// Stop listening and close every service connection.416 /// Stop listening and close every service connection.
@@ -442,7 +461,7 @@ async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection) {
442 )461 )
443 .await;462 .await;
444 463
445- let (worker_id, service, _control) = match handshake {464+ let (worker_id, service, capabilities, _control) = match handshake {
446 Ok(Ok(registered)) => registered,465 Ok(Ok(registered)) => registered,
447 Ok(Err(())) => return,466 Ok(Err(())) => return,
448 Err(_) => {467 Err(_) => {
@@ -452,6 +471,12 @@ async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection) {
452 return;471 return;
453 }472 }
454 };473 };
474+ // The welcome is already on the wire. Spawned, not awaited: walking
475+ // every school's notes must not hold the handshake, and a registration
476+ // that does not offer `rag.index` does not enter.
477+ if crate::ai::rag::should_replay_index(&capabilities) {
478+ spawn_index_replay_if_armed(&inner);
479+ }
455 480
456 // The control stream is held open (`_control`) for the connection's life.481 // The control stream is held open (`_control`) for the connection's life.
457 // Nothing more is read on it: its closure, not a heartbeat frame, is how a482 // Nothing more is read on it: its closure, not a heartbeat frame, is how a
@@ -1202,7 +1227,7 @@ type Control = (quinn::SendStream, quinn::RecvStream);
1202 async fn register(1227 async fn register(
1203 inner: &Inner,1228 inner: &Inner,
1204 conn: &quinn::Connection,1229 conn: &quinn::Connection,
1205-) -> Result<(String, String, Control), ()> {1230+) -> Result<(String, String, Vec<String>, Control), ()> {
1206 let (mut send, mut recv) = match conn.accept_bi().await {1231 let (mut send, mut recv) = match conn.accept_bi().await {
1207 Ok(streams) => streams,1232 Ok(streams) => streams,
1208 Err(e) => {1233 Err(e) => {
@@ -1288,7 +1313,7 @@ async fn register(
1288 max_concurrent,1313 max_concurrent,
1289 "AI service registered"1314 "AI service registered"
1290 );1315 );
1291- Ok((worker_id, hello.service, (send, recv)))1316+ Ok((worker_id, hello.service, hello.capabilities, (send, recv)))
1292 }1317 }
1293 1318
1294 /// Send a rejection the service can act on, then close. Best-effort: a peer1319 /// Send a rejection the service can act on, then close. Best-effort: a peer
@@ -1311,6 +1336,24 @@ async fn refuse(
1311 conn.close(1u32.into(), message.as_bytes());1336 conn.close(1u32.into(), message.as_bytes());
1312 }1337 }
1313 1338
1339+/// Re-index course notes with files, off the handshake path.
1340+///
1341+/// No-op when [`AiBridge::arm_api`] has not stored the root state yet. A
1342+/// worker that dials in during that window is covered by the arm-time kick,
1343+/// once the state exists and the worker is already in the registry.
1344+fn spawn_index_replay_if_armed(inner: &Arc<Inner>) {
1345+ let Some(mut state) = inner.replay.get().cloned() else {
1346+ tracing::warn!(
1347+ "rag.index worker registered before replay state was armed; skipping index replay"
1348+ );
1349+ return;
1350+ };
1351+ state.ai = Some(AiBridge {
1352+ inner: Arc::clone(inner),
1353+ });
1354+ crate::ai::rag::spawn_index_replay(state);
1355+}
1356+
1314 /// Compare two secrets without leaking their common prefix length through1357 /// Compare two secrets without leaking their common prefix length through
1315 /// timing. Length difference is not secret (and cannot be hidden here), but1358 /// timing. Length difference is not secret (and cannot be hidden here), but
1316 /// the byte comparison must not short-circuit.1359 /// the byte comparison must not short-circuit.
src/db/course_note.rsmodified+24 -0
@@ -79,6 +79,30 @@ pub async fn list_for_course(
79 .await79 .await
80 }80 }
81 81
82+/// Every course note that has at least one attachment, newest first.
83+///
84+/// One statement: the attachment table is filtered in the `EXISTS`, not
85+/// queried once per note. A note with no files is absent — a `rag.index`
86+/// replay has nothing to send for it. `file_count` is not the predicate:
87+/// the file rows are the ground truth, and the counter is only a cap.
88+pub async fn list_with_files(db: &Database) -> Result<Vec<CourseNote>, AppError> {
89+ let notes = sqlx::query_as!(
90+ CourseNote,
91+ r#"SELECT id AS "id: CourseNoteId", course AS "course: CourseId",
92+ author AS "author: UserId", title AS "title: CourseNoteTitle",
93+ content AS "content: CourseNoteContent"
94+ FROM course_note
95+ WHERE EXISTS (
96+ SELECT 1 FROM course_note_file
97+ WHERE course_note_file.course_note = course_note.id
98+ )
99+ ORDER BY id DESC"#,
100+ )
101+ .fetch_all(db)
102+ .await?;
103+ Ok(notes)
104+}
105+
82 /// Request-scoped: no lock spans the handler's read and this write, so an106 /// Request-scoped: no lock spans the handler's read and this write, so an
83 /// omitted field (`None`) is not written at all. Passing the snapshot's107 /// omitted field (`None`) is not written at all. Passing the snapshot's
84 /// value back instead would revert a concurrent edit of that field —108 /// value back instead would revert a concurrent edit of that field —
src/lib.rsmodified+4 -1
@@ -54,9 +54,10 @@ use crate::web::module_gate::gate;
54 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),54 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),
55 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). `GET /ai/capabilities` (authenticated) lists what connected services are serving right now — one entry per capability with its worker count and in-flight requests — and answers `200 {enabled: false, capabilities: []}` when the bridge is off: a discovery read showing *that* there is no AI fleet, not a dependency probe. See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),55 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). `GET /ai/capabilities` (authenticated) lists what connected services are serving right now — one entry per capability with its worker count and in-flight requests — and answers `200 {enabled: false, capabilities: []}` when the bridge is off: a discovery read showing *that* there is no AI fleet, not a dependency probe. See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
56 (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),56 (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),
57+ (name = "school", description = "The school the session cookie is bound to. `GET /school` returns `{id, name}` — the registry uuid and the display name — to every authenticated role, parent included. It is not login and not the vendor registry: a builder cookie is `401` here, exactly as a school cookie is `401` on `/schools`."),
57 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),58 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),
58 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),59 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
59- (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sınıf, ders)` pairs, derived on each request from their live memberships — their şubeler' instances, a linked parent's children, and the school-wide club/etüt memberships they hold (which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it. Two **study** doors are one-shot and synchronous rather than threaded: `POST /rag/summarize` returns a summary of one page/span range and `POST /rag/questions` returns a set of practice questions (plus their range-bounded answers) over one — the artifact is the answer, so nothing is stored and there is no thread or poll. Their body names only a *target within* the asker's own derived pairs (the body's `sinif` plus `ders`): a pair the caller does not hold is `403`, and omitting `sinif` for a ders taught at more than one grade is `400` — the backend never picks a corpus for the caller. Both answer `503` when no AI service offers `rag.summarize`/`rag.questions`, and an `abstained: true` reply with a `reason` is a complete `200`, exactly as on a chat turn. Each waits on its dispatch under a 25 s deadline, deliberately inside the middleware's own 30 s envelope — a dropped handler would answer with prose written for a request that may have written something."),60+ (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to `(sınıf, ders)` pairs derived by the server — a manager or an admin gets every class-course pair in the school, everyone else their own memberships (a linked parent's children, and the school-wide club/etüt memberships they hold, which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it. Two **study** doors are one-shot and synchronous rather than threaded: `POST /rag/summarize` returns a summary of one page/span range and `POST /rag/questions` returns a set of practice questions (plus their range-bounded answers) over one — the artifact is the answer, so nothing is stored and there is no thread or poll. Their body names only a *target within* the asker's own derived pairs (the body's `sinif` plus `ders`): a pair the caller does not hold is `403`, and omitting `sinif` for a ders taught at more than one grade is `400` — the backend never picks a corpus for the caller. Both answer `503` when no AI service offers `rag.summarize`/`rag.questions`, and an `abstained: true` reply with a `reason` is a complete `200`, exactly as on a chat turn. Each waits on its dispatch under a 25 s deadline, deliberately inside the middleware's own 30 s envelope — a dropped handler would answer with prose written for a request that may have written something."),
60 (name = "insights", description = "ZEKA's computed student insights. The `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot, but it does **not** touch a school database: the backend owns every statement against the `zeka_*` tables, and the service calls the backend by name (`insight.*` capabilities on a client-initiated stream — see `src/ai/insight.rs`) to have its computed rows written and read back. So this nest reads what the service computed and asks it to compute on demand, and its write doors are the same operations the bridge serves: `POST /insights/summaries`, `/recommendations`, `/segments`, `/profiles` and `/runs` store one batch each (manager+, one call one transaction, rows about students school-wide), `GET /insights/pending` is the students the freshest run left pending, and `POST /insights/sweep` / `POST /insights/purge` are retention and graduation housekeeping — all scoped to the caller's own school by the nest's extractors, and none of them takes a school, a database or a query in its body. `GET /insights/schools` is the exception and is not this nest's usual principal: the active-school directory names every customer, so it is mounted on the **builder** principal outside the school gate (a school session answers `401`), exactly like the vendor surface's `GET /schools`. `GET /insights/me` is the caller's own view: a student's summary, their own recommendation cards and their segment profile — and **never** the attention list about themselves, which is a teacher's tool and is not returned to a student or to a linked parent. `GET /insights/students/{id}` is the observer's view of one student — teacher+ narrowed to the students they actually reach through a shared class×course instance, or a parent holding a live link — adding the attention list and the caller's own cards about that student; anyone else reads `404`, never `403`. `POST /insights/students/{id}` and `POST /insights/refresh` (manager+) queue a recompute through the bridge and answer `202` — the compute lands in the service's own rows, so a client polls the read routes; `GET /insights/runs` (manager+) is the run ledger, newest first. Both dispatch doors answer `503` when no service offers the capability, and nothing is queued. Expired and dismissed cards are filtered out of every card read, segment rows below 30 answers (`confidence: none`) are filtered out of every profile read, and a card's `about` is never returned to a student caller."),61 (name = "insights", description = "ZEKA's computed student insights. The `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot, but it does **not** touch a school database: the backend owns every statement against the `zeka_*` tables, and the service calls the backend by name (`insight.*` capabilities on a client-initiated stream — see `src/ai/insight.rs`) to have its computed rows written and read back. So this nest reads what the service computed and asks it to compute on demand, and its write doors are the same operations the bridge serves: `POST /insights/summaries`, `/recommendations`, `/segments`, `/profiles` and `/runs` store one batch each (manager+, one call one transaction, rows about students school-wide), `GET /insights/pending` is the students the freshest run left pending, and `POST /insights/sweep` / `POST /insights/purge` are retention and graduation housekeeping — all scoped to the caller's own school by the nest's extractors, and none of them takes a school, a database or a query in its body. `GET /insights/schools` is the exception and is not this nest's usual principal: the active-school directory names every customer, so it is mounted on the **builder** principal outside the school gate (a school session answers `401`), exactly like the vendor surface's `GET /schools`. `GET /insights/me` is the caller's own view: a student's summary, their own recommendation cards and their segment profile — and **never** the attention list about themselves, which is a teacher's tool and is not returned to a student or to a linked parent. `GET /insights/students/{id}` is the observer's view of one student — teacher+ narrowed to the students they actually reach through a shared class×course instance, or a parent holding a live link — adding the attention list and the caller's own cards about that student; anyone else reads `404`, never `403`. `POST /insights/students/{id}` and `POST /insights/refresh` (manager+) queue a recompute through the bridge and answer `202` — the compute lands in the service's own rows, so a client polls the read routes; `GET /insights/runs` (manager+) is the run ledger, newest first. Both dispatch doors answer `503` when no service offers the capability, and nothing is queued. Expired and dismissed cards are filtered out of every card read, segment rows below 30 answers (`confidence: none`) are filtered out of every profile read, and a card's `about` is never returned to a student caller."),
61 (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — and the **backend owns the job**, not just the HTTP surface. `POST /podcast/jobs` (`{source_id, format?}`) resolves the note's newest `application/pdf` attachment — the blob key the dispatch hands the service as `source_key`, so the service opens `<media root>/<school>/<source_key>` — refusing `409 source_missing` when the note has no PDF or its bytes are missing from this host, then mints the job id, writes the row, dispatches `podcast.submit` to the service and answers `202` with `{job_id, state, eta_secs}`; `GET /podcast/jobs/{id}` polls the backend's own row `{state, stage, progress, error_code}` with no service round trip, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, format}` (`409` while it is still running), `GET /podcast/jobs/{id}/audio` streams the episode the service uploaded into this school's own blob directory, and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`; a terminal job answers without the service); `GET /podcast/jobs` is the caller's own history, newest first (`?limit=&offset=`), each row carrying the title of the note it narrated. The service reports every transition back through the `podcast.report` capability and uploads the finished mp3 — so status, result and audio keep answering while the service is down or restarted, and a job nobody is updating reads as failed/interrupted after an ETA-scaled window. Submit and cancel refuse `503` when no worker is connected; none of the four read doors needs one (404 for an unknown or foreign job, 410 past the retention window, 409 before the job is done or when its blob is missing from this host)."),62 (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — and the **backend owns the job**, not just the HTTP surface. `POST /podcast/jobs` (`{source_id, format?}`) resolves the note's newest `application/pdf` attachment — the blob key the dispatch hands the service as `source_key`, so the service opens `<media root>/<school>/<source_key>` — refusing `409 source_missing` when the note has no PDF or its bytes are missing from this host, then mints the job id, writes the row, dispatches `podcast.submit` to the service and answers `202` with `{job_id, state, eta_secs}`; `GET /podcast/jobs/{id}` polls the backend's own row `{state, stage, progress, error_code}` with no service round trip, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, format}` (`409` while it is still running), `GET /podcast/jobs/{id}/audio` streams the episode the service uploaded into this school's own blob directory, and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`; a terminal job answers without the service); `GET /podcast/jobs` is the caller's own history, newest first (`?limit=&offset=`), each row carrying the title of the note it narrated. The service reports every transition back through the `podcast.report` capability and uploads the finished mp3 — so status, result and audio keep answering while the service is down or restarted, and a job nobody is updating reads as failed/interrupted after an ETA-scaled window. Submit and cancel refuse `503` when no worker is connected; none of the four read doors needs one (404 for an unknown or foreign job, 410 past the retention window, 409 before the job is done or when its blob is missing from this host)."),
62 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),63 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
@@ -155,6 +156,7 @@ pub fn build_router(state: AppState) -> Router {
155 .routes(routes!(server_time))156 .routes(routes!(server_time))
156 .merge(web::limits::routes())157 .merge(web::limits::routes())
157 .merge(web::modules::routes())158 .merge(web::modules::routes())
159+ .merge(web::school::routes())
158 .nest("/ai", web::ai::routes())160 .nest("/ai", web::ai::routes())
159 .nest("/auth", web::auth::routes(&state))161 .nest("/auth", web::auth::routes(&state))
160 .merge(web::builder::routes(&state))162 .merge(web::builder::routes(&state))
@@ -282,6 +284,7 @@ pub fn build_router(state: AppState) -> Router {
282 state.tenants.clone(),284 state.tenants.clone(),
283 state.files_path.clone(),285 state.files_path.clone(),
284 metrics.clone(),286 metrics.clone(),
287+ &state,
285 );288 );
286 }289 }
287 290
src/service/rag_scope.rsmodified+100 -22
@@ -4,8 +4,8 @@
4 //! separately would cross-product into combinations the asker never named4 //! separately would cross-product into combinations the asker never named
5 //! ([`crate::constant::MAX_RAG_SCOPE_PAIRS`]) — so every question needs the set5 //! ([`crate::constant::MAX_RAG_SCOPE_PAIRS`]) — so every question needs the set
6 //! of pairs its asker is allowed to retrieve from, and that set is derived6 //! of pairs its asker is allowed to retrieve from, and that set is derived
7-//! *here*, from the asker's own rows, never from the request body: a scope a7+//! *here*, never from the request body: a scope a client could name is a
8-//! client could name is a scope a client could widen.8+//! scope a client could widen.
9 //!9 //!
10 //! The derivation is the school's own visibility rules, not a second copy of10 //! The derivation is the school's own visibility rules, not a second copy of
11 //! them. A student's or a teacher's pairs are the courses their11 //! them. A student's or a teacher's pairs are the courses their
@@ -15,14 +15,21 @@
15 //! school-scoped course belongs to no section. A parent has no sections of15 //! school-scoped course belongs to no section. A parent has no sections of
16 //! their own, so their scope is their linked children's, read child by child16 //! their own, so their scope is their linked children's, read child by child
17 //! through the same reader: what a parent may ask about is exactly what their17 //! through the same reader: what a parent may ask about is exactly what their
18-//! children could be taught.18+//! children could be taught. A manager or an admin is none of those people:
19+//! their scope is every class-course instance in the school
20+//! ([`crate::db::class_group::list_all`] plus
21+//! [`crate::db::class_course::list_for_class_ids`]), not the rows their own
22+//! account happens to hold. An empty personal membership is not an empty
23+//! school, and it is not a legal empty scope.
19 //!24 //!
20 //! Two consequences are deliberate. An empty scope is legal and returned as an25 //! Two consequences are deliberate. An empty scope is legal and returned as an
21-//! empty list — the service answers an unscopable question by abstaining, and a26+//! empty list when the asker really has nothing to retrieve from — a student
22-//! `400` here would refuse questions the asker is entitled to ask. And a union27+//! in no section, a teacher with no assignment, a parent with no linked child,
23-//! over the cap is **refused**, never narrowed: dropping pairs would answer a28+//! a manager of a school that has no class-course instance. The service
24-//! question scoped to corpora the asker did not name, which is worse than no29+//! answers an unscopable question by abstaining, and a `400` here would refuse
25-//! answer at all.30+//! questions the asker is entitled to ask. And a union over the cap is
31+//! **refused**, never narrowed: dropping pairs would answer a question scoped
32+//! to corpora the asker did not name, which is worse than no answer at all.
26 33
27 use std::collections::{HashMap, HashSet};34 use std::collections::{HashMap, HashSet};
28 35
@@ -40,25 +47,34 @@ use crate::error::{AppError, ValidationError};
40 /// first-seen order and deduped — one entry per distinct pair.47 /// first-seen order and deduped — one entry per distinct pair.
41 ///48 ///
42 /// `role` is the caller's **live** session role, the same value the49 /// `role` is the caller's **live** session role, the same value the
43-/// `rag.chat` payload carries: the instance arm is the asker's own rows for50+/// `rag.chat` payload carries. A manager or an admin reads every class-course
44-/// everyone but a parent (a section membership, a homeroom column and a51+/// instance in the school. Everyone else reads their own rows: a section
45-/// teaching assignment are all keyed on live roles anyway), and the parent52+/// membership, a homeroom column and a teaching assignment are all keyed on
46-/// arm is the one that has to be chosen by role, because a parent's own53+/// the live role, and the parent arm is chosen by role because a parent's own
47 /// sections do not exist.54 /// sections do not exist.
48 ///55 ///
49-/// The instance arm reads its rows through [`super::instance::visible_instances`]56+/// The non-manager instance arm reads its rows through
50-/// and the two lookup tables (the class sections the pairs sit in and the57+/// [`super::instance::visible_instances`], and both arms finish with the same
51-/// titles of every course named) in one batch read each — never one query per58+/// two lookup tables (the class sections the pairs sit in and the titles of
52-/// instance: a teacher can be assigned to dozens of sections, and a per-row59+/// every course named) in one batch read each — never one query per instance.
53-/// lookup would spend the request's whole budget before the AI service is even60+/// A teacher can be assigned to dozens of sections, and a per-row lookup would
54-/// called.61+/// spend the request's whole budget before the AI service is even called.
55 pub async fn for_user(62 pub async fn for_user(
56 db: &Database,63 db: &Database,
57 user: &User,64 user: &User,
58 role: Role,65 role: Role,
59 ) -> Result<Vec<RagScopePair>, AppError> {66 ) -> Result<Vec<RagScopePair>, AppError> {
60 let mut instances: Vec<ClassCourse> = Vec::new();67 let mut instances: Vec<ClassCourse> = Vec::new();
61- if role == Role::Parent {68+ if role.at_least(Role::Manager) {
69+ // A manager or an admin asks about the school, not about the rows
70+ // their own account holds. A system admin is in no section, no
71+ // homeroom and no teaching assignment, so the personal read is empty
72+ // — and an empty personal read is not an empty school.
73+ let (classes, _) = crate::db::class_group::list_all(db, None, None, 0).await?;
74+ let class_ids: Vec<ClassGroupId> =
75+ classes.iter().map(|class| class.get_id().clone()).collect();
76+ instances = crate::db::class_course::list_for_class_ids(db, &class_ids).await?;
77+ } else if role == Role::Parent {
62 // A parent's scope is what their children are taught — read through78 // A parent's scope is what their children are taught — read through
63 // the same visibility rule, one child at a time because the rule79 // the same visibility rule, one child at a time because the rule
64 // keys on the person asking. A link whose student side changed role80 // keys on the person asking. A link whose student side changed role
@@ -86,11 +102,15 @@ pub async fn for_user(
86 }102 }
87 // The school-scoped courses the asker joined directly (club, supervised103 // The school-scoped courses the asker joined directly (club, supervised
88 // study). Every role may hold one — the table's own gate is the student104 // study). Every role may hold one — the table's own gate is the student
89- // role, so for staff this read is simply empty.105+ // role, so for staff this read is simply empty. A manager's scope is the
90- let memberships =106+ // school's instances, not this personal list, so the read is skipped.
107+ let memberships = if role.at_least(Role::Manager) {
108+ Vec::new()
109+ } else {
91 crate::db::course_membership::list_for_user(db, user.get_id(), None, 0)110 crate::db::course_membership::list_for_user(db, user.get_id(), None, 0)
92 .await?111 .await?
93- .0;112+ .0
113+ };
94 114
95 // One batch read per lookup, over every id the two arms named: the class115 // One batch read per lookup, over every id the two arms named: the class
96 // sections decide each instance's grade, and the courses carry the titles116 // sections decide each instance's grade, and the courses carry the titles
@@ -360,4 +380,62 @@ mod tests {
360 let scope = for_user(&db, &student, Role::Student).await.unwrap();380 let scope = for_user(&db, &student, Role::Student).await.unwrap();
361 assert_eq!(scope, vec![pair(Some("6"), "Matematik")]);381 assert_eq!(scope, vec![pair(Some("6"), "Matematik")]);
362 }382 }
383+
384+ /// A manager or an admin with no personal class row still scopes every
385+ /// class-course pair in the school. A student or a teacher with none does
386+ /// not: their empty membership stays an empty scope. Two sections at one
387+ /// grade teaching one subject are still one pair — the cap refuses a
388+ /// union, it does not get a duplicate slot.
389+ #[tokio::test]
390+ async fn a_manager_with_no_membership_scopes_the_whole_school() {
391+ let (db, _leases) = crate::database::init_test_db().await;
392+ let manager = person(&db, "ragscope-manager", Role::Manager).await;
393+ let admin = person(&db, "ragscope-admin", Role::Admin).await;
394+ let student = person(&db, "ragscope-empty-student", Role::Student).await;
395+ let teacher = person(&db, "ragscope-empty-teacher", Role::Teacher).await;
396+ let grade_eight_a = graded_class(&db, "8-A", "8").await;
397+ let grade_eight_b = graded_class(&db, "8-B", "8").await;
398+ let grade_nine = graded_class(&db, "9-A", "9").await;
399+ attach(&db, &grade_eight_a, "Biology").await;
400+ attach(&db, &grade_eight_b, "Biology").await;
401+ attach(&db, &grade_nine, "Chemistry").await;
402+
403+ let expected = vec![
404+ (Some("8".to_owned()), "Biology".to_owned()),
405+ (Some("9".to_owned()), "Chemistry".to_owned()),
406+ ];
407+ let manager_scope = for_user(&db, &manager, Role::Manager).await.unwrap();
408+ let admin_scope = for_user(&db, &admin, Role::Admin).await.unwrap();
409+ assert_eq!(pair_keys(&manager_scope), expected);
410+ assert_eq!(pair_keys(&admin_scope), expected);
411+ assert_eq!(
412+ manager_scope.len(),
413+ 2,
414+ "the repeated grade-8 subject is one pair"
415+ );
416+ assert!(
417+ for_user(&db, &student, Role::Student)
418+ .await
419+ .unwrap()
420+ .is_empty(),
421+ "a student with no membership still has an empty scope"
422+ );
423+ assert!(
424+ for_user(&db, &teacher, Role::Teacher)
425+ .await
426+ .unwrap()
427+ .is_empty(),
428+ "a teacher with no assignment still has an empty scope"
429+ );
430+ }
431+
432+ /// First-seen order is the wire order; the assertion compares the set.
433+ fn pair_keys(pairs: &[RagScopePair]) -> Vec<(Option<String>, String)> {
434+ let mut keys: Vec<_> = pairs
435+ .iter()
436+ .map(|pair| (pair.sinif.clone(), pair.ders.clone()))
437+ .collect();
438+ keys.sort();
439+ keys
440+ }
363 }441 }
src/web/mod.rsmodified+1 -0
@@ -36,6 +36,7 @@ pub mod pomodoro;
36 pub mod questions;36 pub mod questions;
37 pub mod rag;37 pub mod rag;
38 pub mod room;38 pub mod room;
39+pub mod school;
39 pub mod sessions;40 pub mod sessions;
40 pub mod settings;41 pub mod settings;
41 pub mod subjects;42 pub mod subjects;
src/web/rag.rsmodified+22 -15
@@ -6,8 +6,9 @@
6 //! thread, the payload format, and the last look at the reply before it is6 //! thread, the payload format, and the last look at the reply before it is
7 //! stored. There are no intent or rule tables, and every thread is private to7 //! stored. There are no intent or rule tables, and every thread is private to
8 //! its owner. What differs is the **scope**: every question carries the8 //! its owner. What differs is the **scope**: every question carries the
9-//! `(class, course)` pairs the corpus is routed by, derived server-side from the9+//! `(class, course)` pairs the corpus is routed by, derived server-side
10-//! asker's own memberships ([`crate::service::rag_scope`]) and never from the10+//! ([`crate::service::rag_scope`]: a manager or an admin gets every class-course
11+//! pair in the school, everyone else their own memberships) and never from the
11 //! request body, and every citation the service returns is resolved here to12 //! request body, and every citation the service returns is resolved here to
12 //! the course-note file that owns the cited document — the `doc_id` only the13 //! the course-note file that owns the cited document — the `doc_id` only the
13 //! backend can turn into something a reader can open.14 //! backend can turn into something a reader can open.
@@ -438,7 +439,7 @@ async fn list_messages(
438 /// thread is a `404` and is never charged), then the per-user rate limit (a439 /// thread is a `404` and is never charged), then the per-user rate limit (a
439 /// refused turn leaves no trace), then availability (so an unavailable service440 /// refused turn leaves no trace), then availability (so an unavailable service
440 /// produces a `503` and no dead pending row), then the scope the question is441 /// produces a `503` and no dead pending row), then the scope the question is
441-/// asked under — derived from the asker's own memberships, never from the442+/// asked under — derived by [`crate::service::rag_scope`], never from the
442 /// body. Once the rows are written the turn always settles: the answering task443 /// body. Once the rows are written the turn always settles: the answering task
443 /// stamps `complete`/`failed`, a reader projects a long-stale `pending` as444 /// stamps `complete`/`failed`, a reader projects a long-stale `pending` as
444 /// failed, and the boot sweep repairs whatever a process death left behind.445 /// failed, and the boot sweep repairs whatever a process death left behind.
@@ -500,12 +501,15 @@ async fn send_message(
500 return Ok(ai_unavailable("no AI service is connected right now"));501 return Ok(ai_unavailable("no AI service is connected right now"));
501 }502 }
502 503
503- // The scope the corpus is routed by, derived from the asker's own504+ // The scope the corpus is routed by, derived on every question — a
504- // memberships on every question — never from the body, so a student cannot505+ // manager or an admin gets every class-course pair in the school, everyone
506+ // else their own memberships — never from the body, so a student cannot
505 // widen their own retrieval, and never from a stored copy, so a507 // widen their own retrieval, and never from a stored copy, so a
506 // membership change takes effect on the next question. An empty scope is508 // membership change takes effect on the next question. An empty scope is
507- // legal and is sent as-is: the service abstains rather than the backend509+ // legal when the asker really has nothing to retrieve from, and is sent
508- // refusing a question it cannot know is answerable.510+ // as-is: the service abstains rather than the backend refusing a question
511+ // it cannot know is answerable. An admin's empty personal membership is
512+ // not that case.
509 let scope = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?;513 let scope = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?;
510 514
511 // Each create rides the thread's own row — it moves `updated_at` (the515 // Each create rides the thread's own row — it moves `updated_at` (the
@@ -891,7 +895,7 @@ struct StudyScopeRequest {
891 impl StudyScopeRequest {895 impl StudyScopeRequest {
892 /// The wire scope this request names, with the **resolved** pair as its896 /// The wire scope this request names, with the **resolved** pair as its
893 /// `(sinif, ders)` half: the corpus the service is addressed to is the one897 /// `(sinif, ders)` half: the corpus the service is addressed to is the one
894- /// the asker's own memberships authorized, never the body's spelling of898+ /// [`crate::service::rag_scope`] authorized, never the body's spelling of
895 /// it.899 /// it.
896 fn into_scope(self, pair: RagScopePair) -> RagScope {900 fn into_scope(self, pair: RagScopePair) -> RagScope {
897 RagScope {901 RagScope {
@@ -1072,9 +1076,11 @@ fn resolve_study_pair(
1072 ///1076 ///
1073 /// Synchronous by design: the summary is what the caller asked for, so there is1077 /// Synchronous by design: the summary is what the caller asked for, so there is
1074 /// no thread to open, no row to poll and nothing stored. The scope is derived1078 /// no thread to open, no row to poll and nothing stored. The scope is derived
1075-/// from the asker's own memberships — never from the body, which only names a1079+/// by [`crate::service::rag_scope`] — a manager or an admin gets every
1076-/// target inside them — and the `(sinif, ders)` pair that reaches the service1080+/// class-course pair in the school, everyone else their own memberships —
1077-/// is the derived one. `503` when no AI service offers `rag.summarize`.1081+/// never from the body, which only names a target inside them — and the
1082+/// `(sinif, ders)` pair that reaches the service is the derived one. `503`
1083+/// when no AI service offers `rag.summarize`.
1078 /// `abstained: true` with a `reason` is a complete answer riding a `200`.1084 /// `abstained: true` with a `reason` is a complete answer riding a `200`.
1079 ///1085 ///
1080 /// The dispatch deadline (25 s) is deliberately under the middleware's own1086 /// The dispatch deadline (25 s) is deliberately under the middleware's own
@@ -1114,10 +1120,11 @@ async fn summarize(
1114 return Ok(ai_unavailable("no AI service is connected right now"));1120 return Ok(ai_unavailable("no AI service is connected right now"));
1115 }1121 }
1116 1122
1117- // The scope the corpus is routed by, derived from the asker's own1123+ // The scope the corpus is routed by, derived on every request — a manager
1118- // memberships on every request — never from the body, so a caller cannot1124+ // or an admin gets every class-course pair in the school, everyone else
1119- // summarize a corpus they cannot study. The body's `ders`/`sinif` only pick1125+ // their own memberships — never from the body, so a caller cannot
1120- // a pair out of that set.1126+ // summarize a corpus they cannot study. The body's `ders`/`sinif` only
1127+ // pick a pair out of that set.
1121 let pairs = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?;1128 let pairs = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?;
1122 let pair = resolve_study_pair(&pairs, &req.ders, req.sinif.as_deref())?;1129 let pair = resolve_study_pair(&pairs, &req.ders, req.sinif.as_deref())?;
1123 let payload = RagSummarizePayload {1130 let payload = RagSummarizePayload {
src/web/school.rsadded+68 -0
@@ -0,0 +1,68 @@
1+//! The caller's own school, on the school side of the line.
2+//!
3+//! `GET /schools` is the vendor registry and answers only a builder cookie.
4+//! This route is the inverse: the school the session cookie is already bound
5+//! to, readable by every authenticated role. The uuid is the identity; the
6+//! slug stays off the wire.
7+
8+use axum::Json;
9+use serde::Serialize;
10+use utoipa::ToSchema;
11+use utoipa_axum::router::OpenApiRouter;
12+use utoipa_axum::routes;
13+
14+use crate::error::{AppError, ErrorResponse};
15+use crate::state::AppState;
16+use crate::tenant::{ResolvedTenant, School};
17+use crate::web::CurrentUser;
18+use crate::web::tenant_state::State;
19+
20+pub fn routes() -> OpenApiRouter<AppState> {
21+ OpenApiRouter::new().routes(routes!(current_school))
22+}
23+
24+/// The school behind the session cookie. `id` is the registry uuid — the
25+/// identity the database name and every structural reference mint from — and
26+/// `name` is the display name. The slug is not here: it is a label, not an
27+/// identity, and this response does not publish it.
28+#[derive(Serialize, ToSchema)]
29+struct SchoolIdentity {
30+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
31+ id: String,
32+ #[schema(example = "Ata Koleji")]
33+ name: String,
34+}
35+
36+/// The school the session cookie is bound to: its uuid and display name.
37+///
38+/// Any authenticated school user may read it, including a student or a parent.
39+/// A builder cookie names no school and is `401`, the same as on every other
40+/// school surface.
41+#[utoipa::path(
42+ get,
43+ path = "/school",
44+ tag = "school",
45+ security(("session_cookie" = [])),
46+ responses(
47+ (status = 200, description = "The school this session is bound to", body = SchoolIdentity),
48+ (status = 401, description = "Not authenticated", body = ErrorResponse),
49+ ),
50+)]
51+async fn current_school(
52+ State(st): State<AppState>,
53+ tenant: ResolvedTenant,
54+ _user: CurrentUser,
55+) -> Result<Json<SchoolIdentity>, AppError> {
56+ let school = School::read(&tenant.slug, st.tenants.control())
57+ .await?
58+ .ok_or_else(|| {
59+ AppError::Internal(format!(
60+ "the resolved school `{}` has no control row",
61+ tenant.slug
62+ ))
63+ })?;
64+ Ok(Json(SchoolIdentity {
65+ id: school.get_id().uuid().to_string(),
66+ name: school.name().to_string(),
67+ }))
68+}
tests/integration.rsmodified+56 -2
@@ -85,6 +85,56 @@ async fn time_serves_server_clock_without_auth() {
85 assert!(before <= now && now <= after);85 assert!(before <= now && now <= after);
86 }86 }
87 87
88+/// `GET /school` is the school the session cookie is already bound to.
89+/// Every authenticated role may read it; a missing cookie and a builder
90+/// cookie are both `401`, the same as every other school surface. The body
91+/// is the registry uuid and the display name — never the slug.
92+#[tokio::test]
93+async fn get_school_returns_uuid_and_name_without_slug() {
94+ let (app, db, tenants) = app_and_tenants().await;
95+ let (id, name): (Uuid, String) =
96+ sqlx::query_as("SELECT id, name FROM school WHERE slug = 'demo'")
97+ .fetch_one(tenants.control())
98+ .await
99+ .expect("demo school");
100+
101+ let anon = send(&app, "GET", "/school", None, None).await;
102+ assert_eq!(anon.status, StatusCode::UNAUTHORIZED);
103+
104+ hezarfen_backend::service::builder::ensure(
105+ tenants.control(),
106+ Username::try_new("operator").unwrap(),
107+ Password::try_new("secret1").unwrap(),
108+ )
109+ .await
110+ .expect("seed the builder");
111+ let builder_login = send(
112+ &app,
113+ "POST",
114+ "/builder/login",
115+ None,
116+ Some(json!({ "username": "operator", "password": "secret1" })),
117+ )
118+ .await;
119+ assert_eq!(builder_login.status, StatusCode::OK, "{}", builder_login.body);
120+ let builder_cookie = builder_login.cookie.expect("builder cookie");
121+ let builder = send(&app, "GET", "/school", Some(&builder_cookie), None).await;
122+ assert_eq!(builder.status, StatusCode::UNAUTHORIZED, "{}", builder.body);
123+
124+ let expected = json!({ "id": id.to_string(), "name": name });
125+ for (username, role) in [("school_student", "student"), ("school_parent", "parent")] {
126+ let cookie = login_as(&app, &db, username, role).await;
127+ let res = send(&app, "GET", "/school", Some(&cookie), None).await;
128+ assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body);
129+ assert_eq!(res.body, expected, "{role}");
130+ assert!(
131+ res.body.get("slug").is_none(),
132+ "{role} response must not carry a slug: {}",
133+ res.body
134+ );
135+ }
136+}
137+
88 #[tokio::test]138 #[tokio::test]
89 async fn limits_publishes_the_bounds_the_api_actually_enforces() {139 async fn limits_publishes_the_bounds_the_api_actually_enforces() {
90 let app = mem_app().await;140 let app = mem_app().await;
@@ -434,7 +484,7 @@ async fn protected_routes_require_session() {
434 /// Floor on the number of protected operations swept. It only ever goes484 /// Floor on the number of protected operations swept. It only ever goes
435 /// up: raise it when routes are added. Without it, deleting a route family485 /// up: raise it when routes are added. Without it, deleting a route family
436 /// would delete its own coverage and still pass.486 /// would delete its own coverage and still pass.
437- const MIN_PROTECTED: usize = 342;487+ const MIN_PROTECTED: usize = 343;
438 488
439 let app = mem_app().await;489 let app = mem_app().await;
440 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)490 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
@@ -30051,7 +30101,7 @@ async fn a_school_with_no_modules_can_still_use_the_core_routes() {
30051 30101
30052 /// Route prefixes that are deliberately ungated, each with the reason it is —30102 /// Route prefixes that are deliberately ungated, each with the reason it is —
30053 /// a nest here is one no school can be sold or refused.30103 /// a nest here is one no school can be sold or refused.
30054-const CORE_PREFIXES: [(&str, &str); 13] = [30104+const CORE_PREFIXES: [(&str, &str); 14] = [
30055 ("/", "the health mirror at the root"),30105 ("/", "the health mirror at the root"),
30056 ("/health", "liveness, read before any school is resolved"),30106 ("/health", "liveness, read before any school is resolved"),
30057 ("/time", "the server clock, a deploy constant"),30107 ("/time", "the server clock, a deploy constant"),
@@ -30083,6 +30133,10 @@ const CORE_PREFIXES: [(&str, &str); 13] = [
30083 "the vendor principal, which is not a school user",30133 "the vendor principal, which is not a school user",
30084 ),30134 ),
30085 ("/schools", "the vendor's registry surface, same principal"),30135 ("/schools", "the vendor's registry surface, same principal"),
30136+ (
30137+ "/school",
30138+ "the caller's own school identity, not a sold module",
30139+ ),
30086 ];30140 ];
30087 30141
30088 /// Every module's nest prefix. Written down rather than derived: the point is30142 /// Every module's nest prefix. Written down rather than derived: the point is