diff --git a/.sqlx/query-0a126ff18457632874f2a6563f9b2035b692e40333a15b244ce6b919714f6ba8.json b/.sqlx/query-0a126ff18457632874f2a6563f9b2035b692e40333a15b244ce6b919714f6ba8.json new file mode 100644 index 0000000..4e13640 --- /dev/null +++ b/.sqlx/query-0a126ff18457632874f2a6563f9b2035b692e40333a15b244ce6b919714f6ba8.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT run, module FROM zeka_run_failed_module\n WHERE run = ANY($1) ORDER BY run, ord", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "run", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run_failed_module", + "name": "run" + } + } + }, + { + "ordinal": 1, + "name": "module", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run_failed_module", + "name": "module" + } + } + } + ], + "parameters": { + "Left": [ + "TextArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "0a126ff18457632874f2a6563f9b2035b692e40333a15b244ce6b919714f6ba8" +} diff --git a/.sqlx/query-478026cc19eb8fc83ba254c273d9a2d306fb28042ae99961ddc9d20b26aec99b.json b/.sqlx/query-478026cc19eb8fc83ba254c273d9a2d306fb28042ae99961ddc9d20b26aec99b.json new file mode 100644 index 0000000..9294b2a --- /dev/null +++ b/.sqlx/query-478026cc19eb8fc83ba254c273d9a2d306fb28042ae99961ddc9d20b26aec99b.json @@ -0,0 +1,136 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT dimension, label, n_answers, n_correct, accuracy,\n overall_n_answers, overall_accuracy, contrast, confidence,\n computed_at\n FROM zeka_student_segment_profile\n WHERE student = $1 AND confidence <> 'none'\n ORDER BY dimension, label", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "dimension", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "dimension" + } + } + }, + { + "ordinal": 1, + "name": "label", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "label" + } + } + }, + { + "ordinal": 2, + "name": "n_answers", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "n_answers" + } + } + }, + { + "ordinal": 3, + "name": "n_correct", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "n_correct" + } + } + }, + { + "ordinal": 4, + "name": "accuracy", + "type_info": "Float8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "accuracy" + } + } + }, + { + "ordinal": 5, + "name": "overall_n_answers", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "overall_n_answers" + } + } + }, + { + "ordinal": 6, + "name": "overall_accuracy", + "type_info": "Float8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "overall_accuracy" + } + } + }, + { + "ordinal": 7, + "name": "contrast", + "type_info": "Float8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "contrast" + } + } + }, + { + "ordinal": 8, + "name": "confidence", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "confidence" + } + } + }, + { + "ordinal": 9, + "name": "computed_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "computed_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "478026cc19eb8fc83ba254c273d9a2d306fb28042ae99961ddc9d20b26aec99b" +} diff --git a/.sqlx/query-4e10c854ca658fb2321d8e215ba7e3ea0d12585a7558ba19538dbf73e73c1b8f.json b/.sqlx/query-4e10c854ca658fb2321d8e215ba7e3ea0d12585a7558ba19538dbf73e73c1b8f.json new file mode 100644 index 0000000..c6777f0 --- /dev/null +++ b/.sqlx/query-4e10c854ca658fb2321d8e215ba7e3ea0d12585a7558ba19538dbf73e73c1b8f.json @@ -0,0 +1,88 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT trigger, course AS \"course?: CourseId\",\n fact, window_from, window_to,\n evidence AS \"evidence: SqlJson\"\n FROM zeka_attention_item WHERE student = $1 ORDER BY ord", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "trigger", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "trigger" + } + } + }, + { + "ordinal": 1, + "name": "course?: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "course" + } + } + }, + { + "ordinal": 2, + "name": "fact", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "fact" + } + } + }, + { + "ordinal": 3, + "name": "window_from", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "window_from" + } + } + }, + { + "ordinal": 4, + "name": "window_to", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "window_to" + } + } + }, + { + "ordinal": 5, + "name": "evidence: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "evidence" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + true, + false, + false, + false, + false + ] + }, + "hash": "4e10c854ca658fb2321d8e215ba7e3ea0d12585a7558ba19538dbf73e73c1b8f" +} diff --git a/.sqlx/query-5cad55ab97a112cd2992e1484f60c6a1a4ab5a85ff75fc950eed6eb171af57c4.json b/.sqlx/query-5cad55ab97a112cd2992e1484f60c6a1a4ab5a85ff75fc950eed6eb171af57c4.json new file mode 100644 index 0000000..3be7916 --- /dev/null +++ b/.sqlx/query-5cad55ab97a112cd2992e1484f60c6a1a4ab5a85ff75fc950eed6eb171af57c4.json @@ -0,0 +1,100 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT marks AS \"marks?: SqlJson\",\n attendance AS \"attendance?: SqlJson\",\n submission AS \"submission?: SqlJson\",\n study AS \"study?: SqlJson\",\n confidence, computed_at, retain_until\n FROM zeka_student_summary WHERE student = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "marks?: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "marks" + } + } + }, + { + "ordinal": 1, + "name": "attendance?: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "attendance" + } + } + }, + { + "ordinal": 2, + "name": "submission?: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "submission" + } + } + }, + { + "ordinal": 3, + "name": "study?: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "study" + } + } + }, + { + "ordinal": 4, + "name": "confidence", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "confidence" + } + } + }, + { + "ordinal": 5, + "name": "computed_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "computed_at" + } + } + }, + { + "ordinal": 6, + "name": "retain_until", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "retain_until" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + true, + true, + true, + true, + false, + false, + false + ] + }, + "hash": "5cad55ab97a112cd2992e1484f60c6a1a4ab5a85ff75fc950eed6eb171af57c4" +} diff --git a/.sqlx/query-7d5cee0f5e1a6812329ca89b63a396c80bf152cfe403f37a42fb0d73b8a71076.json b/.sqlx/query-7d5cee0f5e1a6812329ca89b63a396c80bf152cfe403f37a42fb0d73b8a71076.json new file mode 100644 index 0000000..1ed357c --- /dev/null +++ b/.sqlx/query-7d5cee0f5e1a6812329ca89b63a396c80bf152cfe403f37a42fb0d73b8a71076.json @@ -0,0 +1,163 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, product, rule_id, rule_version, scope,\n about AS \"about?: UserId\",\n audience_role, course AS \"course?: CourseId\",\n evidence AS \"evidence: SqlJson\",\n confidence, created_at, expires_at\n FROM zeka_recommendation\n WHERE audience = $1 AND audience_role = $2\n AND ($3::uuid IS NULL OR about = $3)\n AND expires_at > $4 AND dismissed_at IS NULL\n ORDER BY created_at DESC, id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "product", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "product" + } + } + }, + { + "ordinal": 2, + "name": "rule_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "rule_id" + } + } + }, + { + "ordinal": 3, + "name": "rule_version", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "rule_version" + } + } + }, + { + "ordinal": 4, + "name": "scope", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "scope" + } + } + }, + { + "ordinal": 5, + "name": "about?: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "about" + } + } + }, + { + "ordinal": 6, + "name": "audience_role", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "audience_role" + } + } + }, + { + "ordinal": 7, + "name": "course?: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "course" + } + } + }, + { + "ordinal": 8, + "name": "evidence: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "evidence" + } + } + }, + { + "ordinal": 9, + "name": "confidence", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "confidence" + } + } + }, + { + "ordinal": 10, + "name": "created_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "created_at" + } + } + }, + { + "ordinal": 11, + "name": "expires_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "expires_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Uuid", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + true, + false, + true, + false, + false, + false, + false + ] + }, + "hash": "7d5cee0f5e1a6812329ca89b63a396c80bf152cfe403f37a42fb0d73b8a71076" +} diff --git a/.sqlx/query-94f0818bdd655d077d773285cb01d6e976936bd3efa7c940c4dd5b4c62a954ee.json b/.sqlx/query-94f0818bdd655d077d773285cb01d6e976936bd3efa7c940c4dd5b4c62a954ee.json new file mode 100644 index 0000000..2b6dc8d --- /dev/null +++ b/.sqlx/query-94f0818bdd655d077d773285cb01d6e976936bd3efa7c940c4dd5b4c62a954ee.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT run, student FROM zeka_run_pending\n WHERE run = ANY($1) ORDER BY run, ord", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "run", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run_pending", + "name": "run" + } + } + }, + { + "ordinal": 1, + "name": "student", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_run_pending", + "name": "student" + } + } + } + ], + "parameters": { + "Left": [ + "TextArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "94f0818bdd655d077d773285cb01d6e976936bd3efa7c940c4dd5b4c62a954ee" +} diff --git a/.sqlx/query-d382aa4dd8edef3532b6d278d3aa3a74edd9df39b6b1430d6c35f9ae4b28b28f.json b/.sqlx/query-d382aa4dd8edef3532b6d278d3aa3a74edd9df39b6b1430d6c35f9ae4b28b28f.json new file mode 100644 index 0000000..2dd4f7c --- /dev/null +++ b/.sqlx/query-d382aa4dd8edef3532b6d278d3aa3a74edd9df39b6b1430d6c35f9ae4b28b28f.json @@ -0,0 +1,158 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT run_day, started_at, finished_at, status, duration_ms,\n students_total, students_ok, students_failed, students_skipped,\n rows_written, budget_exceeded, budget_ms\n FROM zeka_run\n ORDER BY started_at DESC, run_day DESC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "run_day", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run", + "name": "run_day" + } + } + }, + { + "ordinal": 1, + "name": "started_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "started_at" + } + } + }, + { + "ordinal": 2, + "name": "finished_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "finished_at" + } + } + }, + { + "ordinal": 3, + "name": "status", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run", + "name": "status" + } + } + }, + { + "ordinal": 4, + "name": "duration_ms", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "duration_ms" + } + } + }, + { + "ordinal": 5, + "name": "students_total", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "students_total" + } + } + }, + { + "ordinal": 6, + "name": "students_ok", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "students_ok" + } + } + }, + { + "ordinal": 7, + "name": "students_failed", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "students_failed" + } + } + }, + { + "ordinal": 8, + "name": "students_skipped", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "students_skipped" + } + } + }, + { + "ordinal": 9, + "name": "rows_written", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "rows_written" + } + } + }, + { + "ordinal": 10, + "name": "budget_exceeded", + "type_info": "Bool", + "origin": { + "Table": { + "table": "zeka_run", + "name": "budget_exceeded" + } + } + }, + { + "ordinal": 11, + "name": "budget_ms", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "budget_ms" + } + } + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + false, + true, + false, + true, + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "d382aa4dd8edef3532b6d278d3aa3a74edd9df39b6b1430d6c35f9ae4b28b28f" +} diff --git a/README.md b/README.md index 568c6c2..4901753 100644 --- a/README.md +++ b/README.md @@ -1324,6 +1324,11 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/homework/{id}/submission/files/{fid}` | student | Download a submission file's bytes. Two callers, one handler: a student reads their own file (behind the submission gate), or a teacher who manages the homework's instance reads any file under it. A parent never reaches here — observers get the report, never the bytes. The file is scoped to the homework in the path, so a managed homework's id can't be used to pull a file from another one. | | DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove a file from the caller's own submission — row first, then its blob. Same visibility gates as submitting. Refused (409) once graded. Removing a file re-stamps the submission's `updated_at`. | | GET | `/homework/{id}/submissions` | teacher | The teacher's roster for a homework, paged via `?limit=&offset=` (omit `limit` for all of it): one row per student in the audience — the assigned subset, or every student currently enrolled in the instance when the homework carries none — plus any student outside it who still owns a submission or grade (an unenrollment or an audience change leaves work behind; it stays visible here, flagged). Each row carries the submission with its files and computed late flag, the grade, a computed `missing`, and a computed `unenrolled`. Requires teacher+ and management rights over the homework's instance. Returns a `{items, total, limit, offset}` envelope. | +| GET | `/insights/me` | student | The caller's own insight. Students get their summary, their own cards and their segment profile — **never** the attention list about themselves. Any other role gets the cards addressed to them (a teacher's `T4` cards about their students), with `summary`/`segments` empty. | +| POST | `/insights/refresh` | manager | Ask ZEKA to recompute the whole school's insights, detached. `202` means queued; the sweep's own record is `zeka_run`, which `GET /insights/runs` reads — poll that to watch a run move from `running` to its verdict. | +| GET | `/insights/runs` | manager | The run ledger, newest first. Manager+ only: `pending_students` is a list of people, and ZEKA's output contract confines it to the management view. Paged via `?limit=&offset=`. | +| GET | `/insights/students/{user}` | teacher | One student's insight, as an observer reads it. Teacher+ (narrowed to the students they reach) or a parent holding a live link to that student; everyone else — other students included — gets the same `404` a missing id gets. | +| POST | `/insights/students/{user}` | teacher | Ask ZEKA to recompute one student's insight, detached. `202` means queued, not computed: the service works through the student's data and writes its `zeka_*` rows on its own, and `GET /insights/students/{id}` shows them as soon as they land. `503` when no service offers `insight.student` — and nothing is queued. | | GET | `/instances/me` | student | The instances the caller may act in or see, paged via `?limit=&offset=` (omit `limit` for all of them), newest first; returns a `{items, total, limit, offset}` envelope. The route a student reads to find the courses their section is being taught, and a teacher the ones they run. | | GET | `/instances/{id}` | student | Fetch one instance by id. Visible to its enrolled students, its assigned teachers, its şube's homeroom teacher, and managers/admins. | | PATCH | `/instances/{id}` | teacher | Update one instance's own policy. Requires teacher+ and a right over this instance: manager+, one of its assigned teachers, or its şube's homeroom teacher. Omitted fields keep their value; both are non-clearable. | diff --git a/migrations/school/20260917000002_zeka.sql b/migrations/school/20260917000002_zeka.sql new file mode 100644 index 0000000..31ef17f --- /dev/null +++ b/migrations/school/20260917000002_zeka.sql @@ -0,0 +1,383 @@ +-- ZEKA's output tables, in the school database (Postgres). +-- +-- WHERE THIS FILE BELONGS: `migrations/school/` in the backend repo, applied +-- by `Migrator::new(migrations/school)` to the template at boot and to every +-- school database at create. It is APPEND-ONLY relative to the four existing +-- school migrations: it creates new tables and touches none of them. +-- +-- SCOPE RULE, unchanged: ZEKA **never writes** to a pre-existing table. It +-- reads school data through the bridge's `ApiRequest` allowlist only, and +-- writes nothing but the `zeka_*` tables below. The FKs point outward, one +-- direction only. +-- +-- NO `school` COLUMN: each school already lives in its own database, so the +-- tenant IS the database. The SurrealDB version carried a `school` slug on +-- every row because ZEKA then had a database of its own; that column is gone +-- and every composite key drops its school segment with it. +-- +-- Translated from service/schema/zeka.surql, following the same rules the +-- backend's own translation used: +-- * record links -> uuid FKs, ALL `ON DELETE NO ACTION` (cascades stay +-- explicit application transactions) +-- * `{a}_{b}` text record keys -> natural composite PRIMARY KEYs +-- * timestamps -> BIGINT unix-ms UTC, never `timestamptz` +-- * `option FLEXIBLE` -> JSONB, and only where the shape belongs to +-- the service rather than to this schema (the same line +-- `rag_output.payload` and `exam_question.choices` draw) +-- * `option>` -> a child table with an `ord` column, never a +-- Postgres array: the backend replaced every `TEXT[]` +-- and `uuid[]` it had (course_teacher, menu_dish_tag, +-- blueprint_course, ...), and an array here would be the +-- one exception in the schema. +-- * entity ids are app-minted uuid v7 (`domain::monotonic_id::next_uuid`), +-- never a DB default — the one id convention in the codebase. +-- +-- CHECK constraints carry only the enums ZEKA itself closes (confidence tier, +-- audience role, run status, segment dimension + its labels). `product` and +-- `rule_id` carry NO CHECK: rules are added and versioned far more often than +-- the schema, and a DDL CHECK could not survive that — the same reasoning that +-- left exam kinds and attendance statuses unconstrained. + + +-- --------------------------------------------------------------------------- +-- 1) zeka_student_summary — one nightly row per student +-- +-- PK is the student alone (the `{school}_{user}` key minus its school half), +-- which makes the nightly write an idempotent UPSERT and needs no extra +-- unique index. Same shape as `dietary_profile`, keyed on `app_user`. +-- --------------------------------------------------------------------------- +CREATE TABLE zeka_student_summary ( + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + -- The compute modules' output objects. JSONB because the shape belongs to + -- the service: it changes with a rule version, and this schema should not + -- have to move every time it does. + marks JSONB NULL, + attendance JSONB NULL, + submission JSONB NULL, + study JSONB NULL, + -- 'none' | 'exploratory' | 'stable' — inherited from the weakest input. + confidence TEXT NOT NULL + CHECK (confidence IN ('none', 'exploratory', 'stable')), + computed_at BIGINT NOT NULL, + -- Swept after this instant: derived student profile, "term + 1 year". + retain_until BIGINT NOT NULL, + CONSTRAINT zeka_student_summary_student PRIMARY KEY (student) +); + +CREATE INDEX zeka_student_summary_retain ON zeka_student_summary (retain_until); + +-- The attention list, one row per trigger (was an embedded array). +-- +-- There is deliberately NO score column and no severity: a single risk number +-- would rank children, and the literature review found no validated causal +-- evidence for that product. `ord` keeps the writer's order, which is +-- alphabetical by trigger and NOT by severity — see `attention.order_items`. +CREATE TABLE zeka_attention_item ( + student uuid NOT NULL REFERENCES zeka_student_summary(student) ON DELETE NO ACTION, + -- Which trigger fired: 'attendance' | 'homework' | 'mark_trend'. + -- No CHECK: a fourth trigger is a rule change, not a schema change. + trigger TEXT NOT NULL, + -- The course the trigger is about, when it has one. NULL = school-wide. + -- Only the mark-trend trigger is per-course today. + course uuid NULL REFERENCES course(id) ON DELETE NO ACTION, + -- THE SENTENCE THE TEACHER READS. A statement of fact, not a judgement: + -- "4 of the last 30 days' homework went unsubmitted", never "at risk". + -- It is written here rather than rebuilt by the reader, so that what was + -- shown and what was computed can never drift apart. + fact TEXT NOT NULL, + -- The window the fact is about. Kept as columns, not inside `evidence`, + -- because "is this item about the last 30 days or the last 7" is a + -- question the reader asks of every item. + window_from BIGINT NOT NULL, + window_to BIGINT NOT NULL, + -- The numbers behind the item. Never empty: the store + -- refuses an item without evidence, because an item nobody can explain + -- cannot be shown to a teacher. + evidence JSONB NOT NULL, + ord SMALLINT NOT NULL, + CONSTRAINT zeka_attention_item_student_trigger_course + UNIQUE NULLS NOT DISTINCT (student, trigger, course) +); + +CREATE INDEX zeka_attention_item_student ON zeka_attention_item (student); +CREATE INDEX zeka_attention_item_trigger ON zeka_attention_item (trigger); + + +-- --------------------------------------------------------------------------- +-- 2) zeka_recommendation — generated advice +-- +-- Every row carries a reason. Advice that cannot be explained is not shown, +-- so `evidence` is NOT NULL and the store refuses an empty object. +-- +-- The old record key was `{school}_{audience}_{product}_{rule_id}[_{scope}]`; +-- minus the school half that is exactly the composite PK below. `scope` is +-- the optional last segment (a course id, usually), and NULLS NOT DISTINCT is +-- what makes "no scope" count as a taken slot rather than an unlimited one — +-- the same device `bank_question_image` uses for its NULL slot. +-- --------------------------------------------------------------------------- +CREATE TABLE zeka_recommendation ( + -- A surrogate id, because the natural key below has a nullable column and + -- a PRIMARY KEY cannot: `NULLS NOT DISTINCT` is a UNIQUE-only device. It + -- earns its keep anyway — dismissing a card is a write against one row, + -- and a client should not have to name four columns to do it. + id uuid PRIMARY KEY, + -- Who sees it. + audience uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + -- Which product family: 'O1' | 'O2' | 'O3' | 'O4' | 'T3' | 'T4' today. + product TEXT NOT NULL, + -- Which rule, and which version of it, produced this. A rule may not + -- change what it says without changing this number. + rule_id TEXT NOT NULL, + rule_version BIGINT NOT NULL, + -- The rule's optional scope segment; NULL when the rule has none. TEXT, + -- not uuid: a segment rule scopes itself by label ("bilissel_talep=analiz", + -- "_okuma_yuku=yuksek"), not by a row it could point at. + scope TEXT NULL, + -- Who it is about. NULL on a student's own card (audience = about would + -- be noise); set on every teacher-facing row. + about uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, + -- The role gate. T4 items are 'teacher' only — never shown to the student + -- or the parent. + audience_role TEXT NOT NULL + CHECK (audience_role IN ('student', 'teacher', 'parent', 'manager')), + course uuid NULL REFERENCES course(id) ON DELETE NO ACTION, + -- Which numbers, which window. Feeds the "why?" panel. + evidence JSONB NOT NULL, + confidence TEXT NOT NULL + CHECK (confidence IN ('none', 'exploratory', 'stable')), + created_at BIGINT NOT NULL, + expires_at BIGINT NOT NULL, + -- `expires_at` or 90 days, whichever comes first. The sweep reads this. + retain_until BIGINT NOT NULL, + -- The human-override trail (KVKK art. 11): dismissed, disputed, not + -- useful. The nightly write MERGES; it must never clear these three. + dismissed_at BIGINT NULL, + dismissed_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, + dismiss_reason TEXT NULL, + -- The idempotency key: the same rule is never duplicated for the same + -- person, so the nightly write is an UPSERT on this. + -- + -- `about` IS PART OF THE KEY, and that is not cosmetic. A teacher-facing + -- rule fires once per student: thirty students under one teacher, one + -- rule, one course. Without `about` all thirty share a key, the UPSERT + -- keeps the last, and the teacher is shown one student while twenty-nine + -- vanish without an error anywhere. (The SurrealDB version keyed on + -- `scope or course or about` and lost exactly that way.) + CONSTRAINT zeka_recommendation_key + UNIQUE NULLS NOT DISTINCT (audience, product, rule_id, about, scope) +); + +CREATE INDEX zeka_recommendation_audience ON zeka_recommendation (audience, created_at); +CREATE INDEX zeka_recommendation_about ON zeka_recommendation (about, product); +-- Rule calibration: a rule dismissed as wrong over and over IS wrong. This +-- index is what makes that measurable without a full scan. +CREATE INDEX zeka_recommendation_rule ON zeka_recommendation (rule_id, created_at); +CREATE INDEX zeka_recommendation_retain ON zeka_recommendation (retain_until); + + +-- --------------------------------------------------------------------------- +-- 3) zeka_run — the nightly job's ledger +-- +-- Partial failure and budget accounting rest on this. The key was +-- `{school}_{YYYY-MM-DD}`; minus the school half it is the day itself, so a +-- re-run of the same night overwrites rather than duplicating. TEXT PK, the +-- same choice `settings.id` makes. +-- --------------------------------------------------------------------------- +CREATE TABLE zeka_run ( + run_day TEXT NOT NULL + CHECK (run_day ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'), + started_at BIGINT NOT NULL, + finished_at BIGINT NULL, + status TEXT NOT NULL + CHECK (status IN ('running', 'ok', 'partial', 'failed', 'skipped')), + duration_ms BIGINT NULL, + students_total BIGINT NOT NULL DEFAULT 0, + students_ok BIGINT NOT NULL DEFAULT 0, + students_failed BIGINT NOT NULL DEFAULT 0, + students_skipped BIGINT NOT NULL DEFAULT 0, + rows_written BIGINT NOT NULL DEFAULT 0, + budget_exceeded BOOLEAN NOT NULL DEFAULT false, + budget_ms BIGINT NOT NULL, + retain_until BIGINT NOT NULL, + CONSTRAINT zeka_run_day PRIMARY KEY (run_day) +); + +CREATE INDEX zeka_run_started ON zeka_run (started_at); +CREATE INDEX zeka_run_retain ON zeka_run (retain_until); + +-- Students the budget ran out on, one row each (was an embedded array). The +-- next run starts here, which is the only reason the list is kept. +CREATE TABLE zeka_run_pending ( + run TEXT NOT NULL REFERENCES zeka_run(run_day) ON DELETE NO ACTION, + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + ord INTEGER NOT NULL, + CONSTRAINT zeka_run_pending_run_student PRIMARY KEY (run, student) +); + +-- Modules that failed, one row each (was an embedded array). A partial list +-- is what lets the UI mark a section "missing" instead of showing a hole. +CREATE TABLE zeka_run_failed_module ( + run TEXT NOT NULL REFERENCES zeka_run(run_day) ON DELETE NO ACTION, + module TEXT NOT NULL, + ord SMALLINT NOT NULL, + CONSTRAINT zeka_run_failed_module_run_module PRIMARY KEY (run, module) +); + + +-- --------------------------------------------------------------------------- +-- 4) zeka_question_segment — one cognitive label set per exam question +-- +-- This is a question's LABEL, not its STATISTIC. p-value and discrimination +-- need raw answers, and the bridge allowlist carries no exam path, so item +-- analysis still cannot be built. Everything here comes from the question's +-- own text. +-- +-- NOT PERSONAL DATA: a row is about a question and reaches no student. It +-- still carries a finite `retain_until`, because a label is the output of one +-- model and one prompt version and goes stale when either moves — and an +-- infinite retention would need an exception in the sweep. +-- +-- The composite FK below is the device `exam_answer` uses: naming both the +-- exam and the question means the two can never disagree about the owner. +-- --------------------------------------------------------------------------- +CREATE TABLE zeka_question_segment ( + question uuid NOT NULL, + exam uuid NOT NULL, + -- Denormalized from `subject.course` so the teacher's + -- course x cognitive-demand screen needs no join. ZEKA resolves it at + -- write time; nothing else may set it. + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION, + + -- --- The dimensions. Label sets match src/segment/rubric.py exactly. --- + bilissel_talep TEXT NOT NULL + CHECK (bilissel_talep IN ('hatirlama', 'uygulama', 'analiz')), + dikkat_tuzagi TEXT NOT NULL + CHECK (dikkat_tuzagi IN ('var', 'yok')), + okuma_yuku TEXT NOT NULL + CHECK (okuma_yuku IN ('dusuk', 'yuksek')), + -- EXPERIMENTAL. Measured 0.607 stability on a hand-written probe; it + -- scores far higher on our own seed only because the generator writes + -- multi-step-ness into the text, which makes that an exam we set + -- ourselves. Labelled and stored, never read downstream. + adim_sayisi TEXT NOT NULL + CHECK (adim_sayisi IN ('tek_adim', 'cok_adim')), + + -- Per-dimension model confidence in [0,1]. One total is not enough: a + -- question's reading load can be obvious while its cognitive demand is + -- genuinely ambiguous. + confidence_bilissel_talep DOUBLE PRECISION NOT NULL + CHECK (confidence_bilissel_talep BETWEEN 0 AND 1), + confidence_dikkat_tuzagi DOUBLE PRECISION NOT NULL + CHECK (confidence_dikkat_tuzagi BETWEEN 0 AND 1), + confidence_okuma_yuku DOUBLE PRECISION NOT NULL + CHECK (confidence_okuma_yuku BETWEEN 0 AND 1), + confidence_adim_sayisi DOUBLE PRECISION NOT NULL + CHECK (confidence_adim_sayisi BETWEEN 0 AND 1), + -- Row-level tier, same vocabulary as every other table here. Derived from + -- the LOWEST confidence among the PRODUCTION dimensions; the experimental + -- one does not enter it. + confidence TEXT NOT NULL + CHECK (confidence IN ('none', 'exploratory', 'stable')), + + -- The distractor the trap points at (an id from `exam_question.choices`), + -- when `dikkat_tuzagi = 'var'`. No FK: choices live inside a JSONB column. + trap_choice TEXT NULL, + -- The model's own reasoning, two sentences at most. NOT SHOWN TO THE + -- STUDENT — see docs/CIKTI-SOZLESMESI.md. + rationale TEXT NOT NULL, + + -- Provenance. A silent model or prompt change is forbidden: when either + -- moves, the row moves with it. + model TEXT NOT NULL, + prompt_version TEXT NOT NULL, + variant TEXT NULL, + + computed_at BIGINT NOT NULL, + retain_until BIGINT NOT NULL, + + CONSTRAINT zeka_question_segment_question PRIMARY KEY (question), + CONSTRAINT zeka_question_segment_exam_question_fkey FOREIGN KEY (exam, question) + REFERENCES exam_question (exam, id) ON DELETE NO ACTION +); + +CREATE INDEX zeka_question_segment_exam ON zeka_question_segment (exam); +CREATE INDEX zeka_question_segment_subject ON zeka_question_segment (subject); +CREATE INDEX zeka_question_segment_talep + ON zeka_question_segment (course, bilissel_talep); +CREATE INDEX zeka_question_segment_retain ON zeka_question_segment (retain_until); + +-- Which dimensions downstream actually uses, and which are experimental (was +-- two embedded arrays). Kept per row on purpose: when `rubric.py` demotes a +-- dimension, that a downstream product no longer reads it is legible from the +-- row itself, with no document to consult. +CREATE TABLE zeka_question_segment_dimension ( + question uuid NOT NULL + REFERENCES zeka_question_segment(question) ON DELETE NO ACTION, + dimension TEXT NOT NULL + CHECK (dimension IN ('bilissel_talep', 'dikkat_tuzagi', + 'okuma_yuku', 'adim_sayisi')), + role TEXT NOT NULL CHECK (role IN ('downstream', 'experimental')), + ord SMALLINT NOT NULL, + CONSTRAINT zeka_question_segment_dimension_question_dimension + PRIMARY KEY (question, dimension) +); + + +-- --------------------------------------------------------------------------- +-- 5) zeka_student_segment_profile — student x dimension x label +-- +-- `contrast` IS WHY THIS TABLE EXISTS. +-- +-- Raw `accuracy` is not a discriminating measure: a student's hit rate inside +-- any segment mostly reflects their GENERAL ability. A strong student scores +-- high in every segment and a weak one low in every segment, so "this student +-- struggles with analysis questions" DOES NOT FOLLOW from it. +-- contrast = accuracy - overall_accuracy +-- The general level cancels in that difference and what remains is the part +-- specific to the segment. Recommendation rules fire on `contrast` ONLY, +-- never on `accuracy`. +-- +-- PERSONAL DATA: derived student profile — "term + 1 year", and deleted on +-- graduation (`Store.purge_departed`). +-- --------------------------------------------------------------------------- +CREATE TABLE zeka_student_segment_profile ( + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + -- PRODUCTION dimensions only. The experimental one is labelled in + -- `zeka_question_segment` and stays there; it never reaches a student. + dimension TEXT NOT NULL + CHECK (dimension IN ('bilissel_talep', 'dikkat_tuzagi', 'okuma_yuku')), + label TEXT NOT NULL, + + n_answers BIGINT NOT NULL, + n_correct BIGINT NOT NULL, + -- The segment hit rate. NOT SHOWN ALONE and NEVER FIRES A RULE ALONE: it + -- carries general ability and has no discriminating power. + accuracy DOUBLE PRECISION NOT NULL CHECK (accuracy BETWEEN 0 AND 1), + + -- The student's hit rate across ALL labelled items — the subtrahend. + -- Stored on the row so the evidence panel can show the comparison. + overall_n_answers BIGINT NOT NULL, + overall_accuracy DOUBLE PRECISION NOT NULL + CHECK (overall_accuracy BETWEEN 0 AND 1), + -- The honest measure. Negative = behind their OWN general level here. + contrast DOUBLE PRECISION NOT NULL CHECK (contrast BETWEEN -1 AND 1), + + confidence TEXT NOT NULL + CHECK (confidence IN ('none', 'exploratory', 'stable')), + + computed_at BIGINT NOT NULL, + retain_until BIGINT NOT NULL, + + CONSTRAINT zeka_student_segment_profile_key + PRIMARY KEY (student, dimension, label), + -- n_correct can never exceed n_answers; a row that says otherwise is a + -- counting bug, and the cheapest place to catch it is here. + CONSTRAINT zeka_student_segment_profile_counts + CHECK (n_correct <= n_answers AND n_answers <= overall_n_answers) +); + +CREATE INDEX zeka_student_segment_profile_dimension + ON zeka_student_segment_profile (dimension, label); +CREATE INDEX zeka_student_segment_profile_retain + ON zeka_student_segment_profile (retain_until); diff --git a/src/ai/insight.rs b/src/ai/insight.rs new file mode 100644 index 0000000..6ae65d3 --- /dev/null +++ b/src/ai/insight.rs @@ -0,0 +1,266 @@ +//! Payload contract for the `insight.*` capabilities, and the dispatch behind +//! the two the backend can route today. +//! +//! ZEKA (`hezarfen_zeka`) computes student and class insights from a school's +//! own data. Unlike the chatbot and the RAG nests, whose answers the backend +//! stores, ZEKA **writes its own rows**: the `zeka_*` tables in each school +//! database, created by the school migrator +//! (`migrations/school/20260917000002_zeka.sql`). This module only carries the +//! frames; [`crate::web::insights`] is the reader of what lands. +//! +//! That split is why the dispatches here return the service's answer rather +//! than store it — the answer is a receipt, and the rows are the product. A +//! dispatch that times out, or a service that refuses, leaves the previously +//! computed rows exactly as they are: a stale insight beats a hole. The two +//! capabilities this module dispatches: +//! +//! * [`AI_INSIGHT_STUDENT_CAPABILITY`] — one student, on demand; +//! * [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand. +//! +//! [`AI_INSIGHT_CLASS_CAPABILITY`] is declared (the service announces it) but +//! deliberately not dispatched: its request names a course the service would +//! have to enumerate a roster for, and the bridge's read allowlist carries no +//! member listing yet — the backend half of that contract is still open +//! (`hezarfen_zeka/service/docs/BACKEND-GEREKSINIMLERI.md`, item 3). Routing +//! it early would only hand the service a request it cannot answer. +//! +//! Every payload member is optional on the response side on purpose: the +//! service's TypedDicts are `total=False`, so a partial answer is a legal +//! answer, and a strict struct here would turn a service update into a +//! backend error. + +use std::time::Duration; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::ai::AiBridge; +use crate::ai::error::AiError; +use crate::ai::protocol::FrameError; +use crate::constant::{AI_INSIGHT_REFRESH_TIMEOUT_SECS, AI_INSIGHT_STUDENT_TIMEOUT_SECS}; +use crate::tenant::Slug; + +pub use crate::constant::{ + AI_INSIGHT_CLASS_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY, +}; + +/// What the backend asks a service to compute for one student. +/// +/// `school` is **not** a payload member: it rides the frame's own +/// [`Request.school`](crate::ai::protocol::Request::school), and a second +/// copy here would be one more place the two could disagree. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StudentRequest { + /// The student's user id. + pub user_id: String, + /// ISO-8601 date to compute from; omitted, the service starts at the + /// term's beginning. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub since: Option, + /// Sections to compute; omitted, the service computes all of them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sections: Option>, +} + +/// What the service computed for one student. +/// +/// `signals` and `recommendations` stay JSON values: their shape belongs to +/// the service's rule catalogue, which is versioned far faster than this +/// crate, and the stored form of the same data is JSONB for exactly that +/// reason. A reader that needs a card's fields reads them by name. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StudentResponse { + #[serde(default)] + pub user_id: Option, + #[serde(default)] + pub generated_at: Option, + /// The study profile the service detected. + #[serde(default)] + pub archetype: Option, + #[serde(default)] + pub signals: Vec, + #[serde(default)] + pub recommendations: Vec, + /// Which data source contributed how many records. + #[serde(default)] + pub coverage: Option, +} + +/// What the backend would ask a service to compute for one class (a course +/// as one şube teaches it). Defined for the contract; nothing dispatches it +/// yet — see the module docs. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ClassRequest { + /// The course or class the analysis is about. + pub course_id: String, + /// The dönem to read; omitted, the service uses the current one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub term: Option, + /// Length of the attention list. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub top_n: Option, +} + +/// What the service computed for one class. Same leniency as +/// [`StudentResponse`]: the loose members are the service's own shapes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ClassResponse { + #[serde(default)] + pub course_id: Option, + #[serde(default)] + pub generated_at: Option, + #[serde(default)] + pub cohort_size: Option, + #[serde(default)] + pub topic_gaps: Vec, + #[serde(default)] + pub attention_list: Vec, + #[serde(default)] + pub coverage: Option, +} + +/// What the backend asks a service to recompute for a whole school. +/// +/// A batch job: with `user_ids` omitted the service works through its own +/// configured student list — the backend does not enumerate one, because a +/// school-wide roster is not something the bridge's read scope hands a +/// service (same doc, item 3). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RefreshRequest { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub user_ids: Option>, + /// Recompute even where a cached result is still valid. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub force: Option, +} + +/// The receipt for a refresh: what the sweep did, once it did it. The run's +/// own ledger is `zeka_run` in the school database, which is what a reader +/// polls while this answer is still on its way. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RefreshResponse { + #[serde(default)] + pub started_at: Option, + #[serde(default)] + pub requested: Option, + #[serde(default)] + pub computed: Option, + #[serde(default)] + pub skipped: Option, + /// `{user_id, code, message}` per student the sweep could not compute. + #[serde(default)] + pub failed: Vec, +} + +/// Compute one student's insight, awaited. No capability check here: the +/// caller decides what "no service" means, and every caller today is an HTTP +/// door that has already answered `503` for it ([`crate::web::insights`]). +pub async fn compute_student( + bridge: &AiBridge, + school: &Slug, + request: &StudentRequest, +) -> Result { + dispatch( + bridge, + school, + AI_INSIGHT_STUDENT_CAPABILITY, + AI_INSIGHT_STUDENT_TIMEOUT_SECS, + request, + ) + .await +} + +/// Ask for a school-wide recompute, awaited. The service answers when its +/// batch is over; the deadline is [`AI_INSIGHT_REFRESH_TIMEOUT_SECS`]. +pub async fn refresh( + bridge: &AiBridge, + school: &Slug, + request: &RefreshRequest, +) -> Result { + dispatch( + bridge, + school, + AI_INSIGHT_REFRESH_CAPABILITY, + AI_INSIGHT_REFRESH_TIMEOUT_SECS, + request, + ) + .await +} + +/// One request, one typed answer — the two dispatches differ only in +/// capability, deadline and payload type. +/// +/// A reply that does not parse as the expected type is a +/// [`FrameError::Malformed`]: the bytes were JSON, but not this contract's +/// JSON, and handing back a half-understood answer would be worse than +/// reporting the service out of step. +async fn dispatch( + bridge: &AiBridge, + school: &Slug, + capability: &str, + timeout_secs: u64, + request: &impl Serialize, +) -> Result +where + T: DeserializeOwned, +{ + let payload = serde_json::to_value(request).map_err(malformed)?; + let answer = bridge + .dispatch_with_timeout( + school, + capability, + payload, + Duration::from_secs(timeout_secs), + ) + .await?; + serde_json::from_value(answer).map_err(malformed) +} + +fn malformed(err: serde_json::Error) -> AiError { + AiError::Protocol(FrameError::Malformed(err)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The wire names ARE this contract — a Python service reads them by + /// name, and a Rust-side rename that slipped past a struct literal would + /// break the service silently. Pinned on the encoded JSON. + #[test] + fn the_request_names_are_the_contracts() { + let request = StudentRequest { + user_id: "user-1".into(), + since: Some("2026-09-01".into()), + sections: None, + }; + assert_eq!( + serde_json::to_value(&request).unwrap(), + serde_json::json!({ "user_id": "user-1", "since": "2026-09-01" }), + "an omitted section list stays off the wire, not null" + ); + + let refresh = RefreshRequest { + user_ids: Some(vec!["user-1".into()]), + force: Some(true), + }; + assert_eq!( + serde_json::to_value(&refresh).unwrap(), + serde_json::json!({ "user_ids": ["user-1"], "force": true }) + ); + } + + /// A partial answer is a legal answer: the service's TypedDicts are + /// `total=False`, so parsing must not demand every member — a strict + /// struct here would turn a service update into a backend error. + #[test] + fn a_partial_answer_parses() { + let answer: StudentResponse = + serde_json::from_value(serde_json::json!({ "user_id": "user-1" })) + .expect("a partial answer is still an answer"); + assert_eq!(answer.user_id.as_deref(), Some("user-1")); + assert!(answer.signals.is_empty()); + assert!(answer.coverage.is_none()); + } +} diff --git a/src/ai/mod.rs b/src/ai/mod.rs index 428934a..85f6629 100644 --- a/src/ai/mod.rs +++ b/src/ai/mod.rs @@ -27,6 +27,7 @@ pub mod api; pub mod chat; pub mod error; +pub mod insight; pub mod protocol; pub mod rag; pub mod rag_chat; @@ -36,6 +37,9 @@ pub mod tls; pub use chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn}; pub use error::AiError; +pub use insight::{ + ClassRequest, ClassResponse, RefreshRequest, RefreshResponse, StudentRequest, StudentResponse, +}; pub use rag::{RagFile, RagIndexPayload}; pub use rag_chat::{ RagChatReplyPayload, RagChatRequestPayload, RagCitation, RagScopePair, RagTurn, diff --git a/src/constant.rs b/src/constant.rs index 881ad49..66bd80d 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -594,6 +594,45 @@ pub const AI_RAG_CHAT_CAPABILITY: &str = "rag.chat"; /// alone. pub const AI_RAG_CHAT_TIMEOUT_SECS: u64 = 90; +/// The capability an AI service declares to analyse one student (ZEKA, +/// `hezarfen_zeka`). It is the on-demand half of ZEKA — the service also +/// recomputes on its own schedule — and it is what a teacher's "hesapla" is +/// routed to. The service reads the student's own data back through the +/// bridge's api reads and writes nothing but its `zeka_*` rows. +pub const AI_INSIGHT_STUDENT_CAPABILITY: &str = "insight.student"; + +/// Deadline on one `insight.student` round trip. Computing one student reads +/// several of the school's sources (marks, attendance, submissions, study +/// stints) and writes the derived rows before answering, so it is +/// batch-shaped work — the same ceiling [`AI_RAG_INDEX_TIMEOUT_SECS`] gives a +/// note with ten attachments. Nobody waits on it: the dispatch runs detached +/// and a reader polls the stored rows. +pub const AI_INSIGHT_STUDENT_TIMEOUT_SECS: u64 = 120; + +/// The capability an AI service declares to analyse one class×course (a +/// şube's own instance of a course). Declared here so the name exists in one +/// place, but **no door dispatches it yet**: the request would name a course +/// the service has to enumerate a roster for, and the bridge's read allowlist +/// carries no member listing — that half of the contract is still open +/// (`hezarfen_zeka/service/docs/BACKEND-GEREKSINIMLERI.md`, item 3). +pub const AI_INSIGHT_CLASS_CAPABILITY: &str = "insight.class"; + +/// The capability an AI service declares to recompute a whole school's +/// insights. A batch job: the service works through its configured student +/// list under its own time budget and writes a run ledger. Like ZEKA's own +/// schedule, this is optional on top of the service's own cadence — it is +/// what lets the office trigger a sweep from the UI. +pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh"; + +/// Deadline on one `insight.refresh` round trip — the longest AI deadline in +/// this file. The service answers when its batch is over: the ceiling is +/// sized well past ZEKA's default 60s per-school budget (a raised +/// `ZEKA_BUDGET_MS` included) and well inside its hourly default cadence. The +/// run's progress does not depend on it — ZEKA writes its own `zeka_run` +/// ledger — this only bounds how long the detached task waits for the +/// summary. +pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300; + /// How long a `rag.chat` turn may sit `pending` before a reader projects it as /// failed. The RAG nest mirrors the chatbot's asynchronous send /// ([`CHATBOT_PENDING_STALE_SECS`]): the round trip outlives the request that diff --git a/src/lib.rs b/src/lib.rs index e0a9e56..12fc699 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -57,6 +57,7 @@ use crate::web::module_gate::gate; (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 `.` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.` 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"), (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"), (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."), + (name = "insights", description = "ZEKA's computed student insights — the `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot and writes its own `zeka_*` rows into each school's database, so this nest reads what it wrote and asks it to compute on demand; the backend never composes an insight row itself. `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."), (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`"), (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"), (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), @@ -161,6 +162,10 @@ pub fn build_router(state: AppState) -> Router { gate(web::chatbot::routes(), &state, Module::Chatbot), ) .nest("/rag", gate(web::rag::routes(), &state, Module::Chatbot)) + .nest( + "/insights", + gate(web::insights::routes(), &state, Module::Chatbot), + ) .nest("/users", web::users::routes()) .nest("/notes", gate(web::notes::routes(), &state, Module::Notes)) .nest( diff --git a/src/web/insights.rs b/src/web/insights.rs new file mode 100644 index 0000000..8a5ab03 --- /dev/null +++ b/src/web/insights.rs @@ -0,0 +1,818 @@ +//! The insight nest: the read surface over ZEKA's own tables, plus the two +//! doors that ask ZEKA to compute. +//! +//! ZEKA (`hezarfen_zeka`) is an AI service that dials in over the QUIC bridge +//! and **writes its own rows** into each school database — the `zeka_*` +//! tables created by the school migrator. The backend never composes those +//! rows; it reads them here and, on request, asks the service to compute +//! (the dispatch contract lives in [`crate::ai::insight`]). +//! +//! Reading is authorized the way every per-student report in this API is: +//! [`service::parent_link::ensure_can_observe`] decides whether the caller +//! may read *that student* at all (teacher+ clears it, a parent needs a live +//! link), and a teacher is then narrowed to the students they actually reach +//! — a shared class×course instance, asked through +//! [`service::instance::visible_instances`]. A student who is not the subject +//! reads `404`, never `403`: a foreign id is indistinguishable from a missing +//! one, the same posture `/marks/{user}` and `/rag/threads/{id}` take. +//! +//! What each door deliberately does **not** return is as much of the contract +//! as what it does (ZEKA's output contract, +//! `hezarfen_zeka/service/docs/CIKTI-SOZLESMESI.md` §5): +//! +//! * The attention list is a teacher's tool. It never appears in +//! [`my_insight`], and a linked parent reading their child does not get it +//! either — only staff at `teacher` or above do. +//! * A card's `about` (another student's id) never reaches a student caller. +//! * Segment rows with `confidence = 'none'` (fewer than 30 answers) are +//! filtered out: noise stays in the database, not on a screen. +//! * Dismissed and expired cards are filtered out of both card reads — the +//! application closes a card by stamping `dismissed_at`, and a closed card +//! must not come back. (The dismiss **write** is not built here: nothing in +//! this batch asked for it, and it needs its own decision on who may stamp +//! the audit trail. `deferred`, not half-done.) +//! +//! Sending is detached, like every other AI round trip in this API: the +//! compute doors answer `202` the moment the work is queued, because a +//! student's compute can outlast the request-timeout layer +//! ([`crate::constant::REQUEST_TIMEOUT_SECS`]). The client polls the stored +//! rows — the compute doors change nothing a reader cannot already see. + +use axum::Json; +use axum::extract::{Path, Query}; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use serde::{Deserialize, Serialize}; +use serde_json::Value as JsonValue; +use sqlx::types::Json as SqlJson; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::ai::insight::{self, RefreshRequest, StudentRequest}; +use crate::constant::{AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY}; +use crate::database::Database; +use crate::domain::class_group::ClassGroupId; +use crate::domain::course::CourseId; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service; +use crate::service::parent_link::ensure_can_observe; +use crate::state::AppState; +use crate::tenant::ResolvedTenant; +use crate::web::tenant_state::State; + +use super::{CurrentUser, Page, PageParams, RequireManager, ai_unavailable, paginate}; + +/// The single `now` every card read is filtered against. ZEKA stores unix +/// milliseconds, so "expired" is a comparison, not a projection. +fn now_millis() -> i64 { + crate::domain::timestamp::Timestamp::now().as_millis() +} + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(refresh)) + .routes(routes!(my_insight)) + .routes(routes!(student_insight, compute_student)) + .routes(routes!(list_runs)) +} + +// ---- the compute doors ----------------------------------------------------- + +/// The receipt for a queued dispatch. It carries no id: what was started is +/// not a row of ours, and the work's own record is ZEKA's (`zeka_run` for a +/// refresh, a student's `computed_at` for a compute). +#[derive(Serialize, ToSchema)] +struct AcceptedResponse { + /// Always `accepted` — the field exists so a client can branch on the + /// body rather than on the status code alone. + #[schema(example = "accepted")] + status: String, +} + +#[derive(Deserialize, ToSchema, Default)] +struct ComputeStudentRequest { + /// ISO-8601 date to compute from; omit for the dönem's beginning. + #[schema(example = "2026-09-01")] + since: Option, + /// Compute only these sections; omit for all of them. + sections: Option>, +} + +#[derive(Deserialize, ToSchema, Default)] +struct RefreshInsightsRequest { + /// Student user ids to recompute; omit for the service's own configured + /// list — the backend does not enumerate a school roster for it. + user_ids: Option>, + /// Recompute even where the service considers its cached result valid. + force: Option, +} + +/// Ask ZEKA to recompute one student's insight, detached. `202` means queued, +/// not computed: the service works through the student's data and writes its +/// `zeka_*` rows on its own, and `GET /insights/students/{id}` shows them as +/// soon as they land. `503` when no service offers `insight.student` — and +/// nothing is queued. +/// +/// Authorization is [`student_insight`]'s, gate for gate: the caller must be +/// able to read the student before they may ask for a recompute, and the +/// refusal is a `404` (a foreign id and a missing one look the same). +#[utoipa::path( + post, + path = "/students/{user}", + tag = "insights", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "User id")), + request_body = ComputeStudentRequest, + responses( + (status = 202, description = "Queued; the service writes the rows on its own", body = AcceptedResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse), + (status = 404, description = "Not found — no such student, or not one the caller may read", body = ErrorResponse), + (status = 503, description = "No AI service offers `insight.student` right now; nothing was queued", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn compute_student( + State(st): State, + tenant: ResolvedTenant, + CurrentUser(user): CurrentUser, + Path(id): Path, + body: Option>, +) -> Result { + let target = UserId::from_key(&id); + ensure_can_read(&user, &target, &st.db).await?; + + let body = body.map(|Json(body)| body).unwrap_or_default(); + let request = StudentRequest { + user_id: target.key(), + since: body.since, + sections: body.sections, + }; + let Some(bridge) = st.ai.clone() else { + return Ok(ai_unavailable( + "the AI service is not enabled on this deployment", + )); + }; + if !bridge.has_capability(AI_INSIGHT_STUDENT_CAPABILITY) { + return Ok(ai_unavailable("no AI service is connected right now")); + } + let slug = tenant.slug.clone(); + tokio::spawn(async move { + match insight::compute_student(&bridge, &slug, &request).await { + Ok(answer) => tracing::info!( + "insight.student answered for {}: {} signal(s), {} recommendation(s)", + request.user_id, + answer.signals.len(), + answer.recommendations.len() + ), + Err(err) => tracing::warn!("insight.student failed for {}: {err}", request.user_id), + } + }); + + Ok(accepted()) +} + +/// Ask ZEKA to recompute the whole school's insights, detached. `202` means +/// queued; the sweep's own record is `zeka_run`, which `GET /insights/runs` +/// reads — poll that to watch a run move from `running` to its verdict. +/// +/// Manager+ only: this is a school-wide batch, and the run it starts spends +/// the service's whole time budget. `503` when no service offers +/// `insight.refresh` — nothing is queued. +#[utoipa::path( + post, + path = "/refresh", + tag = "insights", + security(("session_cookie" = [])), + request_body = RefreshInsightsRequest, + responses( + (status = 202, description = "Queued; the service writes its run ledger on its own", body = AcceptedResponse), + (status = 400, description = "`user_ids` names something that is not a user id", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 503, description = "No AI service offers `insight.refresh` right now; nothing was queued", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type"), + ), +)] +async fn refresh( + State(st): State, + tenant: ResolvedTenant, + RequireManager(_user): RequireManager, + body: Option>, +) -> Result { + let body = body.map(|Json(body)| body).unwrap_or_default(); + let request = RefreshRequest { + user_ids: normalized_ids(body.user_ids)?, + force: body.force, + }; + let Some(bridge) = st.ai.clone() else { + return Ok(ai_unavailable( + "the AI service is not enabled on this deployment", + )); + }; + if !bridge.has_capability(AI_INSIGHT_REFRESH_CAPABILITY) { + return Ok(ai_unavailable("no AI service is connected right now")); + } + + let slug = tenant.slug.clone(); + tokio::spawn(async move { + match insight::refresh(&bridge, &slug, &request).await { + Ok(answer) => tracing::info!( + "insight.refresh answered: {} requested, {} computed, {} skipped, {} failed", + answer.requested.unwrap_or(0), + answer.computed.unwrap_or(0), + answer.skipped.unwrap_or(0), + answer.failed.len() + ), + Err(err) => tracing::warn!("insight.refresh failed: {err}"), + } + }); + + Ok(accepted()) +} + +fn accepted() -> Response { + ( + StatusCode::ACCEPTED, + Json(AcceptedResponse { + status: "accepted".to_string(), + }), + ) + .into_response() +} + +/// Canonicalize the ids a refresh body names — through the same parser every +/// route uses for a wire id, so a client cannot hand the service a spelling +/// this backend itself would never produce. Anything that parses as no uuid +/// is a `400`: unlike a path segment (where garbage reads as the nil id and +/// matches no row), a batch naming students is a list this backend must not +/// forward half-understood. +fn normalized_ids(ids: Option>) -> Result>, AppError> { + ids.map(|ids| { + ids.into_iter() + .map(|id| { + let parsed = UserId::from_key(&id); + if parsed.uuid().is_nil() { + Err(AppError::Validation(ValidationError::Invalid { + field: "user_ids", + reason: "must be user ids", + })) + } else { + Ok(parsed.key()) + } + }) + .collect::, AppError>>() + }) + .transpose() +} + +// ---- the reads ------------------------------------------------------------- + +/// One student's nightly summary. The four module objects are ZEKA's own +/// shapes (JSONB, by design): read a member by name, never by position. `null` +/// for a module the run could not compute — an empty object and a missing +/// module are different claims, and only one of them is true. +#[derive(Serialize, ToSchema)] +struct SummaryResponse { + marks: Option, + attendance: Option, + submission: Option, + study: Option, + /// The weakest input's tier: `none` | `exploratory` | `stable`. + #[schema(example = "stable")] + confidence: String, + /// UTC unix milliseconds the summary was computed at — the stamp a + /// client polls for after asking for a recompute. + computed_at: i64, + /// UTC unix milliseconds after which the sweep deletes the row. + retain_until: i64, +} + +/// One entry of the attention list — a statement of fact about a window, not +/// a judgement. **Teacher-facing**: it is never returned to the student it is +/// about (see the module docs). +#[derive(Serialize, ToSchema)] +struct AttentionItemResponse { + /// Which trigger fired: `attendance` | `homework` | `mark_trend` today — + /// a fourth trigger is a rule change, so treat this as an open set. + #[schema(example = "attendance")] + trigger: String, + /// The course the trigger is about, when it has one; `null` = school-wide. + course: Option, + /// The sentence the teacher reads, written once at compute time. + fact: String, + /// UTC unix milliseconds — the window the fact is about. + window_from: i64, + window_to: i64, + /// The numbers behind the fact, for the "neden?" panel. Never empty. + evidence: JsonValue, +} + +/// One recommendation card addressed to the caller. It carries no +/// `dismissed_at`/`dismiss_by`: a dismissed card is filtered out of both card +/// reads, so the field could only ever be null — and a face that never +/// arrives is worse than no face. +#[derive(Serialize, ToSchema)] +struct RecommendationResponse { + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] + id: String, + /// The product family: `O1` … `O4` for students, `T3`/`T4` for teachers. + #[schema(example = "T4")] + product: String, + /// Which rule produced it, and which version of that rule. + #[schema(example = "T4.attendance")] + rule_id: String, + rule_version: i64, + /// The rule's optional scope segment; `null` when the rule has none. + scope: Option, + /// Who the card is about; `null` on a card addressed to its subject + /// (a student's own card), and never returned to a student caller. + about: Option, + /// The role gate the card was written for: `student` | `teacher` | + /// `parent` | `manager`. + audience_role: String, + course: Option, + /// The numbers behind the card, including the mandatory `limitation` + /// line. Never empty. + evidence: JsonValue, + confidence: String, + created_at: i64, + /// After this instant the card is past; expired rows are filtered out of + /// both reads. + expires_at: i64, +} + +/// One student × dimension × label row. `accuracy` is returned alongside +/// `contrast` and never alone: raw accuracy carries general ability, and +/// `contrast = accuracy − overall_accuracy` is the part specific to the +/// segment. +#[derive(Serialize, ToSchema)] +struct SegmentProfileResponse { + /// A production dimension: `bilissel_talep` | `dikkat_tuzagi` | + /// `okuma_yuku` (the experimental `adim_sayisi` never reaches a student). + #[schema(example = "bilissel_talep")] + dimension: String, + #[schema(example = "analiz")] + label: String, + n_answers: i64, + n_correct: i64, + /// The segment's hit rate, `n_correct / n_answers`. + accuracy: f64, + /// The student's hit rate across all labelled items — the subtrahend, on + /// the row so the evidence panel can show the comparison. + overall_n_answers: i64, + overall_accuracy: f64, + /// The honest measure: `accuracy − overall_accuracy`. Negative = behind + /// the student's own general level in this segment. + contrast: f64, + confidence: String, + computed_at: i64, +} + +/// One student's whole readable insight: the stored summary, the caller's own +/// cards about them, and the segment profile. +#[derive(Serialize, ToSchema)] +struct StudentInsightResponse { + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] + user_id: String, + /// `null` until ZEKA has computed this student at least once. + summary: Option, + /// Teacher-facing; always empty for the subject's own view and for a + /// linked parent. + attention: Vec, + /// Cards addressed to the caller about this student — nobody else's cards + /// appear here, so two teachers reading one student each see their own. + cards: Vec, + segments: Vec, +} + +/// The caller's own insight. Students get their summary, their own cards and +/// their segment profile — **never** the attention list about themselves. +/// Any other role gets the cards addressed to them (a teacher's `T4` cards +/// about their students), with `summary`/`segments` empty. +#[utoipa::path( + get, + path = "/me", + tag = "insights", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The caller's own insight", body = StudentInsightResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_insight( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result, AppError> { + let id = user.get_id(); + let student = user.get_role() == Role::Student; + Ok(Json(StudentInsightResponse { + user_id: id.key(), + summary: if student { + summary_of(&st.db, id).await? + } else { + None + }, + attention: Vec::new(), + cards: cards_of(&st.db, id, user.get_role(), None).await?, + segments: if student { + segments_of(&st.db, id).await? + } else { + Vec::new() + }, + })) +} + +/// One student's insight, as an observer reads it. Teacher+ (narrowed to the +/// students they reach) or a parent holding a live link to that student; +/// everyone else — other students included — gets the same `404` a missing id +/// gets. +#[utoipa::path( + get, + path = "/students/{user}", + tag = "insights", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "User id")), + responses( + (status = 200, description = "The student's insight, plus the caller's own cards about them", body = StudentInsightResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse), + (status = 404, description = "Not found — no such student, or not one the caller may read", body = ErrorResponse), + ), +)] +async fn student_insight( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let target = UserId::from_key(&id); + ensure_can_read(&user, &target, &st.db).await?; + let staff = user.get_role().at_least(Role::Teacher); + Ok(Json(StudentInsightResponse { + user_id: target.key(), + summary: summary_of(&st.db, &target).await?, + attention: if staff { + attention_of(&st.db, &target).await? + } else { + Vec::new() + }, + cards: cards_of(&st.db, user.get_id(), user.get_role(), Some(&target)).await?, + segments: segments_of(&st.db, &target).await?, + })) +} + +/// One compute run, as the ledger keeps it. +#[derive(Serialize, ToSchema)] +struct InsightRunResponse { + /// The run's key: `YYYY-MM-DD`, so a re-run of the same night overwrites + /// rather than duplicating. + #[schema(example = "2026-09-17")] + run_day: String, + started_at: i64, + finished_at: Option, + /// `running` | `ok` | `partial` | `failed` | `skipped`. A `partial` run + /// must be shown as such: some students were not processed. + #[schema(example = "partial")] + status: String, + duration_ms: Option, + students_total: i64, + students_ok: i64, + students_failed: i64, + students_skipped: i64, + rows_written: i64, + /// Whether the run hit its time budget before finishing. + budget_exceeded: bool, + budget_ms: i64, + /// The students the budget ran out on; the next run starts here. Kept for + /// the management view, which is the only caller of this route. + pending_students: Vec, + /// Modules that failed, one per row — so a section can be marked missing + /// instead of shown as a hole. + failed_modules: Vec, +} + +/// The run ledger, newest first. Manager+ only: `pending_students` is a list +/// of people, and ZEKA's output contract confines it to the management view. +/// Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/runs", + tag = "insights", + security(("session_cookie" = [])), + params(PageParams), + responses( + (status = 200, description = "The school's compute runs, newest first", body = Page), + (status = 400, description = "`limit` or `offset` out of range", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + ), +)] +async fn list_runs( + State(st): State, + RequireManager(_user): RequireManager, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let rows = sqlx::query!( + r#"SELECT run_day, started_at, finished_at, status, duration_ms, + students_total, students_ok, students_failed, students_skipped, + rows_written, budget_exceeded, budget_ms + FROM zeka_run + ORDER BY started_at DESC, run_day DESC"# + ) + .fetch_all(&st.db) + .await?; + let total = rows.len() as i64; + let window = paginate(&rows, limit, offset); + let days: Vec = window.iter().map(|row| row.run_day.clone()).collect(); + let mut pending = children_of(&st.db, "pending", &days).await?; + let mut failed = children_of(&st.db, "failed", &days).await?; + let items = window + .iter() + .map(|row| InsightRunResponse { + run_day: row.run_day.clone(), + started_at: row.started_at, + finished_at: row.finished_at, + status: row.status.clone(), + duration_ms: row.duration_ms, + students_total: row.students_total, + students_ok: row.students_ok, + students_failed: row.students_failed, + students_skipped: row.students_skipped, + rows_written: row.rows_written, + budget_exceeded: row.budget_exceeded, + budget_ms: row.budget_ms, + pending_students: pending.remove(&row.run_day).unwrap_or_default(), + failed_modules: failed.remove(&row.run_day).unwrap_or_default(), + }) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// The children of the runs on this page — one query for the whole page, not +/// one per run, grouped by run day in `ord` order. +async fn children_of( + db: &Database, + kind: &str, + days: &[String], +) -> Result>, AppError> { + if days.is_empty() { + return Ok(std::collections::HashMap::new()); + } + let mut grouped: std::collections::HashMap> = + std::collections::HashMap::new(); + match kind { + "pending" => { + for row in sqlx::query!( + r#"SELECT run, student FROM zeka_run_pending + WHERE run = ANY($1) ORDER BY run, ord"#, + days + ) + .fetch_all(db) + .await? + { + grouped + .entry(row.run) + .or_default() + .push(row.student.to_string()); + } + } + "failed" => { + for row in sqlx::query!( + r#"SELECT run, module FROM zeka_run_failed_module + WHERE run = ANY($1) ORDER BY run, ord"#, + days + ) + .fetch_all(db) + .await? + { + grouped.entry(row.run).or_default().push(row.module); + } + } + other => unreachable!("unknown run child table: {other}"), + } + Ok(grouped) +} + +// ---- the queries ----------------------------------------------------------- + +/// The nightly summary, or `None` until ZEKA has computed this student once. +async fn summary_of(db: &Database, student: &UserId) -> Result, AppError> { + let row = sqlx::query!( + r#"SELECT marks AS "marks?: SqlJson", + attendance AS "attendance?: SqlJson", + submission AS "submission?: SqlJson", + study AS "study?: SqlJson", + confidence, computed_at, retain_until + FROM zeka_student_summary WHERE student = $1"#, + student.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row.map(|row| SummaryResponse { + marks: row.marks.map(|json| json.0), + attendance: row.attendance.map(|json| json.0), + submission: row.submission.map(|json| json.0), + study: row.study.map(|json| json.0), + confidence: row.confidence, + computed_at: row.computed_at, + retain_until: row.retain_until, + })) +} + +/// The attention list, in the writer's own order. Only staff at `teacher` or +/// above ever call this — see the module docs. +async fn attention_of( + db: &Database, + student: &UserId, +) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT trigger, course AS "course?: CourseId", + fact, window_from, window_to, + evidence AS "evidence: SqlJson" + FROM zeka_attention_item WHERE student = $1 ORDER BY ord"#, + student.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| AttentionItemResponse { + trigger: row.trigger, + course: row.course.map(|course| course.key().to_string()), + fact: row.fact, + window_from: row.window_from, + window_to: row.window_to, + evidence: row.evidence.0, + }) + .collect()) +} + +/// Cards addressed to `audience`, filtered to the label the caller's own role +/// reads (`audience_role`) and to cards that are still live: not expired, not +/// dismissed. `about` narrows to one student — `None` is the caller's own +/// card list, which for a teacher is the `T4` cards about their students. +async fn cards_of( + db: &Database, + audience: &UserId, + role: Role, + about: Option<&UserId>, +) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT id, product, rule_id, rule_version, scope, + about AS "about?: UserId", + audience_role, course AS "course?: CourseId", + evidence AS "evidence: SqlJson", + confidence, created_at, expires_at + FROM zeka_recommendation + WHERE audience = $1 AND audience_role = $2 + AND ($3::uuid IS NULL OR about = $3) + AND expires_at > $4 AND dismissed_at IS NULL + ORDER BY created_at DESC, id"#, + audience.uuid(), + audience_role(role), + about.map(UserId::uuid), + now_millis(), + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| RecommendationResponse { + id: row.id.to_string(), + product: row.product, + rule_id: row.rule_id, + rule_version: row.rule_version, + scope: row.scope, + // A student's own card has no `about` in the database, and the + // contract forbids one reaching a student caller even if a rule + // ever set it — so the value is dropped for a student caller, not + // merely absent. + about: (role != Role::Student) + .then(|| row.about) + .flatten() + .map(|about| about.key().to_string()), + audience_role: row.audience_role, + course: row.course.map(|course| course.key().to_string()), + evidence: row.evidence.0, + confidence: row.confidence, + created_at: row.created_at, + expires_at: row.expires_at, + }) + .collect()) +} + +/// The segment profile, noise filtered out: a row below 30 answers +/// (`confidence = 'none'`) stays in the database and off every screen. +async fn segments_of( + db: &Database, + student: &UserId, +) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT dimension, label, n_answers, n_correct, accuracy, + overall_n_answers, overall_accuracy, contrast, confidence, + computed_at + FROM zeka_student_segment_profile + WHERE student = $1 AND confidence <> 'none' + ORDER BY dimension, label"#, + student.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| SegmentProfileResponse { + dimension: row.dimension, + label: row.label, + n_answers: row.n_answers, + n_correct: row.n_correct, + accuracy: row.accuracy, + overall_n_answers: row.overall_n_answers, + overall_accuracy: row.overall_accuracy, + contrast: row.contrast, + confidence: row.confidence, + computed_at: row.computed_at, + }) + .collect()) +} + +// ---- authorization --------------------------------------------------------- + +/// The one gate every per-student insight route shares, read and compute +/// alike. +/// +/// [`ensure_can_observe`] settles the role question — teacher+ clears it, a +/// parent needs a live link — and the student a caller may *reach* is then +/// narrowed the same way `/marks/{user}` narrows a report: a teacher reads a +/// student only when they run an instance that student sits in. The narrowing +/// is a `404` rather than an empty body because the insight rows are not +/// per-instance: there is nothing honest to narrow *to*, and a foreign +/// student's id must be indistinguishable from a missing one. +async fn ensure_can_read(caller: &User, target: &UserId, db: &Database) -> Result<(), AppError> { + ensure_can_observe(caller, target, db).await?; + let target = service::user::read(db, target) + .await? + .ok_or(AppError::NotFound)?; + // Only a student has insights: a colleague's id is not a narrower report, + // it is a 404. + if target.get_role() != Role::Student { + return Err(AppError::NotFound); + } + if caller.get_role() == Role::Teacher && !teacher_reaches(db, caller, target.get_id()).await? { + return Err(AppError::NotFound); + } + Ok(()) +} + +/// Does this teacher actually reach this student — a shared class×course +/// instance the teacher runs and the student sits in? The instances a teacher +/// runs are [`service::instance::visible_instances`]'s `manages` half, which +/// is the same D10 rule every instance-scoped route applies +/// ([`service::class_course::ensure_instance_teacher`]): an assigned teacher +/// or the şube's homeroom teacher, and nobody else. +async fn teacher_reaches( + db: &Database, + teacher: &User, + student: &UserId, +) -> Result { + let (members, _) = crate::db::class_member::list_for_user(db, student, None, 0).await?; + let classes: Vec = members + .iter() + .map(|member| member.get_class().clone()) + .collect(); + if classes.is_empty() { + return Ok(false); + } + let runs: Vec = service::instance::visible_instances(teacher, db) + .await? + .into_iter() + .filter(|(_, manages)| *manages) + .map(|(instance, _)| instance.get_id().uuid()) + .collect(); + if runs.is_empty() { + return Ok(false); + } + Ok(crate::db::class_course::list_for_class_ids(db, &classes) + .await? + .iter() + .any(|instance| runs.contains(&instance.get_id().uuid()))) +} + +/// The `audience_role` label a caller reads cards under. ZEKA's catalogue +/// closes four labels (`student` | `teacher` | `parent` | `manager`); the two +/// staff ranks above teacher fold into `manager`, and the bridge's own +/// principal reads under a label no row can carry (the column's CHECK lists +/// the human four) — so a service reading as itself gets the empty list an +/// absent surface should give it. +fn audience_role(role: Role) -> &'static str { + match role { + Role::Student => "student", + Role::Parent => "parent", + Role::Teacher => "teacher", + Role::Manager | Role::Admin => "manager", + Role::Ai => "ai", + } +} diff --git a/src/web/mod.rs b/src/web/mod.rs index 0a98182..4db82ff 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -21,6 +21,7 @@ pub mod events; pub mod exam_ws; pub mod exams; pub mod homework; +pub mod insights; pub mod instances; pub mod limits; pub mod marks; diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index f4d1b0a..ccb86ae 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -3354,3 +3354,150 @@ async fn a_rag_stream_replays_a_settled_turn_with_its_citations() { assert_eq!(citation["span_ids"], json!(["s-1"]), "{message}"); assert_eq!(citation["ders"], "Fizik", "{message}"); } + +// ---- insights ---------------------------------------------------------- + +use hezarfen_backend::ai::insight; +use hezarfen_backend::constant::{AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY}; + +/// Wait until the fake service has seen `expected` requests. The compute doors +/// dispatch off the request path, so the frame lands when it lands. +async fn await_seen(service: &FakeService, expected: usize) -> Vec { + for _ in 0..500 { + let seen = service.seen(); + if seen.len() >= expected { + return seen; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("the service never saw {expected} request(s)"); +} + +/// The outbound half of `hab/2` for `insight.student`: the door dispatches to +/// the worker carrying that exact capability, the frame names the school the +/// caller acted in, and the answer round-trips back through the typed +/// contract. +#[tokio::test] +async fn an_insight_student_dispatch_names_the_school_and_round_trips() { + let bridge = bridge().await; + let service = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_STUDENT_CAPABILITY]), + Behaviour::Answer(json!({ + "user_id": "echoed-back", + "generated_at": "2026-09-17T00:00:00Z", + "archetype": "ezberci", + "signals": [], + "recommendations": [], + "coverage": { "marks": 4 }, + })), + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = chat_app(&bridge).await; + + // A manager may read any student, so the reach gate is out of this test's + // way; the student is the subject. + let staff = common::login_as(&app, &db, "mudur", "manager").await; + let student = common::login(&app, "ali").await; + let ali = common::me_id(&app, &student).await; + + let res = common::send( + &app, + "POST", + &format!("/insights/students/{ali}"), + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + + let seen = await_seen(&service, 1).await; + assert_eq!(seen.len(), 1, "one dispatch per request, never a re-send"); + assert_eq!(seen[0].capability, AI_INSIGHT_STUDENT_CAPABILITY); + assert_eq!(seen[0].school, DEMO_SLUG, "the frame names the school"); + assert_eq!(seen[0].payload["user_id"], ali); + + // The same worker driven directly answers the contract's shape, so the + // round trip — not only the send — is exercised: a reply the bridge could + // not parse would fail here. + let reply = insight::compute_student( + &bridge, + &demo(), + &hezarfen_backend::ai::StudentRequest { + user_id: ali.clone(), + since: None, + sections: None, + }, + ) + .await + .expect("the round trip answers"); + assert_eq!(reply.user_id.as_deref(), Some("echoed-back")); + assert_eq!(reply.archetype.as_deref(), Some("ezberci")); + assert_eq!(reply.coverage, Some(json!({ "marks": 4 }))); +} + +/// Routing is exact-match, and the refusal is the shared `503`, not a `500`: +/// a worker carrying only `insight.student` is no fallback for +/// `insight.refresh`, and a refused door dispatches nothing at all. +#[tokio::test] +async fn no_insight_refresh_worker_means_503_and_nothing_is_dispatched() { + let bridge = bridge().await; + let service = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_STUDENT_CAPABILITY]), + Behaviour::Echo, + ) + .await; + await_workers(&bridge, 1).await; + assert!( + !bridge.has_capability(AI_INSIGHT_REFRESH_CAPABILITY), + "the premise: no worker carries insight.refresh" + ); + let (app, db) = chat_app(&bridge).await; + let staff = common::login_as(&app, &db, "mudur", "manager").await; + + let res = common::send( + &app, + "POST", + "/insights/refresh", + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); + assert_eq!(res.body["error"], "no AI service is connected right now"); + assert_eq!( + service.seen().len(), + 0, + "a refused refresh must not reach the student-only worker" + ); + + // The student door still routes to that same worker — the 503 above is the + // capability's absence, not the worker's. + let student = common::login(&app, "ali").await; + let ali = common::me_id(&app, &student).await; + let res = common::send( + &app, + "POST", + &format!("/insights/students/{ali}"), + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + assert_eq!(await_seen(&service, 1).await[0].payload["user_id"], ali); + + // Under-privileged callers are refused before availability is even asked: + // the refresh door is manager+. + let veli = common::login(&app, "veli").await; + let res = common::send( + &app, + "POST", + "/insights/refresh", + Some(&veli), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); +} diff --git a/tests/integration.rs b/tests/integration.rs index 5a37812..3755559 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -434,7 +434,7 @@ async fn protected_routes_require_session() { /// Floor on the number of protected operations swept. It only ever goes /// up: raise it when routes are added. Without it, deleting a route family /// would delete its own coverage and still pass. - const MIN_PROTECTED: usize = 318; + const MIN_PROTECTED: usize = 323; let app = mem_app().await; let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) @@ -29690,10 +29690,12 @@ const CORE_PREFIXES: [(&str, &str); 13] = [ /// /// A module may own more than one prefix: `courses` also answers under /// `/instances` (the instance anchor), and `chatbot` — the whole `ai` package — -/// also answers under `/rag`. -const MODULE_PREFIXES: [(Module, &str); 23] = [ +/// also answers under `/rag`, `/insights` and `/podcast`. +const MODULE_PREFIXES: [(Module, &str); 25] = [ (Module::Chatbot, "/chatbot"), (Module::Chatbot, "/rag"), + (Module::Chatbot, "/insights"), + (Module::Chatbot, "/podcast"), (Module::Notes, "/notes"), (Module::Messages, "/messages"), (Module::Events, "/events"), @@ -30009,3 +30011,307 @@ async fn login_ignores_a_leftover_school_field() { .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); } + +// --- insights: ZEKA's own tables, read back --------------------------------- + +/// Seed one student's ZEKA rows the way the service writes them (the backend +/// never composes one, only reads): a nightly summary, one attention item, a +/// live card addressed to the homeroom teacher, a dismissed card and an +/// expired card addressed to the student, one displayable segment row and one +/// below the display floor. +async fn seed_insight_rows( + db: &hezarfen_backend::database::Database, + course: &str, + student: &str, + teacher: &str, +) { + let student_uuid = Uuid::parse_str(student).expect("student id"); + let teacher_uuid = Uuid::parse_str(teacher).expect("teacher id"); + let course_uuid = Uuid::parse_str(course).expect("course id"); + let now = Timestamp::now().as_millis(); + + sqlx::query( + "INSERT INTO zeka_student_summary + (student, marks, attendance, submission, study, confidence, computed_at, retain_until) + VALUES ($1, '{\"courses\":{\"matematik\":{\"average\":72}}}'::jsonb, NULL, NULL, NULL, + 'stable', $2, $3)", + ) + .bind(student_uuid) + .bind(now) + .bind(now + 400 * 86_400_000) + .execute(db) + .await + .unwrap(); + + sqlx::query( + "INSERT INTO zeka_attention_item + (student, trigger, course, fact, window_from, window_to, evidence, ord) + VALUES ($1, 'attendance', NULL, 'son 30 gunun 4 dersi kacirildi', $2, $3, + '{\"absent_days\":4}'::jsonb, 1)", + ) + .bind(student_uuid) + .bind(now - 30 * 86_400_000) + .bind(now) + .execute(db) + .await + .unwrap(); + + let live_card = Uuid::now_v7(); + sqlx::query( + "INSERT INTO zeka_recommendation + (id, audience, product, rule_id, rule_version, scope, about, audience_role, + course, evidence, confidence, created_at, expires_at, retain_until, + dismissed_at, dismissed_by, dismiss_reason) + VALUES ($1, $2, 'T4', 'T4.attendance', 1, NULL, $3, 'teacher', $4, + '{\"absent_days\":4,\"limitation\":\"yalniz ders yoklamasi\"}'::jsonb, + 'stable', $5, $6, $7, NULL, NULL, NULL)", + ) + .bind(live_card) + .bind(teacher_uuid) + .bind(student_uuid) + .bind(course_uuid) + .bind(now) + .bind(now + 86_400_000) + .bind(now + 90 * 86_400_000) + .execute(db) + .await + .unwrap(); + + // Dismissed: the application's own audit trail — a card closed by its + // audience must never be shown again. + sqlx::query( + "INSERT INTO zeka_recommendation + (id, audience, product, rule_id, rule_version, scope, about, audience_role, + course, evidence, confidence, created_at, expires_at, retain_until, + dismissed_at, dismissed_by, dismiss_reason) + VALUES ($1, $2, 'O3', 'O3.pattern', 1, NULL, NULL, 'student', NULL, + '{\"n_stints\":7,\"limitation\":\"tek donem\"}'::jsonb, + 'stable', $3, $4, $5, $3, $2, 'bu dogru degil')", + ) + .bind(Uuid::now_v7()) + .bind(student_uuid) + .bind(now) + .bind(now + 86_400_000) + .bind(now + 90 * 86_400_000) + .execute(db) + .await + .unwrap(); + + // Expired: past its `expires_at`, so it is shown to nobody. + sqlx::query( + "INSERT INTO zeka_recommendation + (id, audience, product, rule_id, rule_version, scope, about, audience_role, + course, evidence, confidence, created_at, expires_at, retain_until, + dismissed_at, dismissed_by, dismiss_reason) + VALUES ($1, $2, 'O1', 'O1.review_band', 1, NULL, NULL, 'student', NULL, + '{\"band\":\"review\",\"limitation\":\"n=3\"}'::jsonb, + 'exploratory', $3, $4, $5, NULL, NULL, NULL)", + ) + .bind(Uuid::now_v7()) + .bind(student_uuid) + .bind(now - 10 * 86_400_000) + .bind(now - 86_400_000) + .bind(now + 90 * 86_400_000) + .execute(db) + .await + .unwrap(); + + sqlx::query( + "INSERT INTO zeka_student_segment_profile + (student, dimension, label, n_answers, n_correct, accuracy, + overall_n_answers, overall_accuracy, contrast, confidence, + computed_at, retain_until) + VALUES ($1, 'bilissel_talep', 'analiz', 120, 48, 0.40, 240, 0.55, -0.15, + 'stable', $2, $3)", + ) + .bind(student_uuid) + .bind(now) + .bind(now + 400 * 86_400_000) + .execute(db) + .await + .unwrap(); + + // Below the display floor (n < 30): it stays in the database and off every + // screen, so a reader must not see this label. + sqlx::query( + "INSERT INTO zeka_student_segment_profile + (student, dimension, label, n_answers, n_correct, accuracy, + overall_n_answers, overall_accuracy, contrast, confidence, + computed_at, retain_until) + VALUES ($1, 'okuma_yuku', 'yuksek', 12, 9, 0.75, 240, 0.55, 0.20, + 'none', $2, $3)", + ) + .bind(student_uuid) + .bind(now) + .bind(now + 400 * 86_400_000) + .execute(db) + .await + .unwrap(); +} + +/// The insight read is gated twice: role first (a student is refused outright), +/// then reach (a teacher is `404`ed for a student they do not teach) — while +/// the homeroom teacher of the student's own şube reads it whole, and the +/// reader's own filters (dismissed/expired cards, noise segments, the +/// attention list's audience) all hold. +#[tokio::test] +async fn insight_reads_are_gated_to_the_students_the_caller_reaches() { + let (app, db) = app_and_db().await; + let staff = login_as(&app, &db, "mudur", "manager").await; + + let homeroom = login_as(&app, &db, "ayse", "teacher").await; + let taught = taught_under(&app, &staff, &homeroom, "matematik").await; + + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + add_member(&app, &staff, &taught.class, &ali_id).await; + + // A teacher the student shares no instance with — the refusal arm. + let stranger = login_as(&app, &db, "bora", "teacher").await; + let veli = login(&app, "veli").await; + let veli_id = me_id(&app, &veli).await; + add_member(&app, &staff, &taught.class, &veli_id).await; + + let teacher_uuid = me_id(&app, &homeroom).await; + seed_insight_rows(&db, &taught.course, &ali_id, &teacher_uuid).await; + + // The homeroom teacher runs the instance the student sits in: the whole + // card, with the filters applied. + let res = send( + &app, + "GET", + &format!("/insights/students/{ali_id}"), + Some(&homeroom), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["user_id"], ali_id); + assert_eq!(res.body["summary"]["confidence"], "stable"); + assert_eq!( + res.body["summary"]["marks"]["courses"]["matematik"]["average"], + 72 + ); + assert_eq!( + res.body["attention"].as_array().expect("attention").len(), + 1 + ); + assert_eq!(res.body["attention"][0]["trigger"], "attendance"); + let cards = res.body["cards"].as_array().expect("cards"); + assert_eq!( + cards.len(), + 1, + "dismissed and expired cards are filtered out" + ); + assert_eq!(cards[0]["rule_id"], "T4.attendance"); + assert_eq!(cards[0]["about"], ali_id); + assert_eq!(cards[0]["course"], taught.course); + assert_eq!(cards[0]["evidence"]["limitation"], "yalniz ders yoklamasi"); + let segments = res.body["segments"].as_array().expect("segments"); + assert_eq!(segments.len(), 1, "a confidence:none row is not shown"); + assert_eq!(segments[0]["label"], "analiz"); + assert_eq!(segments[0]["contrast"], -0.15); + + // The same student's own view: the summary and the profile, and the two + // things the contract keeps off a student's screen — the attention list + // about themselves, and any card not addressed to them (their live card + // belongs to the teacher, and their own two are dismissed/expired). + let res = send(&app, "GET", "/insights/me", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["summary"]["confidence"], "stable"); + assert_eq!( + res.body["attention"].as_array().expect("attention").len(), + 0 + ); + assert_eq!(res.body["cards"].as_array().expect("cards").len(), 0); + assert_eq!(res.body["segments"].as_array().expect("segments").len(), 1); + + // A teacher who does not run any instance the student sits in reads the + // same 404 a missing id reads — and the row above proves it is a refusal, + // not an absence. + let res = send( + &app, + "GET", + &format!("/insights/students/{ali_id}"), + Some(&stranger), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + + // A fellow student is refused at the role gate, the same posture + // `/marks/{user}` takes. + let res = send( + &app, + "GET", + &format!("/insights/students/{ali_id}"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // The reach check has no existence oracle either: an id no user holds + // reads exactly like the unreachable one. + let res = send( + &app, + "GET", + &format!("/insights/students/{}", Uuid::now_v7()), + Some(&stranger), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); +} + +/// The run ledger is the management view: manager+ reads it whole — with the +/// two child tables joined back in their writer's order — and a teacher is +/// refused outright (a pending-student list is a list of people). +#[tokio::test] +async fn the_insight_run_ledger_is_manager_only() { + let (app, db) = app_and_db().await; + let staff = login_as(&app, &db, "mudur", "manager").await; + let teacher = login_as(&app, &db, "ayse", "teacher").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + + let now = Timestamp::now().as_millis(); + sqlx::query( + "INSERT INTO zeka_run + (run_day, started_at, finished_at, status, duration_ms, + students_total, students_ok, students_failed, students_skipped, + rows_written, budget_exceeded, budget_ms, retain_until) + VALUES ('2026-09-16', $1, $2, 'partial', 61000, 12, 10, 1, 1, 44, true, 60000, $3)", + ) + .bind(now - 61_000) + .bind(now) + .bind(now + 90 * 86_400_000) + .execute(&db) + .await + .unwrap(); + sqlx::query("INSERT INTO zeka_run_pending (run, student, ord) VALUES ('2026-09-16', $1, 1)") + .bind(Uuid::parse_str(&ali_id).expect("student id")) + .execute(&db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO zeka_run_failed_module (run, module, ord) + VALUES ('2026-09-16', 'study', 1), ('2026-09-16', 'attendance', 2)", + ) + .execute(&db) + .await + .unwrap(); + + let res = send(&app, "GET", "/insights/runs", Some(&staff), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["total"], 1); + let run = &res.body["items"][0]; + assert_eq!(run["run_day"], "2026-09-16"); + assert_eq!(run["status"], "partial"); + assert_eq!(run["budget_exceeded"], true); + assert_eq!(run["pending_students"], json!([ali_id])); + assert_eq!(run["failed_modules"], json!(["study", "attendance"])); + + let res = send(&app, "GET", "/insights/runs", Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); +} diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 64ac759..f9bf31a 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -122,6 +122,29 @@ const EXCLUDED: &[(&str, &str)] = &[ "deadline on one RAG ask round trip; the browser waits on its message \ stream, never on this number", ), + ( + "AI_INSIGHT_STUDENT_CAPABILITY", + "capability string an AI service declares", + ), + ( + "AI_INSIGHT_STUDENT_TIMEOUT_SECS", + "deadline on one student's compute; the dispatch is off the request \ + path and a reader polls the stored rows", + ), + ( + "AI_INSIGHT_CLASS_CAPABILITY", + "capability string an AI service declares (declared for the contract; \ + no door dispatches it yet)", + ), + ( + "AI_INSIGHT_REFRESH_CAPABILITY", + "capability string an AI service declares", + ), + ( + "AI_INSIGHT_REFRESH_TIMEOUT_SECS", + "deadline on one school-wide recompute; the run's own ledger is \ + `zeka_run`, which the client polls", + ), ( "CHAT_STREAM_POLL_MS", "server-side poll cadence behind the SSE stream",