forge
Explore
Log in

Don't you dare go Hollow

ZEKA's insight capabilities — its school schema, the dispatch contract, and the /insights nest

Browse files at this commit

b0b5e0cfbe417fea69c87f34f78fc650312f1c4cAhmet Kaan GümüşParent: 1675e73
  • feat
    • ZEKA's insight capabilities — its school schema, the dispatch contract, and the /insights nest
Show full message
✨ feat: ZEKA's insight capabilities — its school schema, the dispatch contract, and the /insights nest

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

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

Gated on `Module::Chatbot` like the other two AI nests, with its tag prose in
`src/lib.rs`, the README endpoints table regenerated, and the `.sqlx` cache
refreshed for the seven new statements.
.sqlx/query-0a126ff18457632874f2a6563f9b2035b692e40333a15b244ce6b919714f6ba8.jsonadded+40 -0
@@ -0,0 +1,40 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT run, module FROM zeka_run_failed_module\n WHERE run = ANY($1) ORDER BY run, ord",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "run",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_run_failed_module",
13+ "name": "run"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "module",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_run_failed_module",
24+ "name": "module"
25+ }
26+ }
27+ }
28+ ],
29+ "parameters": {
30+ "Left": [
31+ "TextArray"
32+ ]
33+ },
34+ "nullable": [
35+ false,
36+ false
37+ ]
38+ },
39+ "hash": "0a126ff18457632874f2a6563f9b2035b692e40333a15b244ce6b919714f6ba8"
40+}
.sqlx/query-478026cc19eb8fc83ba254c273d9a2d306fb28042ae99961ddc9d20b26aec99b.jsonadded+136 -0
@@ -0,0 +1,136 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "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",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "dimension",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_student_segment_profile",
13+ "name": "dimension"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "label",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_student_segment_profile",
24+ "name": "label"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "n_answers",
31+ "type_info": "Int8",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_student_segment_profile",
35+ "name": "n_answers"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "n_correct",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_student_segment_profile",
46+ "name": "n_correct"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "accuracy",
53+ "type_info": "Float8",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_student_segment_profile",
57+ "name": "accuracy"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "overall_n_answers",
64+ "type_info": "Int8",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_student_segment_profile",
68+ "name": "overall_n_answers"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "overall_accuracy",
75+ "type_info": "Float8",
76+ "origin": {
77+ "Table": {
78+ "table": "zeka_student_segment_profile",
79+ "name": "overall_accuracy"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "contrast",
86+ "type_info": "Float8",
87+ "origin": {
88+ "Table": {
89+ "table": "zeka_student_segment_profile",
90+ "name": "contrast"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "confidence",
97+ "type_info": "Text",
98+ "origin": {
99+ "Table": {
100+ "table": "zeka_student_segment_profile",
101+ "name": "confidence"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "computed_at",
108+ "type_info": "Int8",
109+ "origin": {
110+ "Table": {
111+ "table": "zeka_student_segment_profile",
112+ "name": "computed_at"
113+ }
114+ }
115+ }
116+ ],
117+ "parameters": {
118+ "Left": [
119+ "Uuid"
120+ ]
121+ },
122+ "nullable": [
123+ false,
124+ false,
125+ false,
126+ false,
127+ false,
128+ false,
129+ false,
130+ false,
131+ false,
132+ false
133+ ]
134+ },
135+ "hash": "478026cc19eb8fc83ba254c273d9a2d306fb28042ae99961ddc9d20b26aec99b"
136+}
.sqlx/query-4e10c854ca658fb2321d8e215ba7e3ea0d12585a7558ba19538dbf73e73c1b8f.jsonadded+88 -0
@@ -0,0 +1,88 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT trigger, course AS \"course?: CourseId\",\n fact, window_from, window_to,\n evidence AS \"evidence: SqlJson<JsonValue>\"\n FROM zeka_attention_item WHERE student = $1 ORDER BY ord",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "trigger",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_attention_item",
13+ "name": "trigger"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "course?: CourseId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_attention_item",
24+ "name": "course"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "fact",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_attention_item",
35+ "name": "fact"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "window_from",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_attention_item",
46+ "name": "window_from"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "window_to",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_attention_item",
57+ "name": "window_to"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "evidence: SqlJson<JsonValue>",
64+ "type_info": "Jsonb",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_attention_item",
68+ "name": "evidence"
69+ }
70+ }
71+ }
72+ ],
73+ "parameters": {
74+ "Left": [
75+ "Uuid"
76+ ]
77+ },
78+ "nullable": [
79+ false,
80+ true,
81+ false,
82+ false,
83+ false,
84+ false
85+ ]
86+ },
87+ "hash": "4e10c854ca658fb2321d8e215ba7e3ea0d12585a7558ba19538dbf73e73c1b8f"
88+}
.sqlx/query-5cad55ab97a112cd2992e1484f60c6a1a4ab5a85ff75fc950eed6eb171af57c4.jsonadded+100 -0
@@ -0,0 +1,100 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT marks AS \"marks?: SqlJson<JsonValue>\",\n attendance AS \"attendance?: SqlJson<JsonValue>\",\n submission AS \"submission?: SqlJson<JsonValue>\",\n study AS \"study?: SqlJson<JsonValue>\",\n confidence, computed_at, retain_until\n FROM zeka_student_summary WHERE student = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "marks?: SqlJson<JsonValue>",
9+ "type_info": "Jsonb",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_student_summary",
13+ "name": "marks"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "attendance?: SqlJson<JsonValue>",
20+ "type_info": "Jsonb",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_student_summary",
24+ "name": "attendance"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "submission?: SqlJson<JsonValue>",
31+ "type_info": "Jsonb",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_student_summary",
35+ "name": "submission"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "study?: SqlJson<JsonValue>",
42+ "type_info": "Jsonb",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_student_summary",
46+ "name": "study"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "confidence",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_student_summary",
57+ "name": "confidence"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "computed_at",
64+ "type_info": "Int8",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_student_summary",
68+ "name": "computed_at"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "retain_until",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "zeka_student_summary",
79+ "name": "retain_until"
80+ }
81+ }
82+ }
83+ ],
84+ "parameters": {
85+ "Left": [
86+ "Uuid"
87+ ]
88+ },
89+ "nullable": [
90+ true,
91+ true,
92+ true,
93+ true,
94+ false,
95+ false,
96+ false
97+ ]
98+ },
99+ "hash": "5cad55ab97a112cd2992e1484f60c6a1a4ab5a85ff75fc950eed6eb171af57c4"
100+}
.sqlx/query-7d5cee0f5e1a6812329ca89b63a396c80bf152cfe403f37a42fb0d73b8a71076.jsonadded+163 -0
@@ -0,0 +1,163 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "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<JsonValue>\",\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",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_recommendation",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "product",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_recommendation",
24+ "name": "product"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "rule_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_recommendation",
35+ "name": "rule_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "rule_version",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_recommendation",
46+ "name": "rule_version"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "scope",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_recommendation",
57+ "name": "scope"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "about?: UserId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_recommendation",
68+ "name": "about"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "audience_role",
75+ "type_info": "Text",
76+ "origin": {
77+ "Table": {
78+ "table": "zeka_recommendation",
79+ "name": "audience_role"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "course?: CourseId",
86+ "type_info": "Uuid",
87+ "origin": {
88+ "Table": {
89+ "table": "zeka_recommendation",
90+ "name": "course"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "evidence: SqlJson<JsonValue>",
97+ "type_info": "Jsonb",
98+ "origin": {
99+ "Table": {
100+ "table": "zeka_recommendation",
101+ "name": "evidence"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "confidence",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "zeka_recommendation",
112+ "name": "confidence"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "created_at",
119+ "type_info": "Int8",
120+ "origin": {
121+ "Table": {
122+ "table": "zeka_recommendation",
123+ "name": "created_at"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "expires_at",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "zeka_recommendation",
134+ "name": "expires_at"
135+ }
136+ }
137+ }
138+ ],
139+ "parameters": {
140+ "Left": [
141+ "Uuid",
142+ "Text",
143+ "Uuid",
144+ "Int8"
145+ ]
146+ },
147+ "nullable": [
148+ false,
149+ false,
150+ false,
151+ false,
152+ true,
153+ true,
154+ false,
155+ true,
156+ false,
157+ false,
158+ false,
159+ false
160+ ]
161+ },
162+ "hash": "7d5cee0f5e1a6812329ca89b63a396c80bf152cfe403f37a42fb0d73b8a71076"
163+}
.sqlx/query-94f0818bdd655d077d773285cb01d6e976936bd3efa7c940c4dd5b4c62a954ee.jsonadded+40 -0
@@ -0,0 +1,40 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT run, student FROM zeka_run_pending\n WHERE run = ANY($1) ORDER BY run, ord",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "run",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_run_pending",
13+ "name": "run"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "student",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_run_pending",
24+ "name": "student"
25+ }
26+ }
27+ }
28+ ],
29+ "parameters": {
30+ "Left": [
31+ "TextArray"
32+ ]
33+ },
34+ "nullable": [
35+ false,
36+ false
37+ ]
38+ },
39+ "hash": "94f0818bdd655d077d773285cb01d6e976936bd3efa7c940c4dd5b4c62a954ee"
40+}
.sqlx/query-d382aa4dd8edef3532b6d278d3aa3a74edd9df39b6b1430d6c35f9ae4b28b28f.jsonadded+158 -0
@@ -0,0 +1,158 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "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",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "run_day",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_run",
13+ "name": "run_day"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "started_at",
20+ "type_info": "Int8",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_run",
24+ "name": "started_at"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "finished_at",
31+ "type_info": "Int8",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_run",
35+ "name": "finished_at"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "status",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_run",
46+ "name": "status"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "duration_ms",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_run",
57+ "name": "duration_ms"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "students_total",
64+ "type_info": "Int8",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_run",
68+ "name": "students_total"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "students_ok",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "zeka_run",
79+ "name": "students_ok"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "students_failed",
86+ "type_info": "Int8",
87+ "origin": {
88+ "Table": {
89+ "table": "zeka_run",
90+ "name": "students_failed"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "students_skipped",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "zeka_run",
101+ "name": "students_skipped"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "rows_written",
108+ "type_info": "Int8",
109+ "origin": {
110+ "Table": {
111+ "table": "zeka_run",
112+ "name": "rows_written"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "budget_exceeded",
119+ "type_info": "Bool",
120+ "origin": {
121+ "Table": {
122+ "table": "zeka_run",
123+ "name": "budget_exceeded"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "budget_ms",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "zeka_run",
134+ "name": "budget_ms"
135+ }
136+ }
137+ }
138+ ],
139+ "parameters": {
140+ "Left": []
141+ },
142+ "nullable": [
143+ false,
144+ false,
145+ true,
146+ false,
147+ true,
148+ false,
149+ false,
150+ false,
151+ false,
152+ false,
153+ false,
154+ false
155+ ]
156+ },
157+ "hash": "d382aa4dd8edef3532b6d278d3aa3a74edd9df39b6b1430d6c35f9ae4b28b28f"
158+}
README.mdmodified+5 -0
@@ -1324,6 +1324,11 @@ window filtering, before paging; negative values are a `400` naming the field.
13241324 | 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. |
13251325 | 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`. |
13261326 | 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. |
1327+| 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. |
1328+| 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. |
1329+| 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=`. |
1330+| 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. |
1331+| 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. |
13271332 | 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. |
13281333 | 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. |
13291334 | 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. |
migrations/school/20260917000002_zeka.sqladded+383 -0
@@ -0,0 +1,383 @@
1+-- ZEKA's output tables, in the school database (Postgres).
2+--
3+-- WHERE THIS FILE BELONGS: `migrations/school/` in the backend repo, applied
4+-- by `Migrator::new(migrations/school)` to the template at boot and to every
5+-- school database at create. It is APPEND-ONLY relative to the four existing
6+-- school migrations: it creates new tables and touches none of them.
7+--
8+-- SCOPE RULE, unchanged: ZEKA **never writes** to a pre-existing table. It
9+-- reads school data through the bridge's `ApiRequest` allowlist only, and
10+-- writes nothing but the `zeka_*` tables below. The FKs point outward, one
11+-- direction only.
12+--
13+-- NO `school` COLUMN: each school already lives in its own database, so the
14+-- tenant IS the database. The SurrealDB version carried a `school` slug on
15+-- every row because ZEKA then had a database of its own; that column is gone
16+-- and every composite key drops its school segment with it.
17+--
18+-- Translated from service/schema/zeka.surql, following the same rules the
19+-- backend's own translation used:
20+-- * record links -> uuid FKs, ALL `ON DELETE NO ACTION` (cascades stay
21+-- explicit application transactions)
22+-- * `{a}_{b}` text record keys -> natural composite PRIMARY KEYs
23+-- * timestamps -> BIGINT unix-ms UTC, never `timestamptz`
24+-- * `option<object> FLEXIBLE` -> JSONB, and only where the shape belongs to
25+-- the service rather than to this schema (the same line
26+-- `rag_output.payload` and `exam_question.choices` draw)
27+-- * `option<array<...>>` -> a child table with an `ord` column, never a
28+-- Postgres array: the backend replaced every `TEXT[]`
29+-- and `uuid[]` it had (course_teacher, menu_dish_tag,
30+-- blueprint_course, ...), and an array here would be the
31+-- one exception in the schema.
32+-- * entity ids are app-minted uuid v7 (`domain::monotonic_id::next_uuid`),
33+-- never a DB default — the one id convention in the codebase.
34+--
35+-- CHECK constraints carry only the enums ZEKA itself closes (confidence tier,
36+-- audience role, run status, segment dimension + its labels). `product` and
37+-- `rule_id` carry NO CHECK: rules are added and versioned far more often than
38+-- the schema, and a DDL CHECK could not survive that — the same reasoning that
39+-- left exam kinds and attendance statuses unconstrained.
40+
41+
42+-- ---------------------------------------------------------------------------
43+-- 1) zeka_student_summary — one nightly row per student
44+--
45+-- PK is the student alone (the `{school}_{user}` key minus its school half),
46+-- which makes the nightly write an idempotent UPSERT and needs no extra
47+-- unique index. Same shape as `dietary_profile`, keyed on `app_user`.
48+-- ---------------------------------------------------------------------------
49+CREATE TABLE zeka_student_summary (
50+ student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
51+ -- The compute modules' output objects. JSONB because the shape belongs to
52+ -- the service: it changes with a rule version, and this schema should not
53+ -- have to move every time it does.
54+ marks JSONB NULL,
55+ attendance JSONB NULL,
56+ submission JSONB NULL,
57+ study JSONB NULL,
58+ -- 'none' | 'exploratory' | 'stable' — inherited from the weakest input.
59+ confidence TEXT NOT NULL
60+ CHECK (confidence IN ('none', 'exploratory', 'stable')),
61+ computed_at BIGINT NOT NULL,
62+ -- Swept after this instant: derived student profile, "term + 1 year".
63+ retain_until BIGINT NOT NULL,
64+ CONSTRAINT zeka_student_summary_student PRIMARY KEY (student)
65+);
66+
67+CREATE INDEX zeka_student_summary_retain ON zeka_student_summary (retain_until);
68+
69+-- The attention list, one row per trigger (was an embedded array).
70+--
71+-- There is deliberately NO score column and no severity: a single risk number
72+-- would rank children, and the literature review found no validated causal
73+-- evidence for that product. `ord` keeps the writer's order, which is
74+-- alphabetical by trigger and NOT by severity — see `attention.order_items`.
75+CREATE TABLE zeka_attention_item (
76+ student uuid NOT NULL REFERENCES zeka_student_summary(student) ON DELETE NO ACTION,
77+ -- Which trigger fired: 'attendance' | 'homework' | 'mark_trend'.
78+ -- No CHECK: a fourth trigger is a rule change, not a schema change.
79+ trigger TEXT NOT NULL,
80+ -- The course the trigger is about, when it has one. NULL = school-wide.
81+ -- Only the mark-trend trigger is per-course today.
82+ course uuid NULL REFERENCES course(id) ON DELETE NO ACTION,
83+ -- THE SENTENCE THE TEACHER READS. A statement of fact, not a judgement:
84+ -- "4 of the last 30 days' homework went unsubmitted", never "at risk".
85+ -- It is written here rather than rebuilt by the reader, so that what was
86+ -- shown and what was computed can never drift apart.
87+ fact TEXT NOT NULL,
88+ -- The window the fact is about. Kept as columns, not inside `evidence`,
89+ -- because "is this item about the last 30 days or the last 7" is a
90+ -- question the reader asks of every item.
91+ window_from BIGINT NOT NULL,
92+ window_to BIGINT NOT NULL,
93+ -- The numbers behind the item. Never empty: the store
94+ -- refuses an item without evidence, because an item nobody can explain
95+ -- cannot be shown to a teacher.
96+ evidence JSONB NOT NULL,
97+ ord SMALLINT NOT NULL,
98+ CONSTRAINT zeka_attention_item_student_trigger_course
99+ UNIQUE NULLS NOT DISTINCT (student, trigger, course)
100+);
101+
102+CREATE INDEX zeka_attention_item_student ON zeka_attention_item (student);
103+CREATE INDEX zeka_attention_item_trigger ON zeka_attention_item (trigger);
104+
105+
106+-- ---------------------------------------------------------------------------
107+-- 2) zeka_recommendation — generated advice
108+--
109+-- Every row carries a reason. Advice that cannot be explained is not shown,
110+-- so `evidence` is NOT NULL and the store refuses an empty object.
111+--
112+-- The old record key was `{school}_{audience}_{product}_{rule_id}[_{scope}]`;
113+-- minus the school half that is exactly the composite PK below. `scope` is
114+-- the optional last segment (a course id, usually), and NULLS NOT DISTINCT is
115+-- what makes "no scope" count as a taken slot rather than an unlimited one —
116+-- the same device `bank_question_image` uses for its NULL slot.
117+-- ---------------------------------------------------------------------------
118+CREATE TABLE zeka_recommendation (
119+ -- A surrogate id, because the natural key below has a nullable column and
120+ -- a PRIMARY KEY cannot: `NULLS NOT DISTINCT` is a UNIQUE-only device. It
121+ -- earns its keep anyway — dismissing a card is a write against one row,
122+ -- and a client should not have to name four columns to do it.
123+ id uuid PRIMARY KEY,
124+ -- Who sees it.
125+ audience uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
126+ -- Which product family: 'O1' | 'O2' | 'O3' | 'O4' | 'T3' | 'T4' today.
127+ product TEXT NOT NULL,
128+ -- Which rule, and which version of it, produced this. A rule may not
129+ -- change what it says without changing this number.
130+ rule_id TEXT NOT NULL,
131+ rule_version BIGINT NOT NULL,
132+ -- The rule's optional scope segment; NULL when the rule has none. TEXT,
133+ -- not uuid: a segment rule scopes itself by label ("bilissel_talep=analiz",
134+ -- "<class>_okuma_yuku=yuksek"), not by a row it could point at.
135+ scope TEXT NULL,
136+ -- Who it is about. NULL on a student's own card (audience = about would
137+ -- be noise); set on every teacher-facing row.
138+ about uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION,
139+ -- The role gate. T4 items are 'teacher' only — never shown to the student
140+ -- or the parent.
141+ audience_role TEXT NOT NULL
142+ CHECK (audience_role IN ('student', 'teacher', 'parent', 'manager')),
143+ course uuid NULL REFERENCES course(id) ON DELETE NO ACTION,
144+ -- Which numbers, which window. Feeds the "why?" panel.
145+ evidence JSONB NOT NULL,
146+ confidence TEXT NOT NULL
147+ CHECK (confidence IN ('none', 'exploratory', 'stable')),
148+ created_at BIGINT NOT NULL,
149+ expires_at BIGINT NOT NULL,
150+ -- `expires_at` or 90 days, whichever comes first. The sweep reads this.
151+ retain_until BIGINT NOT NULL,
152+ -- The human-override trail (KVKK art. 11): dismissed, disputed, not
153+ -- useful. The nightly write MERGES; it must never clear these three.
154+ dismissed_at BIGINT NULL,
155+ dismissed_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION,
156+ dismiss_reason TEXT NULL,
157+ -- The idempotency key: the same rule is never duplicated for the same
158+ -- person, so the nightly write is an UPSERT on this.
159+ --
160+ -- `about` IS PART OF THE KEY, and that is not cosmetic. A teacher-facing
161+ -- rule fires once per student: thirty students under one teacher, one
162+ -- rule, one course. Without `about` all thirty share a key, the UPSERT
163+ -- keeps the last, and the teacher is shown one student while twenty-nine
164+ -- vanish without an error anywhere. (The SurrealDB version keyed on
165+ -- `scope or course or about` and lost exactly that way.)
166+ CONSTRAINT zeka_recommendation_key
167+ UNIQUE NULLS NOT DISTINCT (audience, product, rule_id, about, scope)
168+);
169+
170+CREATE INDEX zeka_recommendation_audience ON zeka_recommendation (audience, created_at);
171+CREATE INDEX zeka_recommendation_about ON zeka_recommendation (about, product);
172+-- Rule calibration: a rule dismissed as wrong over and over IS wrong. This
173+-- index is what makes that measurable without a full scan.
174+CREATE INDEX zeka_recommendation_rule ON zeka_recommendation (rule_id, created_at);
175+CREATE INDEX zeka_recommendation_retain ON zeka_recommendation (retain_until);
176+
177+
178+-- ---------------------------------------------------------------------------
179+-- 3) zeka_run — the nightly job's ledger
180+--
181+-- Partial failure and budget accounting rest on this. The key was
182+-- `{school}_{YYYY-MM-DD}`; minus the school half it is the day itself, so a
183+-- re-run of the same night overwrites rather than duplicating. TEXT PK, the
184+-- same choice `settings.id` makes.
185+-- ---------------------------------------------------------------------------
186+CREATE TABLE zeka_run (
187+ run_day TEXT NOT NULL
188+ CHECK (run_day ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'),
189+ started_at BIGINT NOT NULL,
190+ finished_at BIGINT NULL,
191+ status TEXT NOT NULL
192+ CHECK (status IN ('running', 'ok', 'partial', 'failed', 'skipped')),
193+ duration_ms BIGINT NULL,
194+ students_total BIGINT NOT NULL DEFAULT 0,
195+ students_ok BIGINT NOT NULL DEFAULT 0,
196+ students_failed BIGINT NOT NULL DEFAULT 0,
197+ students_skipped BIGINT NOT NULL DEFAULT 0,
198+ rows_written BIGINT NOT NULL DEFAULT 0,
199+ budget_exceeded BOOLEAN NOT NULL DEFAULT false,
200+ budget_ms BIGINT NOT NULL,
201+ retain_until BIGINT NOT NULL,
202+ CONSTRAINT zeka_run_day PRIMARY KEY (run_day)
203+);
204+
205+CREATE INDEX zeka_run_started ON zeka_run (started_at);
206+CREATE INDEX zeka_run_retain ON zeka_run (retain_until);
207+
208+-- Students the budget ran out on, one row each (was an embedded array). The
209+-- next run starts here, which is the only reason the list is kept.
210+CREATE TABLE zeka_run_pending (
211+ run TEXT NOT NULL REFERENCES zeka_run(run_day) ON DELETE NO ACTION,
212+ student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
213+ ord INTEGER NOT NULL,
214+ CONSTRAINT zeka_run_pending_run_student PRIMARY KEY (run, student)
215+);
216+
217+-- Modules that failed, one row each (was an embedded array). A partial list
218+-- is what lets the UI mark a section "missing" instead of showing a hole.
219+CREATE TABLE zeka_run_failed_module (
220+ run TEXT NOT NULL REFERENCES zeka_run(run_day) ON DELETE NO ACTION,
221+ module TEXT NOT NULL,
222+ ord SMALLINT NOT NULL,
223+ CONSTRAINT zeka_run_failed_module_run_module PRIMARY KEY (run, module)
224+);
225+
226+
227+-- ---------------------------------------------------------------------------
228+-- 4) zeka_question_segment — one cognitive label set per exam question
229+--
230+-- This is a question's LABEL, not its STATISTIC. p-value and discrimination
231+-- need raw answers, and the bridge allowlist carries no exam path, so item
232+-- analysis still cannot be built. Everything here comes from the question's
233+-- own text.
234+--
235+-- NOT PERSONAL DATA: a row is about a question and reaches no student. It
236+-- still carries a finite `retain_until`, because a label is the output of one
237+-- model and one prompt version and goes stale when either moves — and an
238+-- infinite retention would need an exception in the sweep.
239+--
240+-- The composite FK below is the device `exam_answer` uses: naming both the
241+-- exam and the question means the two can never disagree about the owner.
242+-- ---------------------------------------------------------------------------
243+CREATE TABLE zeka_question_segment (
244+ question uuid NOT NULL,
245+ exam uuid NOT NULL,
246+ -- Denormalized from `subject.course` so the teacher's
247+ -- course x cognitive-demand screen needs no join. ZEKA resolves it at
248+ -- write time; nothing else may set it.
249+ course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION,
250+ subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION,
251+
252+ -- --- The dimensions. Label sets match src/segment/rubric.py exactly. ---
253+ bilissel_talep TEXT NOT NULL
254+ CHECK (bilissel_talep IN ('hatirlama', 'uygulama', 'analiz')),
255+ dikkat_tuzagi TEXT NOT NULL
256+ CHECK (dikkat_tuzagi IN ('var', 'yok')),
257+ okuma_yuku TEXT NOT NULL
258+ CHECK (okuma_yuku IN ('dusuk', 'yuksek')),
259+ -- EXPERIMENTAL. Measured 0.607 stability on a hand-written probe; it
260+ -- scores far higher on our own seed only because the generator writes
261+ -- multi-step-ness into the text, which makes that an exam we set
262+ -- ourselves. Labelled and stored, never read downstream.
263+ adim_sayisi TEXT NOT NULL
264+ CHECK (adim_sayisi IN ('tek_adim', 'cok_adim')),
265+
266+ -- Per-dimension model confidence in [0,1]. One total is not enough: a
267+ -- question's reading load can be obvious while its cognitive demand is
268+ -- genuinely ambiguous.
269+ confidence_bilissel_talep DOUBLE PRECISION NOT NULL
270+ CHECK (confidence_bilissel_talep BETWEEN 0 AND 1),
271+ confidence_dikkat_tuzagi DOUBLE PRECISION NOT NULL
272+ CHECK (confidence_dikkat_tuzagi BETWEEN 0 AND 1),
273+ confidence_okuma_yuku DOUBLE PRECISION NOT NULL
274+ CHECK (confidence_okuma_yuku BETWEEN 0 AND 1),
275+ confidence_adim_sayisi DOUBLE PRECISION NOT NULL
276+ CHECK (confidence_adim_sayisi BETWEEN 0 AND 1),
277+ -- Row-level tier, same vocabulary as every other table here. Derived from
278+ -- the LOWEST confidence among the PRODUCTION dimensions; the experimental
279+ -- one does not enter it.
280+ confidence TEXT NOT NULL
281+ CHECK (confidence IN ('none', 'exploratory', 'stable')),
282+
283+ -- The distractor the trap points at (an id from `exam_question.choices`),
284+ -- when `dikkat_tuzagi = 'var'`. No FK: choices live inside a JSONB column.
285+ trap_choice TEXT NULL,
286+ -- The model's own reasoning, two sentences at most. NOT SHOWN TO THE
287+ -- STUDENT — see docs/CIKTI-SOZLESMESI.md.
288+ rationale TEXT NOT NULL,
289+
290+ -- Provenance. A silent model or prompt change is forbidden: when either
291+ -- moves, the row moves with it.
292+ model TEXT NOT NULL,
293+ prompt_version TEXT NOT NULL,
294+ variant TEXT NULL,
295+
296+ computed_at BIGINT NOT NULL,
297+ retain_until BIGINT NOT NULL,
298+
299+ CONSTRAINT zeka_question_segment_question PRIMARY KEY (question),
300+ CONSTRAINT zeka_question_segment_exam_question_fkey FOREIGN KEY (exam, question)
301+ REFERENCES exam_question (exam, id) ON DELETE NO ACTION
302+);
303+
304+CREATE INDEX zeka_question_segment_exam ON zeka_question_segment (exam);
305+CREATE INDEX zeka_question_segment_subject ON zeka_question_segment (subject);
306+CREATE INDEX zeka_question_segment_talep
307+ ON zeka_question_segment (course, bilissel_talep);
308+CREATE INDEX zeka_question_segment_retain ON zeka_question_segment (retain_until);
309+
310+-- Which dimensions downstream actually uses, and which are experimental (was
311+-- two embedded arrays). Kept per row on purpose: when `rubric.py` demotes a
312+-- dimension, that a downstream product no longer reads it is legible from the
313+-- row itself, with no document to consult.
314+CREATE TABLE zeka_question_segment_dimension (
315+ question uuid NOT NULL
316+ REFERENCES zeka_question_segment(question) ON DELETE NO ACTION,
317+ dimension TEXT NOT NULL
318+ CHECK (dimension IN ('bilissel_talep', 'dikkat_tuzagi',
319+ 'okuma_yuku', 'adim_sayisi')),
320+ role TEXT NOT NULL CHECK (role IN ('downstream', 'experimental')),
321+ ord SMALLINT NOT NULL,
322+ CONSTRAINT zeka_question_segment_dimension_question_dimension
323+ PRIMARY KEY (question, dimension)
324+);
325+
326+
327+-- ---------------------------------------------------------------------------
328+-- 5) zeka_student_segment_profile — student x dimension x label
329+--
330+-- `contrast` IS WHY THIS TABLE EXISTS.
331+--
332+-- Raw `accuracy` is not a discriminating measure: a student's hit rate inside
333+-- any segment mostly reflects their GENERAL ability. A strong student scores
334+-- high in every segment and a weak one low in every segment, so "this student
335+-- struggles with analysis questions" DOES NOT FOLLOW from it.
336+-- contrast = accuracy - overall_accuracy
337+-- The general level cancels in that difference and what remains is the part
338+-- specific to the segment. Recommendation rules fire on `contrast` ONLY,
339+-- never on `accuracy`.
340+--
341+-- PERSONAL DATA: derived student profile — "term + 1 year", and deleted on
342+-- graduation (`Store.purge_departed`).
343+-- ---------------------------------------------------------------------------
344+CREATE TABLE zeka_student_segment_profile (
345+ student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
346+ -- PRODUCTION dimensions only. The experimental one is labelled in
347+ -- `zeka_question_segment` and stays there; it never reaches a student.
348+ dimension TEXT NOT NULL
349+ CHECK (dimension IN ('bilissel_talep', 'dikkat_tuzagi', 'okuma_yuku')),
350+ label TEXT NOT NULL,
351+
352+ n_answers BIGINT NOT NULL,
353+ n_correct BIGINT NOT NULL,
354+ -- The segment hit rate. NOT SHOWN ALONE and NEVER FIRES A RULE ALONE: it
355+ -- carries general ability and has no discriminating power.
356+ accuracy DOUBLE PRECISION NOT NULL CHECK (accuracy BETWEEN 0 AND 1),
357+
358+ -- The student's hit rate across ALL labelled items — the subtrahend.
359+ -- Stored on the row so the evidence panel can show the comparison.
360+ overall_n_answers BIGINT NOT NULL,
361+ overall_accuracy DOUBLE PRECISION NOT NULL
362+ CHECK (overall_accuracy BETWEEN 0 AND 1),
363+ -- The honest measure. Negative = behind their OWN general level here.
364+ contrast DOUBLE PRECISION NOT NULL CHECK (contrast BETWEEN -1 AND 1),
365+
366+ confidence TEXT NOT NULL
367+ CHECK (confidence IN ('none', 'exploratory', 'stable')),
368+
369+ computed_at BIGINT NOT NULL,
370+ retain_until BIGINT NOT NULL,
371+
372+ CONSTRAINT zeka_student_segment_profile_key
373+ PRIMARY KEY (student, dimension, label),
374+ -- n_correct can never exceed n_answers; a row that says otherwise is a
375+ -- counting bug, and the cheapest place to catch it is here.
376+ CONSTRAINT zeka_student_segment_profile_counts
377+ CHECK (n_correct <= n_answers AND n_answers <= overall_n_answers)
378+);
379+
380+CREATE INDEX zeka_student_segment_profile_dimension
381+ ON zeka_student_segment_profile (dimension, label);
382+CREATE INDEX zeka_student_segment_profile_retain
383+ ON zeka_student_segment_profile (retain_until);
src/ai/insight.rsadded+266 -0
@@ -0,0 +1,266 @@
1+//! Payload contract for the `insight.*` capabilities, and the dispatch behind
2+//! the two the backend can route today.
3+//!
4+//! ZEKA (`hezarfen_zeka`) computes student and class insights from a school's
5+//! own data. Unlike the chatbot and the RAG nests, whose answers the backend
6+//! stores, ZEKA **writes its own rows**: the `zeka_*` tables in each school
7+//! database, created by the school migrator
8+//! (`migrations/school/20260917000002_zeka.sql`). This module only carries the
9+//! frames; [`crate::web::insights`] is the reader of what lands.
10+//!
11+//! That split is why the dispatches here return the service's answer rather
12+//! than store it — the answer is a receipt, and the rows are the product. A
13+//! dispatch that times out, or a service that refuses, leaves the previously
14+//! computed rows exactly as they are: a stale insight beats a hole. The two
15+//! capabilities this module dispatches:
16+//!
17+//! * [`AI_INSIGHT_STUDENT_CAPABILITY`] — one student, on demand;
18+//! * [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand.
19+//!
20+//! [`AI_INSIGHT_CLASS_CAPABILITY`] is declared (the service announces it) but
21+//! deliberately not dispatched: its request names a course the service would
22+//! have to enumerate a roster for, and the bridge's read allowlist carries no
23+//! member listing yet — the backend half of that contract is still open
24+//! (`hezarfen_zeka/service/docs/BACKEND-GEREKSINIMLERI.md`, item 3). Routing
25+//! it early would only hand the service a request it cannot answer.
26+//!
27+//! Every payload member is optional on the response side on purpose: the
28+//! service's TypedDicts are `total=False`, so a partial answer is a legal
29+//! answer, and a strict struct here would turn a service update into a
30+//! backend error.
31+
32+use std::time::Duration;
33+
34+use serde::de::DeserializeOwned;
35+use serde::{Deserialize, Serialize};
36+use serde_json::Value;
37+
38+use crate::ai::AiBridge;
39+use crate::ai::error::AiError;
40+use crate::ai::protocol::FrameError;
41+use crate::constant::{AI_INSIGHT_REFRESH_TIMEOUT_SECS, AI_INSIGHT_STUDENT_TIMEOUT_SECS};
42+use crate::tenant::Slug;
43+
44+pub use crate::constant::{
45+ AI_INSIGHT_CLASS_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY,
46+};
47+
48+/// What the backend asks a service to compute for one student.
49+///
50+/// `school` is **not** a payload member: it rides the frame's own
51+/// [`Request.school`](crate::ai::protocol::Request::school), and a second
52+/// copy here would be one more place the two could disagree.
53+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54+pub struct StudentRequest {
55+ /// The student's user id.
56+ pub user_id: String,
57+ /// ISO-8601 date to compute from; omitted, the service starts at the
58+ /// term's beginning.
59+ #[serde(default, skip_serializing_if = "Option::is_none")]
60+ pub since: Option<String>,
61+ /// Sections to compute; omitted, the service computes all of them.
62+ #[serde(default, skip_serializing_if = "Option::is_none")]
63+ pub sections: Option<Vec<String>>,
64+}
65+
66+/// What the service computed for one student.
67+///
68+/// `signals` and `recommendations` stay JSON values: their shape belongs to
69+/// the service's rule catalogue, which is versioned far faster than this
70+/// crate, and the stored form of the same data is JSONB for exactly that
71+/// reason. A reader that needs a card's fields reads them by name.
72+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73+pub struct StudentResponse {
74+ #[serde(default)]
75+ pub user_id: Option<String>,
76+ #[serde(default)]
77+ pub generated_at: Option<String>,
78+ /// The study profile the service detected.
79+ #[serde(default)]
80+ pub archetype: Option<String>,
81+ #[serde(default)]
82+ pub signals: Vec<Value>,
83+ #[serde(default)]
84+ pub recommendations: Vec<Value>,
85+ /// Which data source contributed how many records.
86+ #[serde(default)]
87+ pub coverage: Option<Value>,
88+}
89+
90+/// What the backend would ask a service to compute for one class (a course
91+/// as one şube teaches it). Defined for the contract; nothing dispatches it
92+/// yet — see the module docs.
93+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94+pub struct ClassRequest {
95+ /// The course or class the analysis is about.
96+ pub course_id: String,
97+ /// The dönem to read; omitted, the service uses the current one.
98+ #[serde(default, skip_serializing_if = "Option::is_none")]
99+ pub term: Option<String>,
100+ /// Length of the attention list.
101+ #[serde(default, skip_serializing_if = "Option::is_none")]
102+ pub top_n: Option<u32>,
103+}
104+
105+/// What the service computed for one class. Same leniency as
106+/// [`StudentResponse`]: the loose members are the service's own shapes.
107+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108+pub struct ClassResponse {
109+ #[serde(default)]
110+ pub course_id: Option<String>,
111+ #[serde(default)]
112+ pub generated_at: Option<String>,
113+ #[serde(default)]
114+ pub cohort_size: Option<u64>,
115+ #[serde(default)]
116+ pub topic_gaps: Vec<Value>,
117+ #[serde(default)]
118+ pub attention_list: Vec<Value>,
119+ #[serde(default)]
120+ pub coverage: Option<Value>,
121+}
122+
123+/// What the backend asks a service to recompute for a whole school.
124+///
125+/// A batch job: with `user_ids` omitted the service works through its own
126+/// configured student list — the backend does not enumerate one, because a
127+/// school-wide roster is not something the bridge's read scope hands a
128+/// service (same doc, item 3).
129+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130+pub struct RefreshRequest {
131+ #[serde(default, skip_serializing_if = "Option::is_none")]
132+ pub user_ids: Option<Vec<String>>,
133+ /// Recompute even where a cached result is still valid.
134+ #[serde(default, skip_serializing_if = "Option::is_none")]
135+ pub force: Option<bool>,
136+}
137+
138+/// The receipt for a refresh: what the sweep did, once it did it. The run's
139+/// own ledger is `zeka_run` in the school database, which is what a reader
140+/// polls while this answer is still on its way.
141+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142+pub struct RefreshResponse {
143+ #[serde(default)]
144+ pub started_at: Option<String>,
145+ #[serde(default)]
146+ pub requested: Option<u64>,
147+ #[serde(default)]
148+ pub computed: Option<u64>,
149+ #[serde(default)]
150+ pub skipped: Option<u64>,
151+ /// `{user_id, code, message}` per student the sweep could not compute.
152+ #[serde(default)]
153+ pub failed: Vec<Value>,
154+}
155+
156+/// Compute one student's insight, awaited. No capability check here: the
157+/// caller decides what "no service" means, and every caller today is an HTTP
158+/// door that has already answered `503` for it ([`crate::web::insights`]).
159+pub async fn compute_student(
160+ bridge: &AiBridge,
161+ school: &Slug,
162+ request: &StudentRequest,
163+) -> Result<StudentResponse, AiError> {
164+ dispatch(
165+ bridge,
166+ school,
167+ AI_INSIGHT_STUDENT_CAPABILITY,
168+ AI_INSIGHT_STUDENT_TIMEOUT_SECS,
169+ request,
170+ )
171+ .await
172+}
173+
174+/// Ask for a school-wide recompute, awaited. The service answers when its
175+/// batch is over; the deadline is [`AI_INSIGHT_REFRESH_TIMEOUT_SECS`].
176+pub async fn refresh(
177+ bridge: &AiBridge,
178+ school: &Slug,
179+ request: &RefreshRequest,
180+) -> Result<RefreshResponse, AiError> {
181+ dispatch(
182+ bridge,
183+ school,
184+ AI_INSIGHT_REFRESH_CAPABILITY,
185+ AI_INSIGHT_REFRESH_TIMEOUT_SECS,
186+ request,
187+ )
188+ .await
189+}
190+
191+/// One request, one typed answer — the two dispatches differ only in
192+/// capability, deadline and payload type.
193+///
194+/// A reply that does not parse as the expected type is a
195+/// [`FrameError::Malformed`]: the bytes were JSON, but not this contract's
196+/// JSON, and handing back a half-understood answer would be worse than
197+/// reporting the service out of step.
198+async fn dispatch<T>(
199+ bridge: &AiBridge,
200+ school: &Slug,
201+ capability: &str,
202+ timeout_secs: u64,
203+ request: &impl Serialize,
204+) -> Result<T, AiError>
205+where
206+ T: DeserializeOwned,
207+{
208+ let payload = serde_json::to_value(request).map_err(malformed)?;
209+ let answer = bridge
210+ .dispatch_with_timeout(
211+ school,
212+ capability,
213+ payload,
214+ Duration::from_secs(timeout_secs),
215+ )
216+ .await?;
217+ serde_json::from_value(answer).map_err(malformed)
218+}
219+
220+fn malformed(err: serde_json::Error) -> AiError {
221+ AiError::Protocol(FrameError::Malformed(err))
222+}
223+
224+#[cfg(test)]
225+mod tests {
226+ use super::*;
227+
228+ /// The wire names ARE this contract — a Python service reads them by
229+ /// name, and a Rust-side rename that slipped past a struct literal would
230+ /// break the service silently. Pinned on the encoded JSON.
231+ #[test]
232+ fn the_request_names_are_the_contracts() {
233+ let request = StudentRequest {
234+ user_id: "user-1".into(),
235+ since: Some("2026-09-01".into()),
236+ sections: None,
237+ };
238+ assert_eq!(
239+ serde_json::to_value(&request).unwrap(),
240+ serde_json::json!({ "user_id": "user-1", "since": "2026-09-01" }),
241+ "an omitted section list stays off the wire, not null"
242+ );
243+
244+ let refresh = RefreshRequest {
245+ user_ids: Some(vec!["user-1".into()]),
246+ force: Some(true),
247+ };
248+ assert_eq!(
249+ serde_json::to_value(&refresh).unwrap(),
250+ serde_json::json!({ "user_ids": ["user-1"], "force": true })
251+ );
252+ }
253+
254+ /// A partial answer is a legal answer: the service's TypedDicts are
255+ /// `total=False`, so parsing must not demand every member — a strict
256+ /// struct here would turn a service update into a backend error.
257+ #[test]
258+ fn a_partial_answer_parses() {
259+ let answer: StudentResponse =
260+ serde_json::from_value(serde_json::json!({ "user_id": "user-1" }))
261+ .expect("a partial answer is still an answer");
262+ assert_eq!(answer.user_id.as_deref(), Some("user-1"));
263+ assert!(answer.signals.is_empty());
264+ assert!(answer.coverage.is_none());
265+ }
266+}
src/ai/mod.rsmodified+4 -0
@@ -27,6 +27,7 @@
2727 pub mod api;
2828 pub mod chat;
2929 pub mod error;
30+pub mod insight;
3031 pub mod protocol;
3132 pub mod rag;
3233 pub mod rag_chat;
@@ -36,6 +37,9 @@ pub mod tls;
3637
3738 pub use chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};
3839 pub use error::AiError;
40+pub use insight::{
41+ ClassRequest, ClassResponse, RefreshRequest, RefreshResponse, StudentRequest, StudentResponse,
42+};
3943 pub use rag::{RagFile, RagIndexPayload};
4044 pub use rag_chat::{
4145 RagChatReplyPayload, RagChatRequestPayload, RagCitation, RagScopePair, RagTurn,
src/constant.rsmodified+39 -0
@@ -594,6 +594,45 @@ pub const AI_RAG_CHAT_CAPABILITY: &str = "rag.chat";
594594 /// alone.
595595 pub const AI_RAG_CHAT_TIMEOUT_SECS: u64 = 90;
596596
597+/// The capability an AI service declares to analyse one student (ZEKA,
598+/// `hezarfen_zeka`). It is the on-demand half of ZEKA — the service also
599+/// recomputes on its own schedule — and it is what a teacher's "hesapla" is
600+/// routed to. The service reads the student's own data back through the
601+/// bridge's api reads and writes nothing but its `zeka_*` rows.
602+pub const AI_INSIGHT_STUDENT_CAPABILITY: &str = "insight.student";
603+
604+/// Deadline on one `insight.student` round trip. Computing one student reads
605+/// several of the school's sources (marks, attendance, submissions, study
606+/// stints) and writes the derived rows before answering, so it is
607+/// batch-shaped work — the same ceiling [`AI_RAG_INDEX_TIMEOUT_SECS`] gives a
608+/// note with ten attachments. Nobody waits on it: the dispatch runs detached
609+/// and a reader polls the stored rows.
610+pub const AI_INSIGHT_STUDENT_TIMEOUT_SECS: u64 = 120;
611+
612+/// The capability an AI service declares to analyse one class×course (a
613+/// şube's own instance of a course). Declared here so the name exists in one
614+/// place, but **no door dispatches it yet**: the request would name a course
615+/// the service has to enumerate a roster for, and the bridge's read allowlist
616+/// carries no member listing — that half of the contract is still open
617+/// (`hezarfen_zeka/service/docs/BACKEND-GEREKSINIMLERI.md`, item 3).
618+pub const AI_INSIGHT_CLASS_CAPABILITY: &str = "insight.class";
619+
620+/// The capability an AI service declares to recompute a whole school's
621+/// insights. A batch job: the service works through its configured student
622+/// list under its own time budget and writes a run ledger. Like ZEKA's own
623+/// schedule, this is optional on top of the service's own cadence — it is
624+/// what lets the office trigger a sweep from the UI.
625+pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh";
626+
627+/// Deadline on one `insight.refresh` round trip — the longest AI deadline in
628+/// this file. The service answers when its batch is over: the ceiling is
629+/// sized well past ZEKA's default 60s per-school budget (a raised
630+/// `ZEKA_BUDGET_MS` included) and well inside its hourly default cadence. The
631+/// run's progress does not depend on it — ZEKA writes its own `zeka_run`
632+/// ledger — this only bounds how long the detached task waits for the
633+/// summary.
634+pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300;
635+
597636 /// How long a `rag.chat` turn may sit `pending` before a reader projects it as
598637 /// failed. The RAG nest mirrors the chatbot's asynchronous send
599638 /// ([`CHATBOT_PENDING_STALE_SECS`]): the round trip outlives the request that
src/lib.rsmodified+5 -0
@@ -57,6 +57,7 @@ use crate::web::module_gate::gate;
5757 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),
5858 (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"),
5959 (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."),
60+ (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."),
6061 (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`"),
6162 (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"),
6263 (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 {
161162 gate(web::chatbot::routes(), &state, Module::Chatbot),
162163 )
163164 .nest("/rag", gate(web::rag::routes(), &state, Module::Chatbot))
165+ .nest(
166+ "/insights",
167+ gate(web::insights::routes(), &state, Module::Chatbot),
168+ )
164169 .nest("/users", web::users::routes())
165170 .nest("/notes", gate(web::notes::routes(), &state, Module::Notes))
166171 .nest(
src/web/insights.rsadded+818 -0
@@ -0,0 +1,818 @@
1+//! The insight nest: the read surface over ZEKA's own tables, plus the two
2+//! doors that ask ZEKA to compute.
3+//!
4+//! ZEKA (`hezarfen_zeka`) is an AI service that dials in over the QUIC bridge
5+//! and **writes its own rows** into each school database — the `zeka_*`
6+//! tables created by the school migrator. The backend never composes those
7+//! rows; it reads them here and, on request, asks the service to compute
8+//! (the dispatch contract lives in [`crate::ai::insight`]).
9+//!
10+//! Reading is authorized the way every per-student report in this API is:
11+//! [`service::parent_link::ensure_can_observe`] decides whether the caller
12+//! may read *that student* at all (teacher+ clears it, a parent needs a live
13+//! link), and a teacher is then narrowed to the students they actually reach
14+//! — a shared class×course instance, asked through
15+//! [`service::instance::visible_instances`]. A student who is not the subject
16+//! reads `404`, never `403`: a foreign id is indistinguishable from a missing
17+//! one, the same posture `/marks/{user}` and `/rag/threads/{id}` take.
18+//!
19+//! What each door deliberately does **not** return is as much of the contract
20+//! as what it does (ZEKA's output contract,
21+//! `hezarfen_zeka/service/docs/CIKTI-SOZLESMESI.md` §5):
22+//!
23+//! * The attention list is a teacher's tool. It never appears in
24+//! [`my_insight`], and a linked parent reading their child does not get it
25+//! either — only staff at `teacher` or above do.
26+//! * A card's `about` (another student's id) never reaches a student caller.
27+//! * Segment rows with `confidence = 'none'` (fewer than 30 answers) are
28+//! filtered out: noise stays in the database, not on a screen.
29+//! * Dismissed and expired cards are filtered out of both card reads — the
30+//! application closes a card by stamping `dismissed_at`, and a closed card
31+//! must not come back. (The dismiss **write** is not built here: nothing in
32+//! this batch asked for it, and it needs its own decision on who may stamp
33+//! the audit trail. `deferred`, not half-done.)
34+//!
35+//! Sending is detached, like every other AI round trip in this API: the
36+//! compute doors answer `202` the moment the work is queued, because a
37+//! student's compute can outlast the request-timeout layer
38+//! ([`crate::constant::REQUEST_TIMEOUT_SECS`]). The client polls the stored
39+//! rows — the compute doors change nothing a reader cannot already see.
40+
41+use axum::Json;
42+use axum::extract::{Path, Query};
43+use axum::http::StatusCode;
44+use axum::response::{IntoResponse, Response};
45+use serde::{Deserialize, Serialize};
46+use serde_json::Value as JsonValue;
47+use sqlx::types::Json as SqlJson;
48+use utoipa::ToSchema;
49+use utoipa_axum::router::OpenApiRouter;
50+use utoipa_axum::routes;
51+
52+use crate::ai::insight::{self, RefreshRequest, StudentRequest};
53+use crate::constant::{AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY};
54+use crate::database::Database;
55+use crate::domain::class_group::ClassGroupId;
56+use crate::domain::course::CourseId;
57+use crate::domain::role::Role;
58+use crate::domain::user::{User, UserId};
59+use crate::error::{AppError, ErrorResponse, ValidationError};
60+use crate::service;
61+use crate::service::parent_link::ensure_can_observe;
62+use crate::state::AppState;
63+use crate::tenant::ResolvedTenant;
64+use crate::web::tenant_state::State;
65+
66+use super::{CurrentUser, Page, PageParams, RequireManager, ai_unavailable, paginate};
67+
68+/// The single `now` every card read is filtered against. ZEKA stores unix
69+/// milliseconds, so "expired" is a comparison, not a projection.
70+fn now_millis() -> i64 {
71+ crate::domain::timestamp::Timestamp::now().as_millis()
72+}
73+
74+pub fn routes() -> OpenApiRouter<AppState> {
75+ OpenApiRouter::new()
76+ .routes(routes!(refresh))
77+ .routes(routes!(my_insight))
78+ .routes(routes!(student_insight, compute_student))
79+ .routes(routes!(list_runs))
80+}
81+
82+// ---- the compute doors -----------------------------------------------------
83+
84+/// The receipt for a queued dispatch. It carries no id: what was started is
85+/// not a row of ours, and the work's own record is ZEKA's (`zeka_run` for a
86+/// refresh, a student's `computed_at` for a compute).
87+#[derive(Serialize, ToSchema)]
88+struct AcceptedResponse {
89+ /// Always `accepted` — the field exists so a client can branch on the
90+ /// body rather than on the status code alone.
91+ #[schema(example = "accepted")]
92+ status: String,
93+}
94+
95+#[derive(Deserialize, ToSchema, Default)]
96+struct ComputeStudentRequest {
97+ /// ISO-8601 date to compute from; omit for the dönem's beginning.
98+ #[schema(example = "2026-09-01")]
99+ since: Option<String>,
100+ /// Compute only these sections; omit for all of them.
101+ sections: Option<Vec<String>>,
102+}
103+
104+#[derive(Deserialize, ToSchema, Default)]
105+struct RefreshInsightsRequest {
106+ /// Student user ids to recompute; omit for the service's own configured
107+ /// list — the backend does not enumerate a school roster for it.
108+ user_ids: Option<Vec<String>>,
109+ /// Recompute even where the service considers its cached result valid.
110+ force: Option<bool>,
111+}
112+
113+/// Ask ZEKA to recompute one student's insight, detached. `202` means queued,
114+/// not computed: the service works through the student's data and writes its
115+/// `zeka_*` rows on its own, and `GET /insights/students/{id}` shows them as
116+/// soon as they land. `503` when no service offers `insight.student` — and
117+/// nothing is queued.
118+///
119+/// Authorization is [`student_insight`]'s, gate for gate: the caller must be
120+/// able to read the student before they may ask for a recompute, and the
121+/// refusal is a `404` (a foreign id and a missing one look the same).
122+#[utoipa::path(
123+ post,
124+ path = "/students/{user}",
125+ tag = "insights",
126+ security(("session_cookie" = [])),
127+ params(("user" = String, Path, description = "User id")),
128+ request_body = ComputeStudentRequest,
129+ responses(
130+ (status = 202, description = "Queued; the service writes the rows on its own", body = AcceptedResponse),
131+ (status = 401, description = "Not authenticated", body = ErrorResponse),
132+ (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
133+ (status = 404, description = "Not found — no such student, or not one the caller may read", body = ErrorResponse),
134+ (status = 503, description = "No AI service offers `insight.student` right now; nothing was queued", body = ErrorResponse),
135+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
136+ ),
137+)]
138+async fn compute_student(
139+ State(st): State<AppState>,
140+ tenant: ResolvedTenant,
141+ CurrentUser(user): CurrentUser,
142+ Path(id): Path<String>,
143+ body: Option<Json<ComputeStudentRequest>>,
144+) -> Result<Response, AppError> {
145+ let target = UserId::from_key(&id);
146+ ensure_can_read(&user, &target, &st.db).await?;
147+
148+ let body = body.map(|Json(body)| body).unwrap_or_default();
149+ let request = StudentRequest {
150+ user_id: target.key(),
151+ since: body.since,
152+ sections: body.sections,
153+ };
154+ let Some(bridge) = st.ai.clone() else {
155+ return Ok(ai_unavailable(
156+ "the AI service is not enabled on this deployment",
157+ ));
158+ };
159+ if !bridge.has_capability(AI_INSIGHT_STUDENT_CAPABILITY) {
160+ return Ok(ai_unavailable("no AI service is connected right now"));
161+ }
162+ let slug = tenant.slug.clone();
163+ tokio::spawn(async move {
164+ match insight::compute_student(&bridge, &slug, &request).await {
165+ Ok(answer) => tracing::info!(
166+ "insight.student answered for {}: {} signal(s), {} recommendation(s)",
167+ request.user_id,
168+ answer.signals.len(),
169+ answer.recommendations.len()
170+ ),
171+ Err(err) => tracing::warn!("insight.student failed for {}: {err}", request.user_id),
172+ }
173+ });
174+
175+ Ok(accepted())
176+}
177+
178+/// Ask ZEKA to recompute the whole school's insights, detached. `202` means
179+/// queued; the sweep's own record is `zeka_run`, which `GET /insights/runs`
180+/// reads — poll that to watch a run move from `running` to its verdict.
181+///
182+/// Manager+ only: this is a school-wide batch, and the run it starts spends
183+/// the service's whole time budget. `503` when no service offers
184+/// `insight.refresh` — nothing is queued.
185+#[utoipa::path(
186+ post,
187+ path = "/refresh",
188+ tag = "insights",
189+ security(("session_cookie" = [])),
190+ request_body = RefreshInsightsRequest,
191+ responses(
192+ (status = 202, description = "Queued; the service writes its run ledger on its own", body = AcceptedResponse),
193+ (status = 400, description = "`user_ids` names something that is not a user id", body = ErrorResponse),
194+ (status = 401, description = "Not authenticated", body = ErrorResponse),
195+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
196+ (status = 503, description = "No AI service offers `insight.refresh` right now; nothing was queued", body = ErrorResponse),
197+ (status = 422, description = "The body does not fit this request: a field has the wrong type"),
198+ ),
199+)]
200+async fn refresh(
201+ State(st): State<AppState>,
202+ tenant: ResolvedTenant,
203+ RequireManager(_user): RequireManager,
204+ body: Option<Json<RefreshInsightsRequest>>,
205+) -> Result<Response, AppError> {
206+ let body = body.map(|Json(body)| body).unwrap_or_default();
207+ let request = RefreshRequest {
208+ user_ids: normalized_ids(body.user_ids)?,
209+ force: body.force,
210+ };
211+ let Some(bridge) = st.ai.clone() else {
212+ return Ok(ai_unavailable(
213+ "the AI service is not enabled on this deployment",
214+ ));
215+ };
216+ if !bridge.has_capability(AI_INSIGHT_REFRESH_CAPABILITY) {
217+ return Ok(ai_unavailable("no AI service is connected right now"));
218+ }
219+
220+ let slug = tenant.slug.clone();
221+ tokio::spawn(async move {
222+ match insight::refresh(&bridge, &slug, &request).await {
223+ Ok(answer) => tracing::info!(
224+ "insight.refresh answered: {} requested, {} computed, {} skipped, {} failed",
225+ answer.requested.unwrap_or(0),
226+ answer.computed.unwrap_or(0),
227+ answer.skipped.unwrap_or(0),
228+ answer.failed.len()
229+ ),
230+ Err(err) => tracing::warn!("insight.refresh failed: {err}"),
231+ }
232+ });
233+
234+ Ok(accepted())
235+}
236+
237+fn accepted() -> Response {
238+ (
239+ StatusCode::ACCEPTED,
240+ Json(AcceptedResponse {
241+ status: "accepted".to_string(),
242+ }),
243+ )
244+ .into_response()
245+}
246+
247+/// Canonicalize the ids a refresh body names — through the same parser every
248+/// route uses for a wire id, so a client cannot hand the service a spelling
249+/// this backend itself would never produce. Anything that parses as no uuid
250+/// is a `400`: unlike a path segment (where garbage reads as the nil id and
251+/// matches no row), a batch naming students is a list this backend must not
252+/// forward half-understood.
253+fn normalized_ids(ids: Option<Vec<String>>) -> Result<Option<Vec<String>>, AppError> {
254+ ids.map(|ids| {
255+ ids.into_iter()
256+ .map(|id| {
257+ let parsed = UserId::from_key(&id);
258+ if parsed.uuid().is_nil() {
259+ Err(AppError::Validation(ValidationError::Invalid {
260+ field: "user_ids",
261+ reason: "must be user ids",
262+ }))
263+ } else {
264+ Ok(parsed.key())
265+ }
266+ })
267+ .collect::<Result<Vec<String>, AppError>>()
268+ })
269+ .transpose()
270+}
271+
272+// ---- the reads -------------------------------------------------------------
273+
274+/// One student's nightly summary. The four module objects are ZEKA's own
275+/// shapes (JSONB, by design): read a member by name, never by position. `null`
276+/// for a module the run could not compute — an empty object and a missing
277+/// module are different claims, and only one of them is true.
278+#[derive(Serialize, ToSchema)]
279+struct SummaryResponse {
280+ marks: Option<JsonValue>,
281+ attendance: Option<JsonValue>,
282+ submission: Option<JsonValue>,
283+ study: Option<JsonValue>,
284+ /// The weakest input's tier: `none` | `exploratory` | `stable`.
285+ #[schema(example = "stable")]
286+ confidence: String,
287+ /// UTC unix milliseconds the summary was computed at — the stamp a
288+ /// client polls for after asking for a recompute.
289+ computed_at: i64,
290+ /// UTC unix milliseconds after which the sweep deletes the row.
291+ retain_until: i64,
292+}
293+
294+/// One entry of the attention list — a statement of fact about a window, not
295+/// a judgement. **Teacher-facing**: it is never returned to the student it is
296+/// about (see the module docs).
297+#[derive(Serialize, ToSchema)]
298+struct AttentionItemResponse {
299+ /// Which trigger fired: `attendance` | `homework` | `mark_trend` today —
300+ /// a fourth trigger is a rule change, so treat this as an open set.
301+ #[schema(example = "attendance")]
302+ trigger: String,
303+ /// The course the trigger is about, when it has one; `null` = school-wide.
304+ course: Option<String>,
305+ /// The sentence the teacher reads, written once at compute time.
306+ fact: String,
307+ /// UTC unix milliseconds — the window the fact is about.
308+ window_from: i64,
309+ window_to: i64,
310+ /// The numbers behind the fact, for the "neden?" panel. Never empty.
311+ evidence: JsonValue,
312+}
313+
314+/// One recommendation card addressed to the caller. It carries no
315+/// `dismissed_at`/`dismiss_by`: a dismissed card is filtered out of both card
316+/// reads, so the field could only ever be null — and a face that never
317+/// arrives is worse than no face.
318+#[derive(Serialize, ToSchema)]
319+struct RecommendationResponse {
320+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
321+ id: String,
322+ /// The product family: `O1` … `O4` for students, `T3`/`T4` for teachers.
323+ #[schema(example = "T4")]
324+ product: String,
325+ /// Which rule produced it, and which version of that rule.
326+ #[schema(example = "T4.attendance")]
327+ rule_id: String,
328+ rule_version: i64,
329+ /// The rule's optional scope segment; `null` when the rule has none.
330+ scope: Option<String>,
331+ /// Who the card is about; `null` on a card addressed to its subject
332+ /// (a student's own card), and never returned to a student caller.
333+ about: Option<String>,
334+ /// The role gate the card was written for: `student` | `teacher` |
335+ /// `parent` | `manager`.
336+ audience_role: String,
337+ course: Option<String>,
338+ /// The numbers behind the card, including the mandatory `limitation`
339+ /// line. Never empty.
340+ evidence: JsonValue,
341+ confidence: String,
342+ created_at: i64,
343+ /// After this instant the card is past; expired rows are filtered out of
344+ /// both reads.
345+ expires_at: i64,
346+}
347+
348+/// One student × dimension × label row. `accuracy` is returned alongside
349+/// `contrast` and never alone: raw accuracy carries general ability, and
350+/// `contrast = accuracy − overall_accuracy` is the part specific to the
351+/// segment.
352+#[derive(Serialize, ToSchema)]
353+struct SegmentProfileResponse {
354+ /// A production dimension: `bilissel_talep` | `dikkat_tuzagi` |
355+ /// `okuma_yuku` (the experimental `adim_sayisi` never reaches a student).
356+ #[schema(example = "bilissel_talep")]
357+ dimension: String,
358+ #[schema(example = "analiz")]
359+ label: String,
360+ n_answers: i64,
361+ n_correct: i64,
362+ /// The segment's hit rate, `n_correct / n_answers`.
363+ accuracy: f64,
364+ /// The student's hit rate across all labelled items — the subtrahend, on
365+ /// the row so the evidence panel can show the comparison.
366+ overall_n_answers: i64,
367+ overall_accuracy: f64,
368+ /// The honest measure: `accuracy − overall_accuracy`. Negative = behind
369+ /// the student's own general level in this segment.
370+ contrast: f64,
371+ confidence: String,
372+ computed_at: i64,
373+}
374+
375+/// One student's whole readable insight: the stored summary, the caller's own
376+/// cards about them, and the segment profile.
377+#[derive(Serialize, ToSchema)]
378+struct StudentInsightResponse {
379+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
380+ user_id: String,
381+ /// `null` until ZEKA has computed this student at least once.
382+ summary: Option<SummaryResponse>,
383+ /// Teacher-facing; always empty for the subject's own view and for a
384+ /// linked parent.
385+ attention: Vec<AttentionItemResponse>,
386+ /// Cards addressed to the caller about this student — nobody else's cards
387+ /// appear here, so two teachers reading one student each see their own.
388+ cards: Vec<RecommendationResponse>,
389+ segments: Vec<SegmentProfileResponse>,
390+}
391+
392+/// The caller's own insight. Students get their summary, their own cards and
393+/// their segment profile — **never** the attention list about themselves.
394+/// Any other role gets the cards addressed to them (a teacher's `T4` cards
395+/// about their students), with `summary`/`segments` empty.
396+#[utoipa::path(
397+ get,
398+ path = "/me",
399+ tag = "insights",
400+ security(("session_cookie" = [])),
401+ responses(
402+ (status = 200, description = "The caller's own insight", body = StudentInsightResponse),
403+ (status = 401, description = "Not authenticated", body = ErrorResponse),
404+ ),
405+)]
406+async fn my_insight(
407+ State(st): State<AppState>,
408+ CurrentUser(user): CurrentUser,
409+) -> Result<Json<StudentInsightResponse>, AppError> {
410+ let id = user.get_id();
411+ let student = user.get_role() == Role::Student;
412+ Ok(Json(StudentInsightResponse {
413+ user_id: id.key(),
414+ summary: if student {
415+ summary_of(&st.db, id).await?
416+ } else {
417+ None
418+ },
419+ attention: Vec::new(),
420+ cards: cards_of(&st.db, id, user.get_role(), None).await?,
421+ segments: if student {
422+ segments_of(&st.db, id).await?
423+ } else {
424+ Vec::new()
425+ },
426+ }))
427+}
428+
429+/// One student's insight, as an observer reads it. Teacher+ (narrowed to the
430+/// students they reach) or a parent holding a live link to that student;
431+/// everyone else — other students included — gets the same `404` a missing id
432+/// gets.
433+#[utoipa::path(
434+ get,
435+ path = "/students/{user}",
436+ tag = "insights",
437+ security(("session_cookie" = [])),
438+ params(("user" = String, Path, description = "User id")),
439+ responses(
440+ (status = 200, description = "The student's insight, plus the caller's own cards about them", body = StudentInsightResponse),
441+ (status = 401, description = "Not authenticated", body = ErrorResponse),
442+ (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
443+ (status = 404, description = "Not found — no such student, or not one the caller may read", body = ErrorResponse),
444+ ),
445+)]
446+async fn student_insight(
447+ State(st): State<AppState>,
448+ CurrentUser(user): CurrentUser,
449+ Path(id): Path<String>,
450+) -> Result<Json<StudentInsightResponse>, AppError> {
451+ let target = UserId::from_key(&id);
452+ ensure_can_read(&user, &target, &st.db).await?;
453+ let staff = user.get_role().at_least(Role::Teacher);
454+ Ok(Json(StudentInsightResponse {
455+ user_id: target.key(),
456+ summary: summary_of(&st.db, &target).await?,
457+ attention: if staff {
458+ attention_of(&st.db, &target).await?
459+ } else {
460+ Vec::new()
461+ },
462+ cards: cards_of(&st.db, user.get_id(), user.get_role(), Some(&target)).await?,
463+ segments: segments_of(&st.db, &target).await?,
464+ }))
465+}
466+
467+/// One compute run, as the ledger keeps it.
468+#[derive(Serialize, ToSchema)]
469+struct InsightRunResponse {
470+ /// The run's key: `YYYY-MM-DD`, so a re-run of the same night overwrites
471+ /// rather than duplicating.
472+ #[schema(example = "2026-09-17")]
473+ run_day: String,
474+ started_at: i64,
475+ finished_at: Option<i64>,
476+ /// `running` | `ok` | `partial` | `failed` | `skipped`. A `partial` run
477+ /// must be shown as such: some students were not processed.
478+ #[schema(example = "partial")]
479+ status: String,
480+ duration_ms: Option<i64>,
481+ students_total: i64,
482+ students_ok: i64,
483+ students_failed: i64,
484+ students_skipped: i64,
485+ rows_written: i64,
486+ /// Whether the run hit its time budget before finishing.
487+ budget_exceeded: bool,
488+ budget_ms: i64,
489+ /// The students the budget ran out on; the next run starts here. Kept for
490+ /// the management view, which is the only caller of this route.
491+ pending_students: Vec<String>,
492+ /// Modules that failed, one per row — so a section can be marked missing
493+ /// instead of shown as a hole.
494+ failed_modules: Vec<String>,
495+}
496+
497+/// The run ledger, newest first. Manager+ only: `pending_students` is a list
498+/// of people, and ZEKA's output contract confines it to the management view.
499+/// Paged via `?limit=&offset=`.
500+#[utoipa::path(
501+ get,
502+ path = "/runs",
503+ tag = "insights",
504+ security(("session_cookie" = [])),
505+ params(PageParams),
506+ responses(
507+ (status = 200, description = "The school's compute runs, newest first", body = Page<InsightRunResponse>),
508+ (status = 400, description = "`limit` or `offset` out of range", body = ErrorResponse),
509+ (status = 401, description = "Not authenticated", body = ErrorResponse),
510+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
511+ ),
512+)]
513+async fn list_runs(
514+ State(st): State<AppState>,
515+ RequireManager(_user): RequireManager,
516+ Query(page): Query<PageParams>,
517+) -> Result<Json<Page<InsightRunResponse>>, AppError> {
518+ let (limit, offset) = page.resolve()?;
519+ let rows = sqlx::query!(
520+ r#"SELECT run_day, started_at, finished_at, status, duration_ms,
521+ students_total, students_ok, students_failed, students_skipped,
522+ rows_written, budget_exceeded, budget_ms
523+ FROM zeka_run
524+ ORDER BY started_at DESC, run_day DESC"#
525+ )
526+ .fetch_all(&st.db)
527+ .await?;
528+ let total = rows.len() as i64;
529+ let window = paginate(&rows, limit, offset);
530+ let days: Vec<String> = window.iter().map(|row| row.run_day.clone()).collect();
531+ let mut pending = children_of(&st.db, "pending", &days).await?;
532+ let mut failed = children_of(&st.db, "failed", &days).await?;
533+ let items = window
534+ .iter()
535+ .map(|row| InsightRunResponse {
536+ run_day: row.run_day.clone(),
537+ started_at: row.started_at,
538+ finished_at: row.finished_at,
539+ status: row.status.clone(),
540+ duration_ms: row.duration_ms,
541+ students_total: row.students_total,
542+ students_ok: row.students_ok,
543+ students_failed: row.students_failed,
544+ students_skipped: row.students_skipped,
545+ rows_written: row.rows_written,
546+ budget_exceeded: row.budget_exceeded,
547+ budget_ms: row.budget_ms,
548+ pending_students: pending.remove(&row.run_day).unwrap_or_default(),
549+ failed_modules: failed.remove(&row.run_day).unwrap_or_default(),
550+ })
551+ .collect();
552+ Ok(Json(Page::new(items, total, limit, offset)))
553+}
554+
555+/// The children of the runs on this page — one query for the whole page, not
556+/// one per run, grouped by run day in `ord` order.
557+async fn children_of(
558+ db: &Database,
559+ kind: &str,
560+ days: &[String],
561+) -> Result<std::collections::HashMap<String, Vec<String>>, AppError> {
562+ if days.is_empty() {
563+ return Ok(std::collections::HashMap::new());
564+ }
565+ let mut grouped: std::collections::HashMap<String, Vec<String>> =
566+ std::collections::HashMap::new();
567+ match kind {
568+ "pending" => {
569+ for row in sqlx::query!(
570+ r#"SELECT run, student FROM zeka_run_pending
571+ WHERE run = ANY($1) ORDER BY run, ord"#,
572+ days
573+ )
574+ .fetch_all(db)
575+ .await?
576+ {
577+ grouped
578+ .entry(row.run)
579+ .or_default()
580+ .push(row.student.to_string());
581+ }
582+ }
583+ "failed" => {
584+ for row in sqlx::query!(
585+ r#"SELECT run, module FROM zeka_run_failed_module
586+ WHERE run = ANY($1) ORDER BY run, ord"#,
587+ days
588+ )
589+ .fetch_all(db)
590+ .await?
591+ {
592+ grouped.entry(row.run).or_default().push(row.module);
593+ }
594+ }
595+ other => unreachable!("unknown run child table: {other}"),
596+ }
597+ Ok(grouped)
598+}
599+
600+// ---- the queries -----------------------------------------------------------
601+
602+/// The nightly summary, or `None` until ZEKA has computed this student once.
603+async fn summary_of(db: &Database, student: &UserId) -> Result<Option<SummaryResponse>, AppError> {
604+ let row = sqlx::query!(
605+ r#"SELECT marks AS "marks?: SqlJson<JsonValue>",
606+ attendance AS "attendance?: SqlJson<JsonValue>",
607+ submission AS "submission?: SqlJson<JsonValue>",
608+ study AS "study?: SqlJson<JsonValue>",
609+ confidence, computed_at, retain_until
610+ FROM zeka_student_summary WHERE student = $1"#,
611+ student.uuid(),
612+ )
613+ .fetch_optional(db)
614+ .await?;
615+ Ok(row.map(|row| SummaryResponse {
616+ marks: row.marks.map(|json| json.0),
617+ attendance: row.attendance.map(|json| json.0),
618+ submission: row.submission.map(|json| json.0),
619+ study: row.study.map(|json| json.0),
620+ confidence: row.confidence,
621+ computed_at: row.computed_at,
622+ retain_until: row.retain_until,
623+ }))
624+}
625+
626+/// The attention list, in the writer's own order. Only staff at `teacher` or
627+/// above ever call this — see the module docs.
628+async fn attention_of(
629+ db: &Database,
630+ student: &UserId,
631+) -> Result<Vec<AttentionItemResponse>, AppError> {
632+ let rows = sqlx::query!(
633+ r#"SELECT trigger, course AS "course?: CourseId",
634+ fact, window_from, window_to,
635+ evidence AS "evidence: SqlJson<JsonValue>"
636+ FROM zeka_attention_item WHERE student = $1 ORDER BY ord"#,
637+ student.uuid(),
638+ )
639+ .fetch_all(db)
640+ .await?;
641+ Ok(rows
642+ .into_iter()
643+ .map(|row| AttentionItemResponse {
644+ trigger: row.trigger,
645+ course: row.course.map(|course| course.key().to_string()),
646+ fact: row.fact,
647+ window_from: row.window_from,
648+ window_to: row.window_to,
649+ evidence: row.evidence.0,
650+ })
651+ .collect())
652+}
653+
654+/// Cards addressed to `audience`, filtered to the label the caller's own role
655+/// reads (`audience_role`) and to cards that are still live: not expired, not
656+/// dismissed. `about` narrows to one student — `None` is the caller's own
657+/// card list, which for a teacher is the `T4` cards about their students.
658+async fn cards_of(
659+ db: &Database,
660+ audience: &UserId,
661+ role: Role,
662+ about: Option<&UserId>,
663+) -> Result<Vec<RecommendationResponse>, AppError> {
664+ let rows = sqlx::query!(
665+ r#"SELECT id, product, rule_id, rule_version, scope,
666+ about AS "about?: UserId",
667+ audience_role, course AS "course?: CourseId",
668+ evidence AS "evidence: SqlJson<JsonValue>",
669+ confidence, created_at, expires_at
670+ FROM zeka_recommendation
671+ WHERE audience = $1 AND audience_role = $2
672+ AND ($3::uuid IS NULL OR about = $3)
673+ AND expires_at > $4 AND dismissed_at IS NULL
674+ ORDER BY created_at DESC, id"#,
675+ audience.uuid(),
676+ audience_role(role),
677+ about.map(UserId::uuid),
678+ now_millis(),
679+ )
680+ .fetch_all(db)
681+ .await?;
682+ Ok(rows
683+ .into_iter()
684+ .map(|row| RecommendationResponse {
685+ id: row.id.to_string(),
686+ product: row.product,
687+ rule_id: row.rule_id,
688+ rule_version: row.rule_version,
689+ scope: row.scope,
690+ // A student's own card has no `about` in the database, and the
691+ // contract forbids one reaching a student caller even if a rule
692+ // ever set it — so the value is dropped for a student caller, not
693+ // merely absent.
694+ about: (role != Role::Student)
695+ .then(|| row.about)
696+ .flatten()
697+ .map(|about| about.key().to_string()),
698+ audience_role: row.audience_role,
699+ course: row.course.map(|course| course.key().to_string()),
700+ evidence: row.evidence.0,
701+ confidence: row.confidence,
702+ created_at: row.created_at,
703+ expires_at: row.expires_at,
704+ })
705+ .collect())
706+}
707+
708+/// The segment profile, noise filtered out: a row below 30 answers
709+/// (`confidence = 'none'`) stays in the database and off every screen.
710+async fn segments_of(
711+ db: &Database,
712+ student: &UserId,
713+) -> Result<Vec<SegmentProfileResponse>, AppError> {
714+ let rows = sqlx::query!(
715+ r#"SELECT dimension, label, n_answers, n_correct, accuracy,
716+ overall_n_answers, overall_accuracy, contrast, confidence,
717+ computed_at
718+ FROM zeka_student_segment_profile
719+ WHERE student = $1 AND confidence <> 'none'
720+ ORDER BY dimension, label"#,
721+ student.uuid(),
722+ )
723+ .fetch_all(db)
724+ .await?;
725+ Ok(rows
726+ .into_iter()
727+ .map(|row| SegmentProfileResponse {
728+ dimension: row.dimension,
729+ label: row.label,
730+ n_answers: row.n_answers,
731+ n_correct: row.n_correct,
732+ accuracy: row.accuracy,
733+ overall_n_answers: row.overall_n_answers,
734+ overall_accuracy: row.overall_accuracy,
735+ contrast: row.contrast,
736+ confidence: row.confidence,
737+ computed_at: row.computed_at,
738+ })
739+ .collect())
740+}
741+
742+// ---- authorization ---------------------------------------------------------
743+
744+/// The one gate every per-student insight route shares, read and compute
745+/// alike.
746+///
747+/// [`ensure_can_observe`] settles the role question — teacher+ clears it, a
748+/// parent needs a live link — and the student a caller may *reach* is then
749+/// narrowed the same way `/marks/{user}` narrows a report: a teacher reads a
750+/// student only when they run an instance that student sits in. The narrowing
751+/// is a `404` rather than an empty body because the insight rows are not
752+/// per-instance: there is nothing honest to narrow *to*, and a foreign
753+/// student's id must be indistinguishable from a missing one.
754+async fn ensure_can_read(caller: &User, target: &UserId, db: &Database) -> Result<(), AppError> {
755+ ensure_can_observe(caller, target, db).await?;
756+ let target = service::user::read(db, target)
757+ .await?
758+ .ok_or(AppError::NotFound)?;
759+ // Only a student has insights: a colleague's id is not a narrower report,
760+ // it is a 404.
761+ if target.get_role() != Role::Student {
762+ return Err(AppError::NotFound);
763+ }
764+ if caller.get_role() == Role::Teacher && !teacher_reaches(db, caller, target.get_id()).await? {
765+ return Err(AppError::NotFound);
766+ }
767+ Ok(())
768+}
769+
770+/// Does this teacher actually reach this student — a shared class×course
771+/// instance the teacher runs and the student sits in? The instances a teacher
772+/// runs are [`service::instance::visible_instances`]'s `manages` half, which
773+/// is the same D10 rule every instance-scoped route applies
774+/// ([`service::class_course::ensure_instance_teacher`]): an assigned teacher
775+/// or the şube's homeroom teacher, and nobody else.
776+async fn teacher_reaches(
777+ db: &Database,
778+ teacher: &User,
779+ student: &UserId,
780+) -> Result<bool, AppError> {
781+ let (members, _) = crate::db::class_member::list_for_user(db, student, None, 0).await?;
782+ let classes: Vec<ClassGroupId> = members
783+ .iter()
784+ .map(|member| member.get_class().clone())
785+ .collect();
786+ if classes.is_empty() {
787+ return Ok(false);
788+ }
789+ let runs: Vec<uuid::Uuid> = service::instance::visible_instances(teacher, db)
790+ .await?
791+ .into_iter()
792+ .filter(|(_, manages)| *manages)
793+ .map(|(instance, _)| instance.get_id().uuid())
794+ .collect();
795+ if runs.is_empty() {
796+ return Ok(false);
797+ }
798+ Ok(crate::db::class_course::list_for_class_ids(db, &classes)
799+ .await?
800+ .iter()
801+ .any(|instance| runs.contains(&instance.get_id().uuid())))
802+}
803+
804+/// The `audience_role` label a caller reads cards under. ZEKA's catalogue
805+/// closes four labels (`student` | `teacher` | `parent` | `manager`); the two
806+/// staff ranks above teacher fold into `manager`, and the bridge's own
807+/// principal reads under a label no row can carry (the column's CHECK lists
808+/// the human four) — so a service reading as itself gets the empty list an
809+/// absent surface should give it.
810+fn audience_role(role: Role) -> &'static str {
811+ match role {
812+ Role::Student => "student",
813+ Role::Parent => "parent",
814+ Role::Teacher => "teacher",
815+ Role::Manager | Role::Admin => "manager",
816+ Role::Ai => "ai",
817+ }
818+}
src/web/mod.rsmodified+1 -0
@@ -21,6 +21,7 @@ pub mod events;
2121 pub mod exam_ws;
2222 pub mod exams;
2323 pub mod homework;
24+pub mod insights;
2425 pub mod instances;
2526 pub mod limits;
2627 pub mod marks;
tests/ai_bridge.rsmodified+147 -0
@@ -3354,3 +3354,150 @@ async fn a_rag_stream_replays_a_settled_turn_with_its_citations() {
33543354 assert_eq!(citation["span_ids"], json!(["s-1"]), "{message}");
33553355 assert_eq!(citation["ders"], "Fizik", "{message}");
33563356 }
3357+
3358+// ---- insights ----------------------------------------------------------
3359+
3360+use hezarfen_backend::ai::insight;
3361+use hezarfen_backend::constant::{AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY};
3362+
3363+/// Wait until the fake service has seen `expected` requests. The compute doors
3364+/// dispatch off the request path, so the frame lands when it lands.
3365+async fn await_seen(service: &FakeService, expected: usize) -> Vec<Request> {
3366+ for _ in 0..500 {
3367+ let seen = service.seen();
3368+ if seen.len() >= expected {
3369+ return seen;
3370+ }
3371+ tokio::time::sleep(Duration::from_millis(10)).await;
3372+ }
3373+ panic!("the service never saw {expected} request(s)");
3374+}
3375+
3376+/// The outbound half of `hab/2` for `insight.student`: the door dispatches to
3377+/// the worker carrying that exact capability, the frame names the school the
3378+/// caller acted in, and the answer round-trips back through the typed
3379+/// contract.
3380+#[tokio::test]
3381+async fn an_insight_student_dispatch_names_the_school_and_round_trips() {
3382+ let bridge = bridge().await;
3383+ let service = connect_service(
3384+ &bridge,
3385+ hello("zeka", &[AI_INSIGHT_STUDENT_CAPABILITY]),
3386+ Behaviour::Answer(json!({
3387+ "user_id": "echoed-back",
3388+ "generated_at": "2026-09-17T00:00:00Z",
3389+ "archetype": "ezberci",
3390+ "signals": [],
3391+ "recommendations": [],
3392+ "coverage": { "marks": 4 },
3393+ })),
3394+ )
3395+ .await;
3396+ await_workers(&bridge, 1).await;
3397+ let (app, db) = chat_app(&bridge).await;
3398+
3399+ // A manager may read any student, so the reach gate is out of this test's
3400+ // way; the student is the subject.
3401+ let staff = common::login_as(&app, &db, "mudur", "manager").await;
3402+ let student = common::login(&app, "ali").await;
3403+ let ali = common::me_id(&app, &student).await;
3404+
3405+ let res = common::send(
3406+ &app,
3407+ "POST",
3408+ &format!("/insights/students/{ali}"),
3409+ Some(&staff),
3410+ Some(json!({})),
3411+ )
3412+ .await;
3413+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
3414+
3415+ let seen = await_seen(&service, 1).await;
3416+ assert_eq!(seen.len(), 1, "one dispatch per request, never a re-send");
3417+ assert_eq!(seen[0].capability, AI_INSIGHT_STUDENT_CAPABILITY);
3418+ assert_eq!(seen[0].school, DEMO_SLUG, "the frame names the school");
3419+ assert_eq!(seen[0].payload["user_id"], ali);
3420+
3421+ // The same worker driven directly answers the contract's shape, so the
3422+ // round trip — not only the send — is exercised: a reply the bridge could
3423+ // not parse would fail here.
3424+ let reply = insight::compute_student(
3425+ &bridge,
3426+ &demo(),
3427+ &hezarfen_backend::ai::StudentRequest {
3428+ user_id: ali.clone(),
3429+ since: None,
3430+ sections: None,
3431+ },
3432+ )
3433+ .await
3434+ .expect("the round trip answers");
3435+ assert_eq!(reply.user_id.as_deref(), Some("echoed-back"));
3436+ assert_eq!(reply.archetype.as_deref(), Some("ezberci"));
3437+ assert_eq!(reply.coverage, Some(json!({ "marks": 4 })));
3438+}
3439+
3440+/// Routing is exact-match, and the refusal is the shared `503`, not a `500`:
3441+/// a worker carrying only `insight.student` is no fallback for
3442+/// `insight.refresh`, and a refused door dispatches nothing at all.
3443+#[tokio::test]
3444+async fn no_insight_refresh_worker_means_503_and_nothing_is_dispatched() {
3445+ let bridge = bridge().await;
3446+ let service = connect_service(
3447+ &bridge,
3448+ hello("zeka", &[AI_INSIGHT_STUDENT_CAPABILITY]),
3449+ Behaviour::Echo,
3450+ )
3451+ .await;
3452+ await_workers(&bridge, 1).await;
3453+ assert!(
3454+ !bridge.has_capability(AI_INSIGHT_REFRESH_CAPABILITY),
3455+ "the premise: no worker carries insight.refresh"
3456+ );
3457+ let (app, db) = chat_app(&bridge).await;
3458+ let staff = common::login_as(&app, &db, "mudur", "manager").await;
3459+
3460+ let res = common::send(
3461+ &app,
3462+ "POST",
3463+ "/insights/refresh",
3464+ Some(&staff),
3465+ Some(json!({})),
3466+ )
3467+ .await;
3468+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
3469+ assert_eq!(res.body["error"], "no AI service is connected right now");
3470+ assert_eq!(
3471+ service.seen().len(),
3472+ 0,
3473+ "a refused refresh must not reach the student-only worker"
3474+ );
3475+
3476+ // The student door still routes to that same worker — the 503 above is the
3477+ // capability's absence, not the worker's.
3478+ let student = common::login(&app, "ali").await;
3479+ let ali = common::me_id(&app, &student).await;
3480+ let res = common::send(
3481+ &app,
3482+ "POST",
3483+ &format!("/insights/students/{ali}"),
3484+ Some(&staff),
3485+ Some(json!({})),
3486+ )
3487+ .await;
3488+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
3489+ assert_eq!(await_seen(&service, 1).await[0].payload["user_id"], ali);
3490+
3491+ // Under-privileged callers are refused before availability is even asked:
3492+ // the refresh door is manager+.
3493+ let veli = common::login(&app, "veli").await;
3494+ let res = common::send(
3495+ &app,
3496+ "POST",
3497+ "/insights/refresh",
3498+ Some(&veli),
3499+ Some(json!({})),
3500+ )
3501+ .await;
3502+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
3503+}
tests/integration.rsmodified+309 -3
@@ -434,7 +434,7 @@ async fn protected_routes_require_session() {
434434 /// Floor on the number of protected operations swept. It only ever goes
435435 /// up: raise it when routes are added. Without it, deleting a route family
436436 /// would delete its own coverage and still pass.
437- const MIN_PROTECTED: usize = 318;
437+ const MIN_PROTECTED: usize = 323;
438438
439439 let app = mem_app().await;
440440 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
@@ -29690,10 +29690,12 @@ const CORE_PREFIXES: [(&str, &str); 13] = [
2969029690 ///
2969129691 /// A module may own more than one prefix: `courses` also answers under
2969229692 /// `/instances` (the instance anchor), and `chatbot` — the whole `ai` package —
29693-/// also answers under `/rag`.
29694-const MODULE_PREFIXES: [(Module, &str); 23] = [
29693+/// also answers under `/rag`, `/insights` and `/podcast`.
29694+const MODULE_PREFIXES: [(Module, &str); 25] = [
2969529695 (Module::Chatbot, "/chatbot"),
2969629696 (Module::Chatbot, "/rag"),
29697+ (Module::Chatbot, "/insights"),
29698+ (Module::Chatbot, "/podcast"),
2969729699 (Module::Notes, "/notes"),
2969829700 (Module::Messages, "/messages"),
2969929701 (Module::Events, "/events"),
@@ -30009,3 +30011,307 @@ async fn login_ignores_a_leftover_school_field() {
3000930011 .await;
3001030012 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
3001130013 }
30014+
30015+// --- insights: ZEKA's own tables, read back ---------------------------------
30016+
30017+/// Seed one student's ZEKA rows the way the service writes them (the backend
30018+/// never composes one, only reads): a nightly summary, one attention item, a
30019+/// live card addressed to the homeroom teacher, a dismissed card and an
30020+/// expired card addressed to the student, one displayable segment row and one
30021+/// below the display floor.
30022+async fn seed_insight_rows(
30023+ db: &hezarfen_backend::database::Database,
30024+ course: &str,
30025+ student: &str,
30026+ teacher: &str,
30027+) {
30028+ let student_uuid = Uuid::parse_str(student).expect("student id");
30029+ let teacher_uuid = Uuid::parse_str(teacher).expect("teacher id");
30030+ let course_uuid = Uuid::parse_str(course).expect("course id");
30031+ let now = Timestamp::now().as_millis();
30032+
30033+ sqlx::query(
30034+ "INSERT INTO zeka_student_summary
30035+ (student, marks, attendance, submission, study, confidence, computed_at, retain_until)
30036+ VALUES ($1, '{\"courses\":{\"matematik\":{\"average\":72}}}'::jsonb, NULL, NULL, NULL,
30037+ 'stable', $2, $3)",
30038+ )
30039+ .bind(student_uuid)
30040+ .bind(now)
30041+ .bind(now + 400 * 86_400_000)
30042+ .execute(db)
30043+ .await
30044+ .unwrap();
30045+
30046+ sqlx::query(
30047+ "INSERT INTO zeka_attention_item
30048+ (student, trigger, course, fact, window_from, window_to, evidence, ord)
30049+ VALUES ($1, 'attendance', NULL, 'son 30 gunun 4 dersi kacirildi', $2, $3,
30050+ '{\"absent_days\":4}'::jsonb, 1)",
30051+ )
30052+ .bind(student_uuid)
30053+ .bind(now - 30 * 86_400_000)
30054+ .bind(now)
30055+ .execute(db)
30056+ .await
30057+ .unwrap();
30058+
30059+ let live_card = Uuid::now_v7();
30060+ sqlx::query(
30061+ "INSERT INTO zeka_recommendation
30062+ (id, audience, product, rule_id, rule_version, scope, about, audience_role,
30063+ course, evidence, confidence, created_at, expires_at, retain_until,
30064+ dismissed_at, dismissed_by, dismiss_reason)
30065+ VALUES ($1, $2, 'T4', 'T4.attendance', 1, NULL, $3, 'teacher', $4,
30066+ '{\"absent_days\":4,\"limitation\":\"yalniz ders yoklamasi\"}'::jsonb,
30067+ 'stable', $5, $6, $7, NULL, NULL, NULL)",
30068+ )
30069+ .bind(live_card)
30070+ .bind(teacher_uuid)
30071+ .bind(student_uuid)
30072+ .bind(course_uuid)
30073+ .bind(now)
30074+ .bind(now + 86_400_000)
30075+ .bind(now + 90 * 86_400_000)
30076+ .execute(db)
30077+ .await
30078+ .unwrap();
30079+
30080+ // Dismissed: the application's own audit trail — a card closed by its
30081+ // audience must never be shown again.
30082+ sqlx::query(
30083+ "INSERT INTO zeka_recommendation
30084+ (id, audience, product, rule_id, rule_version, scope, about, audience_role,
30085+ course, evidence, confidence, created_at, expires_at, retain_until,
30086+ dismissed_at, dismissed_by, dismiss_reason)
30087+ VALUES ($1, $2, 'O3', 'O3.pattern', 1, NULL, NULL, 'student', NULL,
30088+ '{\"n_stints\":7,\"limitation\":\"tek donem\"}'::jsonb,
30089+ 'stable', $3, $4, $5, $3, $2, 'bu dogru degil')",
30090+ )
30091+ .bind(Uuid::now_v7())
30092+ .bind(student_uuid)
30093+ .bind(now)
30094+ .bind(now + 86_400_000)
30095+ .bind(now + 90 * 86_400_000)
30096+ .execute(db)
30097+ .await
30098+ .unwrap();
30099+
30100+ // Expired: past its `expires_at`, so it is shown to nobody.
30101+ sqlx::query(
30102+ "INSERT INTO zeka_recommendation
30103+ (id, audience, product, rule_id, rule_version, scope, about, audience_role,
30104+ course, evidence, confidence, created_at, expires_at, retain_until,
30105+ dismissed_at, dismissed_by, dismiss_reason)
30106+ VALUES ($1, $2, 'O1', 'O1.review_band', 1, NULL, NULL, 'student', NULL,
30107+ '{\"band\":\"review\",\"limitation\":\"n=3\"}'::jsonb,
30108+ 'exploratory', $3, $4, $5, NULL, NULL, NULL)",
30109+ )
30110+ .bind(Uuid::now_v7())
30111+ .bind(student_uuid)
30112+ .bind(now - 10 * 86_400_000)
30113+ .bind(now - 86_400_000)
30114+ .bind(now + 90 * 86_400_000)
30115+ .execute(db)
30116+ .await
30117+ .unwrap();
30118+
30119+ sqlx::query(
30120+ "INSERT INTO zeka_student_segment_profile
30121+ (student, dimension, label, n_answers, n_correct, accuracy,
30122+ overall_n_answers, overall_accuracy, contrast, confidence,
30123+ computed_at, retain_until)
30124+ VALUES ($1, 'bilissel_talep', 'analiz', 120, 48, 0.40, 240, 0.55, -0.15,
30125+ 'stable', $2, $3)",
30126+ )
30127+ .bind(student_uuid)
30128+ .bind(now)
30129+ .bind(now + 400 * 86_400_000)
30130+ .execute(db)
30131+ .await
30132+ .unwrap();
30133+
30134+ // Below the display floor (n < 30): it stays in the database and off every
30135+ // screen, so a reader must not see this label.
30136+ sqlx::query(
30137+ "INSERT INTO zeka_student_segment_profile
30138+ (student, dimension, label, n_answers, n_correct, accuracy,
30139+ overall_n_answers, overall_accuracy, contrast, confidence,
30140+ computed_at, retain_until)
30141+ VALUES ($1, 'okuma_yuku', 'yuksek', 12, 9, 0.75, 240, 0.55, 0.20,
30142+ 'none', $2, $3)",
30143+ )
30144+ .bind(student_uuid)
30145+ .bind(now)
30146+ .bind(now + 400 * 86_400_000)
30147+ .execute(db)
30148+ .await
30149+ .unwrap();
30150+}
30151+
30152+/// The insight read is gated twice: role first (a student is refused outright),
30153+/// then reach (a teacher is `404`ed for a student they do not teach) — while
30154+/// the homeroom teacher of the student's own şube reads it whole, and the
30155+/// reader's own filters (dismissed/expired cards, noise segments, the
30156+/// attention list's audience) all hold.
30157+#[tokio::test]
30158+async fn insight_reads_are_gated_to_the_students_the_caller_reaches() {
30159+ let (app, db) = app_and_db().await;
30160+ let staff = login_as(&app, &db, "mudur", "manager").await;
30161+
30162+ let homeroom = login_as(&app, &db, "ayse", "teacher").await;
30163+ let taught = taught_under(&app, &staff, &homeroom, "matematik").await;
30164+
30165+ let ali = login(&app, "ali").await;
30166+ let ali_id = me_id(&app, &ali).await;
30167+ add_member(&app, &staff, &taught.class, &ali_id).await;
30168+
30169+ // A teacher the student shares no instance with — the refusal arm.
30170+ let stranger = login_as(&app, &db, "bora", "teacher").await;
30171+ let veli = login(&app, "veli").await;
30172+ let veli_id = me_id(&app, &veli).await;
30173+ add_member(&app, &staff, &taught.class, &veli_id).await;
30174+
30175+ let teacher_uuid = me_id(&app, &homeroom).await;
30176+ seed_insight_rows(&db, &taught.course, &ali_id, &teacher_uuid).await;
30177+
30178+ // The homeroom teacher runs the instance the student sits in: the whole
30179+ // card, with the filters applied.
30180+ let res = send(
30181+ &app,
30182+ "GET",
30183+ &format!("/insights/students/{ali_id}"),
30184+ Some(&homeroom),
30185+ None,
30186+ )
30187+ .await;
30188+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
30189+ assert_eq!(res.body["user_id"], ali_id);
30190+ assert_eq!(res.body["summary"]["confidence"], "stable");
30191+ assert_eq!(
30192+ res.body["summary"]["marks"]["courses"]["matematik"]["average"],
30193+ 72
30194+ );
30195+ assert_eq!(
30196+ res.body["attention"].as_array().expect("attention").len(),
30197+ 1
30198+ );
30199+ assert_eq!(res.body["attention"][0]["trigger"], "attendance");
30200+ let cards = res.body["cards"].as_array().expect("cards");
30201+ assert_eq!(
30202+ cards.len(),
30203+ 1,
30204+ "dismissed and expired cards are filtered out"
30205+ );
30206+ assert_eq!(cards[0]["rule_id"], "T4.attendance");
30207+ assert_eq!(cards[0]["about"], ali_id);
30208+ assert_eq!(cards[0]["course"], taught.course);
30209+ assert_eq!(cards[0]["evidence"]["limitation"], "yalniz ders yoklamasi");
30210+ let segments = res.body["segments"].as_array().expect("segments");
30211+ assert_eq!(segments.len(), 1, "a confidence:none row is not shown");
30212+ assert_eq!(segments[0]["label"], "analiz");
30213+ assert_eq!(segments[0]["contrast"], -0.15);
30214+
30215+ // The same student's own view: the summary and the profile, and the two
30216+ // things the contract keeps off a student's screen — the attention list
30217+ // about themselves, and any card not addressed to them (their live card
30218+ // belongs to the teacher, and their own two are dismissed/expired).
30219+ let res = send(&app, "GET", "/insights/me", Some(&ali), None).await;
30220+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
30221+ assert_eq!(res.body["summary"]["confidence"], "stable");
30222+ assert_eq!(
30223+ res.body["attention"].as_array().expect("attention").len(),
30224+ 0
30225+ );
30226+ assert_eq!(res.body["cards"].as_array().expect("cards").len(), 0);
30227+ assert_eq!(res.body["segments"].as_array().expect("segments").len(), 1);
30228+
30229+ // A teacher who does not run any instance the student sits in reads the
30230+ // same 404 a missing id reads — and the row above proves it is a refusal,
30231+ // not an absence.
30232+ let res = send(
30233+ &app,
30234+ "GET",
30235+ &format!("/insights/students/{ali_id}"),
30236+ Some(&stranger),
30237+ None,
30238+ )
30239+ .await;
30240+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
30241+
30242+ // A fellow student is refused at the role gate, the same posture
30243+ // `/marks/{user}` takes.
30244+ let res = send(
30245+ &app,
30246+ "GET",
30247+ &format!("/insights/students/{ali_id}"),
30248+ Some(&veli),
30249+ None,
30250+ )
30251+ .await;
30252+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
30253+
30254+ // The reach check has no existence oracle either: an id no user holds
30255+ // reads exactly like the unreachable one.
30256+ let res = send(
30257+ &app,
30258+ "GET",
30259+ &format!("/insights/students/{}", Uuid::now_v7()),
30260+ Some(&stranger),
30261+ None,
30262+ )
30263+ .await;
30264+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
30265+}
30266+
30267+/// The run ledger is the management view: manager+ reads it whole — with the
30268+/// two child tables joined back in their writer's order — and a teacher is
30269+/// refused outright (a pending-student list is a list of people).
30270+#[tokio::test]
30271+async fn the_insight_run_ledger_is_manager_only() {
30272+ let (app, db) = app_and_db().await;
30273+ let staff = login_as(&app, &db, "mudur", "manager").await;
30274+ let teacher = login_as(&app, &db, "ayse", "teacher").await;
30275+ let ali = login(&app, "ali").await;
30276+ let ali_id = me_id(&app, &ali).await;
30277+
30278+ let now = Timestamp::now().as_millis();
30279+ sqlx::query(
30280+ "INSERT INTO zeka_run
30281+ (run_day, started_at, finished_at, status, duration_ms,
30282+ students_total, students_ok, students_failed, students_skipped,
30283+ rows_written, budget_exceeded, budget_ms, retain_until)
30284+ VALUES ('2026-09-16', $1, $2, 'partial', 61000, 12, 10, 1, 1, 44, true, 60000, $3)",
30285+ )
30286+ .bind(now - 61_000)
30287+ .bind(now)
30288+ .bind(now + 90 * 86_400_000)
30289+ .execute(&db)
30290+ .await
30291+ .unwrap();
30292+ sqlx::query("INSERT INTO zeka_run_pending (run, student, ord) VALUES ('2026-09-16', $1, 1)")
30293+ .bind(Uuid::parse_str(&ali_id).expect("student id"))
30294+ .execute(&db)
30295+ .await
30296+ .unwrap();
30297+ sqlx::query(
30298+ "INSERT INTO zeka_run_failed_module (run, module, ord)
30299+ VALUES ('2026-09-16', 'study', 1), ('2026-09-16', 'attendance', 2)",
30300+ )
30301+ .execute(&db)
30302+ .await
30303+ .unwrap();
30304+
30305+ let res = send(&app, "GET", "/insights/runs", Some(&staff), None).await;
30306+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
30307+ assert_eq!(res.body["total"], 1);
30308+ let run = &res.body["items"][0];
30309+ assert_eq!(run["run_day"], "2026-09-16");
30310+ assert_eq!(run["status"], "partial");
30311+ assert_eq!(run["budget_exceeded"], true);
30312+ assert_eq!(run["pending_students"], json!([ali_id]));
30313+ assert_eq!(run["failed_modules"], json!(["study", "attendance"]));
30314+
30315+ let res = send(&app, "GET", "/insights/runs", Some(&teacher), None).await;
30316+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
30317+}
tests/limits_completeness.rsmodified+23 -0
@@ -122,6 +122,29 @@ const EXCLUDED: &[(&str, &str)] = &[
122122 "deadline on one RAG ask round trip; the browser waits on its message \
123123 stream, never on this number",
124124 ),
125+ (
126+ "AI_INSIGHT_STUDENT_CAPABILITY",
127+ "capability string an AI service declares",
128+ ),
129+ (
130+ "AI_INSIGHT_STUDENT_TIMEOUT_SECS",
131+ "deadline on one student's compute; the dispatch is off the request \
132+ path and a reader polls the stored rows",
133+ ),
134+ (
135+ "AI_INSIGHT_CLASS_CAPABILITY",
136+ "capability string an AI service declares (declared for the contract; \
137+ no door dispatches it yet)",
138+ ),
139+ (
140+ "AI_INSIGHT_REFRESH_CAPABILITY",
141+ "capability string an AI service declares",
142+ ),
143+ (
144+ "AI_INSIGHT_REFRESH_TIMEOUT_SECS",
145+ "deadline on one school-wide recompute; the run's own ledger is \
146+ `zeka_run`, which the client polls",
147+ ),
125148 (
126149 "CHAT_STREAM_POLL_MS",
127150 "server-side poll cadence behind the SSE stream",