forge
Explore
Log in

Don't you dare go Hollow

ZEKA no longer touches the database directly - the insight.* storage surface

Browse files at this commit

7c96e47e91c6a53a4949074bdf5f53dd1a1e4570Ahmet Kaan GümüşParent: 4a2411d
  • feat
    • ZEKA no longer touches the database directly - the insight.* storage surface
Show full message
✨ feat: ZEKA no longer touches the database directly - the insight.* storage surface

No AI service may hold a school database credential, so the nine reads and
writes ZEKA performed against its own zeka_* tables become named operations
the backend serves: insight.summary|recommendation|segment|profile|run.upsert,
insight.pending.list, insight.retention.sweep, insight.departed.purge and the
deployment-scoped insight.schools.list.

They ride a new client-initiated capability call (CapabilityRequest ->
CapabilityResponse, mirroring Request/Response field for field) and are
mounted as HTTP doors on the same functions (manager+; the school directory is
the builder's, outside the school gate). Every statement runs inside the
school the frame named, in one transaction per batch.
.sqlx/query-00e4b6eca87d0ab5012f3d0562bf749302b7824859737c780efb433e972af5e4.jsonadded+210 -0
@@ -0,0 +1,210 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE podcast_job SET state = 'failed', error_code = $2, stage = '', updated_at = $3 WHERE id = $1 AND state IN ('queued', 'running') RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: PodcastJobId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "podcast_job",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user_id: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "podcast_job",
24+ "name": "user_id"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "source_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "podcast_job",
35+ "name": "source_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "format",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "podcast_job",
46+ "name": "format"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "state: PodcastJobState",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "podcast_job",
57+ "name": "state"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "stage",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "podcast_job",
68+ "name": "stage"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "progress",
75+ "type_info": "Float8",
76+ "origin": {
77+ "Table": {
78+ "table": "podcast_job",
79+ "name": "progress"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "podcast_job",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "audio_key",
97+ "type_info": "Text",
98+ "origin": {
99+ "Table": {
100+ "table": "podcast_job",
101+ "name": "audio_key"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "audio_name",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "podcast_job",
112+ "name": "audio_name"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "audio_type",
119+ "type_info": "Text",
120+ "origin": {
121+ "Table": {
122+ "table": "podcast_job",
123+ "name": "audio_type"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "audio_bytes",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "podcast_job",
134+ "name": "audio_bytes"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "duration_secs",
141+ "type_info": "Float8",
142+ "origin": {
143+ "Table": {
144+ "table": "podcast_job",
145+ "name": "duration_secs"
146+ }
147+ }
148+ },
149+ {
150+ "ordinal": 13,
151+ "name": "eta_secs",
152+ "type_info": "Int8",
153+ "origin": {
154+ "Table": {
155+ "table": "podcast_job",
156+ "name": "eta_secs"
157+ }
158+ }
159+ },
160+ {
161+ "ordinal": 14,
162+ "name": "created_at: Timestamp",
163+ "type_info": "Int8",
164+ "origin": {
165+ "Table": {
166+ "table": "podcast_job",
167+ "name": "created_at"
168+ }
169+ }
170+ },
171+ {
172+ "ordinal": 15,
173+ "name": "updated_at: Timestamp",
174+ "type_info": "Int8",
175+ "origin": {
176+ "Table": {
177+ "table": "podcast_job",
178+ "name": "updated_at"
179+ }
180+ }
181+ }
182+ ],
183+ "parameters": {
184+ "Left": [
185+ "Uuid",
186+ "Text",
187+ "Int8"
188+ ]
189+ },
190+ "nullable": [
191+ false,
192+ false,
193+ false,
194+ true,
195+ false,
196+ false,
197+ false,
198+ true,
199+ true,
200+ true,
201+ true,
202+ true,
203+ true,
204+ true,
205+ false,
206+ false
207+ ]
208+ },
209+ "hash": "00e4b6eca87d0ab5012f3d0562bf749302b7824859737c780efb433e972af5e4"
210+}
.sqlx/query-1419d2d6a1288438261cfccd2ceff0448a94963efd2d4b669f4b5b63ce009c84.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM zeka_run_pending WHERE run = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Text"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "1419d2d6a1288438261cfccd2ceff0448a94963efd2d4b669f4b5b63ce009c84"
14+}
.sqlx/query-16da7d91af8ef555b98bdf14cc418cdd618f48caa4f3c49dc5ecbdffcfafccc6.jsonadded+16 -0
@@ -0,0 +1,16 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO zeka_run_failed_module (run, module, ord) VALUES ($1, $2, $3)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Text",
9+ "Text",
10+ "Int2"
11+ ]
12+ },
13+ "nullable": []
14+ },
15+ "hash": "16da7d91af8ef555b98bdf14cc418cdd618f48caa4f3c49dc5ecbdffcfafccc6"
16+}
.sqlx/query-3773b2b5864210017fbfa74b89d2227d102dfdcc8c42e3958427d8bc1bf91225.jsonadded+27 -0
@@ -0,0 +1,27 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO zeka_recommendation\n (id, audience, product, rule_id, rule_version, scope, about, audience_role,\n course, evidence, confidence, created_at, expires_at, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)\n ON CONFLICT (audience, product, rule_id, about, scope) DO UPDATE SET\n rule_version = EXCLUDED.rule_version,\n audience_role = EXCLUDED.audience_role,\n course = EXCLUDED.course,\n evidence = EXCLUDED.evidence,\n confidence = EXCLUDED.confidence,\n created_at = EXCLUDED.created_at,\n expires_at = EXCLUDED.expires_at,\n retain_until = EXCLUDED.retain_until",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid",
10+ "Text",
11+ "Text",
12+ "Int8",
13+ "Text",
14+ "Uuid",
15+ "Text",
16+ "Uuid",
17+ "Jsonb",
18+ "Text",
19+ "Int8",
20+ "Int8",
21+ "Int8"
22+ ]
23+ },
24+ "nullable": []
25+ },
26+ "hash": "3773b2b5864210017fbfa74b89d2227d102dfdcc8c42e3958427d8bc1bf91225"
27+}
.sqlx/query-5b00aa8c5c7814c7a5c82f5b0be3ff6ce87354aaa1a808eeeb6b2e72f56a3d48.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM zeka_question_segment_dimension WHERE question = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "5b00aa8c5c7814c7a5c82f5b0be3ff6ce87354aaa1a808eeeb6b2e72f56a3d48"
14+}
.sqlx/query-5c4295befb79370b86726cfc5ce5d4474062400acdf4d6b10f4ec9fb2408808a.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM zeka_run_failed_module WHERE run = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Text"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "5c4295befb79370b86726cfc5ce5d4474062400acdf4d6b10f4ec9fb2408808a"
14+}
.sqlx/query-636b29289a1fc139ca239ddae85bdd59d39b5f90fb69e27cf6acb616cd3c8101.jsonadded+222 -0
@@ -0,0 +1,222 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO podcast_job (id, user_id, source_id, format, state, stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $15) RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: PodcastJobId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "podcast_job",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user_id: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "podcast_job",
24+ "name": "user_id"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "source_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "podcast_job",
35+ "name": "source_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "format",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "podcast_job",
46+ "name": "format"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "state: PodcastJobState",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "podcast_job",
57+ "name": "state"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "stage",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "podcast_job",
68+ "name": "stage"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "progress",
75+ "type_info": "Float8",
76+ "origin": {
77+ "Table": {
78+ "table": "podcast_job",
79+ "name": "progress"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "podcast_job",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "audio_key",
97+ "type_info": "Text",
98+ "origin": {
99+ "Table": {
100+ "table": "podcast_job",
101+ "name": "audio_key"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "audio_name",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "podcast_job",
112+ "name": "audio_name"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "audio_type",
119+ "type_info": "Text",
120+ "origin": {
121+ "Table": {
122+ "table": "podcast_job",
123+ "name": "audio_type"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "audio_bytes",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "podcast_job",
134+ "name": "audio_bytes"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "duration_secs",
141+ "type_info": "Float8",
142+ "origin": {
143+ "Table": {
144+ "table": "podcast_job",
145+ "name": "duration_secs"
146+ }
147+ }
148+ },
149+ {
150+ "ordinal": 13,
151+ "name": "eta_secs",
152+ "type_info": "Int8",
153+ "origin": {
154+ "Table": {
155+ "table": "podcast_job",
156+ "name": "eta_secs"
157+ }
158+ }
159+ },
160+ {
161+ "ordinal": 14,
162+ "name": "created_at: Timestamp",
163+ "type_info": "Int8",
164+ "origin": {
165+ "Table": {
166+ "table": "podcast_job",
167+ "name": "created_at"
168+ }
169+ }
170+ },
171+ {
172+ "ordinal": 15,
173+ "name": "updated_at: Timestamp",
174+ "type_info": "Int8",
175+ "origin": {
176+ "Table": {
177+ "table": "podcast_job",
178+ "name": "updated_at"
179+ }
180+ }
181+ }
182+ ],
183+ "parameters": {
184+ "Left": [
185+ "Uuid",
186+ "Uuid",
187+ "Text",
188+ "Text",
189+ "Text",
190+ "Text",
191+ "Float8",
192+ "Text",
193+ "Text",
194+ "Text",
195+ "Text",
196+ "Int8",
197+ "Float8",
198+ "Int8",
199+ "Int8"
200+ ]
201+ },
202+ "nullable": [
203+ false,
204+ false,
205+ false,
206+ true,
207+ false,
208+ false,
209+ false,
210+ true,
211+ true,
212+ true,
213+ true,
214+ true,
215+ true,
216+ true,
217+ false,
218+ false
219+ ]
220+ },
221+ "hash": "636b29289a1fc139ca239ddae85bdd59d39b5f90fb69e27cf6acb616cd3c8101"
222+}
.sqlx/query-63ab56b7c9cec73b82d7143c9595dc575c23ef9aaf415321bfedae115dfbc8ac.jsonadded+21 -0
@@ -0,0 +1,21 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO zeka_student_summary\n (student, marks, attendance, submission, study, confidence,\n computed_at, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (student) DO UPDATE SET\n marks = EXCLUDED.marks, attendance = EXCLUDED.attendance,\n submission = EXCLUDED.submission, study = EXCLUDED.study,\n confidence = EXCLUDED.confidence, computed_at = EXCLUDED.computed_at,\n retain_until = EXCLUDED.retain_until",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Jsonb",
10+ "Jsonb",
11+ "Jsonb",
12+ "Jsonb",
13+ "Text",
14+ "Int8",
15+ "Int8"
16+ ]
17+ },
18+ "nullable": []
19+ },
20+ "hash": "63ab56b7c9cec73b82d7143c9595dc575c23ef9aaf415321bfedae115dfbc8ac"
21+}
.sqlx/query-64a0ae377768cc932bb3751b6d8857924536cb9eae45bb42ac5ddf8b37ef5702.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM zeka_recommendation\n WHERE about IS NOT NULL AND about <> ALL($1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "UuidArray"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "64a0ae377768cc932bb3751b6d8857924536cb9eae45bb42ac5ddf8b37ef5702"
14+}
.sqlx/query-670b56558479909cc3f10badcfa87498d97beaa1c834ecfe46948b92d4c64a17.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM zeka_student_summary WHERE student <> ALL($1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "UuidArray"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "670b56558479909cc3f10badcfa87498d97beaa1c834ecfe46948b92d4c64a17"
14+}
.sqlx/query-744065e06ac54db230fdfe81656769f2f96ef594e3b147de6a86dd3c4fdd25e4.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM zeka_student_segment_profile WHERE student <> ALL($1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "UuidArray"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "744065e06ac54db230fdfe81656769f2f96ef594e3b147de6a86dd3c4fdd25e4"
14+}
.sqlx/query-7a93565369caf1d8f68b8214735971e4e862032a071474516a149286eb61e9c8.jsonadded+33 -0
@@ -0,0 +1,33 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO zeka_question_segment\n (question, exam, course, subject, bilissel_talep, dikkat_tuzagi, okuma_yuku,\n adim_sayisi, confidence_bilissel_talep, confidence_dikkat_tuzagi,\n confidence_okuma_yuku, confidence_adim_sayisi, confidence, trap_choice,\n rationale, model, prompt_version, variant, computed_at, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10,\n $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)\n ON CONFLICT (question) DO UPDATE SET\n exam = EXCLUDED.exam, course = EXCLUDED.course, subject = EXCLUDED.subject,\n bilissel_talep = EXCLUDED.bilissel_talep,\n dikkat_tuzagi = EXCLUDED.dikkat_tuzagi,\n okuma_yuku = EXCLUDED.okuma_yuku,\n adim_sayisi = EXCLUDED.adim_sayisi,\n confidence_bilissel_talep = EXCLUDED.confidence_bilissel_talep,\n confidence_dikkat_tuzagi = EXCLUDED.confidence_dikkat_tuzagi,\n confidence_okuma_yuku = EXCLUDED.confidence_okuma_yuku,\n confidence_adim_sayisi = EXCLUDED.confidence_adim_sayisi,\n confidence = EXCLUDED.confidence, trap_choice = EXCLUDED.trap_choice,\n rationale = EXCLUDED.rationale, model = EXCLUDED.model,\n prompt_version = EXCLUDED.prompt_version, variant = EXCLUDED.variant,\n computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid",
10+ "Uuid",
11+ "Uuid",
12+ "Text",
13+ "Text",
14+ "Text",
15+ "Text",
16+ "Float8",
17+ "Float8",
18+ "Float8",
19+ "Float8",
20+ "Text",
21+ "Text",
22+ "Text",
23+ "Text",
24+ "Text",
25+ "Text",
26+ "Int8",
27+ "Int8"
28+ ]
29+ },
30+ "nullable": []
31+ },
32+ "hash": "7a93565369caf1d8f68b8214735971e4e862032a071474516a149286eb61e9c8"
33+}
.sqlx/query-826c34848d470eb17f7a677d1ce1d6d80b9a0cad9fbba7a655104c7d1a16ea18.jsonadded+208 -0
@@ -0,0 +1,208 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM podcast_job WHERE id = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: PodcastJobId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "podcast_job",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user_id: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "podcast_job",
24+ "name": "user_id"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "source_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "podcast_job",
35+ "name": "source_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "format",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "podcast_job",
46+ "name": "format"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "state: PodcastJobState",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "podcast_job",
57+ "name": "state"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "stage",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "podcast_job",
68+ "name": "stage"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "progress",
75+ "type_info": "Float8",
76+ "origin": {
77+ "Table": {
78+ "table": "podcast_job",
79+ "name": "progress"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "podcast_job",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "audio_key",
97+ "type_info": "Text",
98+ "origin": {
99+ "Table": {
100+ "table": "podcast_job",
101+ "name": "audio_key"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "audio_name",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "podcast_job",
112+ "name": "audio_name"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "audio_type",
119+ "type_info": "Text",
120+ "origin": {
121+ "Table": {
122+ "table": "podcast_job",
123+ "name": "audio_type"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "audio_bytes",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "podcast_job",
134+ "name": "audio_bytes"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "duration_secs",
141+ "type_info": "Float8",
142+ "origin": {
143+ "Table": {
144+ "table": "podcast_job",
145+ "name": "duration_secs"
146+ }
147+ }
148+ },
149+ {
150+ "ordinal": 13,
151+ "name": "eta_secs",
152+ "type_info": "Int8",
153+ "origin": {
154+ "Table": {
155+ "table": "podcast_job",
156+ "name": "eta_secs"
157+ }
158+ }
159+ },
160+ {
161+ "ordinal": 14,
162+ "name": "created_at: Timestamp",
163+ "type_info": "Int8",
164+ "origin": {
165+ "Table": {
166+ "table": "podcast_job",
167+ "name": "created_at"
168+ }
169+ }
170+ },
171+ {
172+ "ordinal": 15,
173+ "name": "updated_at: Timestamp",
174+ "type_info": "Int8",
175+ "origin": {
176+ "Table": {
177+ "table": "podcast_job",
178+ "name": "updated_at"
179+ }
180+ }
181+ }
182+ ],
183+ "parameters": {
184+ "Left": [
185+ "Uuid"
186+ ]
187+ },
188+ "nullable": [
189+ false,
190+ false,
191+ false,
192+ true,
193+ false,
194+ false,
195+ false,
196+ true,
197+ true,
198+ true,
199+ true,
200+ true,
201+ true,
202+ true,
203+ false,
204+ false
205+ ]
206+ },
207+ "hash": "826c34848d470eb17f7a677d1ce1d6d80b9a0cad9fbba7a655104c7d1a16ea18"
208+}
.sqlx/query-8378e48dd68785c1caccc7e7be489d93fbb51942736383921d200584eb202d32.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT p.student FROM zeka_run_pending p\n JOIN zeka_run r ON r.run_day = p.run\n WHERE r.run_day = (SELECT run_day FROM zeka_run\n ORDER BY started_at DESC, run_day DESC LIMIT 1)\n ORDER BY p.ord\n LIMIT $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "student",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_run_pending",
13+ "name": "student"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Int8"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "8378e48dd68785c1caccc7e7be489d93fbb51942736383921d200584eb202d32"
28+}
.sqlx/query-913496d365010822c99818a92fc901a1939d16cb7aff9023c8b7331ece7265c0.jsonadded+209 -0
@@ -0,0 +1,209 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE podcast_job SET eta_secs = $2 WHERE id = $1 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: PodcastJobId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "podcast_job",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user_id: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "podcast_job",
24+ "name": "user_id"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "source_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "podcast_job",
35+ "name": "source_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "format",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "podcast_job",
46+ "name": "format"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "state: PodcastJobState",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "podcast_job",
57+ "name": "state"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "stage",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "podcast_job",
68+ "name": "stage"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "progress",
75+ "type_info": "Float8",
76+ "origin": {
77+ "Table": {
78+ "table": "podcast_job",
79+ "name": "progress"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "podcast_job",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "audio_key",
97+ "type_info": "Text",
98+ "origin": {
99+ "Table": {
100+ "table": "podcast_job",
101+ "name": "audio_key"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "audio_name",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "podcast_job",
112+ "name": "audio_name"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "audio_type",
119+ "type_info": "Text",
120+ "origin": {
121+ "Table": {
122+ "table": "podcast_job",
123+ "name": "audio_type"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "audio_bytes",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "podcast_job",
134+ "name": "audio_bytes"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "duration_secs",
141+ "type_info": "Float8",
142+ "origin": {
143+ "Table": {
144+ "table": "podcast_job",
145+ "name": "duration_secs"
146+ }
147+ }
148+ },
149+ {
150+ "ordinal": 13,
151+ "name": "eta_secs",
152+ "type_info": "Int8",
153+ "origin": {
154+ "Table": {
155+ "table": "podcast_job",
156+ "name": "eta_secs"
157+ }
158+ }
159+ },
160+ {
161+ "ordinal": 14,
162+ "name": "created_at: Timestamp",
163+ "type_info": "Int8",
164+ "origin": {
165+ "Table": {
166+ "table": "podcast_job",
167+ "name": "created_at"
168+ }
169+ }
170+ },
171+ {
172+ "ordinal": 15,
173+ "name": "updated_at: Timestamp",
174+ "type_info": "Int8",
175+ "origin": {
176+ "Table": {
177+ "table": "podcast_job",
178+ "name": "updated_at"
179+ }
180+ }
181+ }
182+ ],
183+ "parameters": {
184+ "Left": [
185+ "Uuid",
186+ "Int8"
187+ ]
188+ },
189+ "nullable": [
190+ false,
191+ false,
192+ false,
193+ true,
194+ false,
195+ false,
196+ false,
197+ true,
198+ true,
199+ true,
200+ true,
201+ true,
202+ true,
203+ true,
204+ false,
205+ false
206+ ]
207+ },
208+ "hash": "913496d365010822c99818a92fc901a1939d16cb7aff9023c8b7331ece7265c0"
209+}
.sqlx/query-91c968305e53e61df2c67fdaeea78150a1e8c7f19991e21b45272785cd2e4055.jsonadded+209 -0
@@ -0,0 +1,209 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM podcast_job WHERE id = $1 AND user_id = $2",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: PodcastJobId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "podcast_job",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user_id: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "podcast_job",
24+ "name": "user_id"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "source_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "podcast_job",
35+ "name": "source_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "format",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "podcast_job",
46+ "name": "format"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "state: PodcastJobState",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "podcast_job",
57+ "name": "state"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "stage",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "podcast_job",
68+ "name": "stage"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "progress",
75+ "type_info": "Float8",
76+ "origin": {
77+ "Table": {
78+ "table": "podcast_job",
79+ "name": "progress"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "podcast_job",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "audio_key",
97+ "type_info": "Text",
98+ "origin": {
99+ "Table": {
100+ "table": "podcast_job",
101+ "name": "audio_key"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "audio_name",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "podcast_job",
112+ "name": "audio_name"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "audio_type",
119+ "type_info": "Text",
120+ "origin": {
121+ "Table": {
122+ "table": "podcast_job",
123+ "name": "audio_type"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "audio_bytes",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "podcast_job",
134+ "name": "audio_bytes"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "duration_secs",
141+ "type_info": "Float8",
142+ "origin": {
143+ "Table": {
144+ "table": "podcast_job",
145+ "name": "duration_secs"
146+ }
147+ }
148+ },
149+ {
150+ "ordinal": 13,
151+ "name": "eta_secs",
152+ "type_info": "Int8",
153+ "origin": {
154+ "Table": {
155+ "table": "podcast_job",
156+ "name": "eta_secs"
157+ }
158+ }
159+ },
160+ {
161+ "ordinal": 14,
162+ "name": "created_at: Timestamp",
163+ "type_info": "Int8",
164+ "origin": {
165+ "Table": {
166+ "table": "podcast_job",
167+ "name": "created_at"
168+ }
169+ }
170+ },
171+ {
172+ "ordinal": 15,
173+ "name": "updated_at: Timestamp",
174+ "type_info": "Int8",
175+ "origin": {
176+ "Table": {
177+ "table": "podcast_job",
178+ "name": "updated_at"
179+ }
180+ }
181+ }
182+ ],
183+ "parameters": {
184+ "Left": [
185+ "Uuid",
186+ "Uuid"
187+ ]
188+ },
189+ "nullable": [
190+ false,
191+ false,
192+ false,
193+ true,
194+ false,
195+ false,
196+ false,
197+ true,
198+ true,
199+ true,
200+ true,
201+ true,
202+ true,
203+ true,
204+ false,
205+ false
206+ ]
207+ },
208+ "hash": "91c968305e53e61df2c67fdaeea78150a1e8c7f19991e21b45272785cd2e4055"
209+}
.sqlx/query-9c0a2825d86358bb6088de901bff1c0437b5db4609942d07a95a1262a723bb99.jsonadded+21 -0
@@ -0,0 +1,21 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO zeka_attention_item\n (student, trigger, course, fact, window_from, window_to, evidence, ord)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Text",
10+ "Uuid",
11+ "Text",
12+ "Int8",
13+ "Int8",
14+ "Jsonb",
15+ "Int2"
16+ ]
17+ },
18+ "nullable": []
19+ },
20+ "hash": "9c0a2825d86358bb6088de901bff1c0437b5db4609942d07a95a1262a723bb99"
21+}
.sqlx/query-a090ce70a604c900d6a516bf14844918826d27c938b536063b8c526f1133d620.jsonadded+26 -0
@@ -0,0 +1,26 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO zeka_run\n (run_day, started_at, finished_at, status, duration_ms, students_total,\n students_ok, students_failed, students_skipped, rows_written,\n budget_exceeded, budget_ms, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)\n ON CONFLICT (run_day) DO UPDATE SET\n started_at = EXCLUDED.started_at, finished_at = EXCLUDED.finished_at,\n status = EXCLUDED.status, duration_ms = EXCLUDED.duration_ms,\n students_total = EXCLUDED.students_total, students_ok = EXCLUDED.students_ok,\n students_failed = EXCLUDED.students_failed,\n students_skipped = EXCLUDED.students_skipped,\n rows_written = EXCLUDED.rows_written,\n budget_exceeded = EXCLUDED.budget_exceeded, budget_ms = EXCLUDED.budget_ms,\n retain_until = EXCLUDED.retain_until",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Text",
9+ "Int8",
10+ "Int8",
11+ "Text",
12+ "Int8",
13+ "Int8",
14+ "Int8",
15+ "Int8",
16+ "Int8",
17+ "Int8",
18+ "Bool",
19+ "Int8",
20+ "Int8"
21+ ]
22+ },
23+ "nullable": []
24+ },
25+ "hash": "a090ce70a604c900d6a516bf14844918826d27c938b536063b8c526f1133d620"
26+}
.sqlx/query-ad5b90d0407d3abf9a3bdf119146041a67a486a5560fa151ad8fe8210bfd9d53.jsonadded+209 -0
@@ -0,0 +1,209 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE podcast_job SET state = 'cancelled', stage = '', updated_at = $2 WHERE id = $1 AND state IN ('queued', 'running') RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: PodcastJobId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "podcast_job",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user_id: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "podcast_job",
24+ "name": "user_id"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "source_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "podcast_job",
35+ "name": "source_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "format",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "podcast_job",
46+ "name": "format"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "state: PodcastJobState",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "podcast_job",
57+ "name": "state"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "stage",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "podcast_job",
68+ "name": "stage"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "progress",
75+ "type_info": "Float8",
76+ "origin": {
77+ "Table": {
78+ "table": "podcast_job",
79+ "name": "progress"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "podcast_job",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "audio_key",
97+ "type_info": "Text",
98+ "origin": {
99+ "Table": {
100+ "table": "podcast_job",
101+ "name": "audio_key"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "audio_name",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "podcast_job",
112+ "name": "audio_name"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "audio_type",
119+ "type_info": "Text",
120+ "origin": {
121+ "Table": {
122+ "table": "podcast_job",
123+ "name": "audio_type"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "audio_bytes",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "podcast_job",
134+ "name": "audio_bytes"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "duration_secs",
141+ "type_info": "Float8",
142+ "origin": {
143+ "Table": {
144+ "table": "podcast_job",
145+ "name": "duration_secs"
146+ }
147+ }
148+ },
149+ {
150+ "ordinal": 13,
151+ "name": "eta_secs",
152+ "type_info": "Int8",
153+ "origin": {
154+ "Table": {
155+ "table": "podcast_job",
156+ "name": "eta_secs"
157+ }
158+ }
159+ },
160+ {
161+ "ordinal": 14,
162+ "name": "created_at: Timestamp",
163+ "type_info": "Int8",
164+ "origin": {
165+ "Table": {
166+ "table": "podcast_job",
167+ "name": "created_at"
168+ }
169+ }
170+ },
171+ {
172+ "ordinal": 15,
173+ "name": "updated_at: Timestamp",
174+ "type_info": "Int8",
175+ "origin": {
176+ "Table": {
177+ "table": "podcast_job",
178+ "name": "updated_at"
179+ }
180+ }
181+ }
182+ ],
183+ "parameters": {
184+ "Left": [
185+ "Uuid",
186+ "Int8"
187+ ]
188+ },
189+ "nullable": [
190+ false,
191+ false,
192+ false,
193+ true,
194+ false,
195+ false,
196+ false,
197+ true,
198+ true,
199+ true,
200+ true,
201+ true,
202+ true,
203+ true,
204+ false,
205+ false
206+ ]
207+ },
208+ "hash": "ad5b90d0407d3abf9a3bdf119146041a67a486a5560fa151ad8fe8210bfd9d53"
209+}
.sqlx/query-b0f040f8c3044894f49702f9918b672f5b07587db6047f00cfda9c2effe7af56.jsonadded+17 -0
@@ -0,0 +1,17 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO zeka_question_segment_dimension\n (question, dimension, role, ord)\n VALUES ($1, $2, $3, $4)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Text",
10+ "Text",
11+ "Int2"
12+ ]
13+ },
14+ "nullable": []
15+ },
16+ "hash": "b0f040f8c3044894f49702f9918b672f5b07587db6047f00cfda9c2effe7af56"
17+}
.sqlx/query-c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b.jsonadded+26 -0
@@ -0,0 +1,26 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT slug FROM school WHERE status = 'active' ORDER BY slug",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "slug",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "school",
13+ "name": "slug"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": []
20+ },
21+ "nullable": [
22+ false
23+ ]
24+ },
25+ "hash": "c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b"
26+}
.sqlx/query-d47b73487d9975d8c5fb3fc6236eb9e549150c86a1c752343b841147f359de28.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM zeka_attention_item WHERE student = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "d47b73487d9975d8c5fb3fc6236eb9e549150c86a1c752343b841147f359de28"
14+}
.sqlx/query-da1423194dea4b1b011f5d3634b12da661992cdc26d5ec3e2c30f6a6dcda2487.jsonadded+25 -0
@@ -0,0 +1,25 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO zeka_student_segment_profile\n (student, dimension, label, n_answers, n_correct, accuracy,\n overall_n_answers, overall_accuracy, contrast, confidence,\n computed_at, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)\n ON CONFLICT (student, dimension, label) DO UPDATE SET\n n_answers = EXCLUDED.n_answers, n_correct = EXCLUDED.n_correct,\n accuracy = EXCLUDED.accuracy,\n overall_n_answers = EXCLUDED.overall_n_answers,\n overall_accuracy = EXCLUDED.overall_accuracy,\n contrast = EXCLUDED.contrast, confidence = EXCLUDED.confidence,\n computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Text",
10+ "Text",
11+ "Int8",
12+ "Int8",
13+ "Float8",
14+ "Int8",
15+ "Float8",
16+ "Float8",
17+ "Text",
18+ "Int8",
19+ "Int8"
20+ ]
21+ },
22+ "nullable": []
23+ },
24+ "hash": "da1423194dea4b1b011f5d3634b12da661992cdc26d5ec3e2c30f6a6dcda2487"
25+}
.sqlx/query-e3c904f558317d2d0c709f4b6bb3c2109bc86448a3dc6895c5bf2a9c0c99cc98.jsonadded+215 -0
@@ -0,0 +1,215 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE podcast_job SET state = $3, stage = $4, progress = $5, error_code = $6, format = COALESCE(format, $7::text), updated_at = $8 WHERE id = $1 AND state = $2 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: PodcastJobId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "podcast_job",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user_id: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "podcast_job",
24+ "name": "user_id"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "source_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "podcast_job",
35+ "name": "source_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "format",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "podcast_job",
46+ "name": "format"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "state: PodcastJobState",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "podcast_job",
57+ "name": "state"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "stage",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "podcast_job",
68+ "name": "stage"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "progress",
75+ "type_info": "Float8",
76+ "origin": {
77+ "Table": {
78+ "table": "podcast_job",
79+ "name": "progress"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "podcast_job",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "audio_key",
97+ "type_info": "Text",
98+ "origin": {
99+ "Table": {
100+ "table": "podcast_job",
101+ "name": "audio_key"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "audio_name",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "podcast_job",
112+ "name": "audio_name"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "audio_type",
119+ "type_info": "Text",
120+ "origin": {
121+ "Table": {
122+ "table": "podcast_job",
123+ "name": "audio_type"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "audio_bytes",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "podcast_job",
134+ "name": "audio_bytes"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "duration_secs",
141+ "type_info": "Float8",
142+ "origin": {
143+ "Table": {
144+ "table": "podcast_job",
145+ "name": "duration_secs"
146+ }
147+ }
148+ },
149+ {
150+ "ordinal": 13,
151+ "name": "eta_secs",
152+ "type_info": "Int8",
153+ "origin": {
154+ "Table": {
155+ "table": "podcast_job",
156+ "name": "eta_secs"
157+ }
158+ }
159+ },
160+ {
161+ "ordinal": 14,
162+ "name": "created_at: Timestamp",
163+ "type_info": "Int8",
164+ "origin": {
165+ "Table": {
166+ "table": "podcast_job",
167+ "name": "created_at"
168+ }
169+ }
170+ },
171+ {
172+ "ordinal": 15,
173+ "name": "updated_at: Timestamp",
174+ "type_info": "Int8",
175+ "origin": {
176+ "Table": {
177+ "table": "podcast_job",
178+ "name": "updated_at"
179+ }
180+ }
181+ }
182+ ],
183+ "parameters": {
184+ "Left": [
185+ "Uuid",
186+ "Text",
187+ "Text",
188+ "Text",
189+ "Float8",
190+ "Text",
191+ "Text",
192+ "Int8"
193+ ]
194+ },
195+ "nullable": [
196+ false,
197+ false,
198+ false,
199+ true,
200+ false,
201+ false,
202+ false,
203+ true,
204+ true,
205+ true,
206+ true,
207+ true,
208+ true,
209+ true,
210+ false,
211+ false
212+ ]
213+ },
214+ "hash": "e3c904f558317d2d0c709f4b6bb3c2109bc86448a3dc6895c5bf2a9c0c99cc98"
215+}
.sqlx/query-eef4d307eacc7efa9eff673b382448cebbfaa47e3e7e1d907a8c902d582b3fbc.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM zeka_run_pending WHERE student <> ALL($1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "UuidArray"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "eef4d307eacc7efa9eff673b382448cebbfaa47e3e7e1d907a8c902d582b3fbc"
14+}
.sqlx/query-f1a079e6c5978b7d9458172705e0c66f070d71e3435dc8f359d09675c5fcccdc.jsonadded+214 -0
@@ -0,0 +1,214 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE podcast_job SET audio_key = $2, audio_name = $3, audio_type = $4, audio_bytes = $5, duration_secs = $6, updated_at = $7 WHERE id = $1 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: PodcastJobId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "podcast_job",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user_id: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "podcast_job",
24+ "name": "user_id"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "source_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "podcast_job",
35+ "name": "source_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "format",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "podcast_job",
46+ "name": "format"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "state: PodcastJobState",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "podcast_job",
57+ "name": "state"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "stage",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "podcast_job",
68+ "name": "stage"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "progress",
75+ "type_info": "Float8",
76+ "origin": {
77+ "Table": {
78+ "table": "podcast_job",
79+ "name": "progress"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "podcast_job",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "audio_key",
97+ "type_info": "Text",
98+ "origin": {
99+ "Table": {
100+ "table": "podcast_job",
101+ "name": "audio_key"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "audio_name",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "podcast_job",
112+ "name": "audio_name"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "audio_type",
119+ "type_info": "Text",
120+ "origin": {
121+ "Table": {
122+ "table": "podcast_job",
123+ "name": "audio_type"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "audio_bytes",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "podcast_job",
134+ "name": "audio_bytes"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "duration_secs",
141+ "type_info": "Float8",
142+ "origin": {
143+ "Table": {
144+ "table": "podcast_job",
145+ "name": "duration_secs"
146+ }
147+ }
148+ },
149+ {
150+ "ordinal": 13,
151+ "name": "eta_secs",
152+ "type_info": "Int8",
153+ "origin": {
154+ "Table": {
155+ "table": "podcast_job",
156+ "name": "eta_secs"
157+ }
158+ }
159+ },
160+ {
161+ "ordinal": 14,
162+ "name": "created_at: Timestamp",
163+ "type_info": "Int8",
164+ "origin": {
165+ "Table": {
166+ "table": "podcast_job",
167+ "name": "created_at"
168+ }
169+ }
170+ },
171+ {
172+ "ordinal": 15,
173+ "name": "updated_at: Timestamp",
174+ "type_info": "Int8",
175+ "origin": {
176+ "Table": {
177+ "table": "podcast_job",
178+ "name": "updated_at"
179+ }
180+ }
181+ }
182+ ],
183+ "parameters": {
184+ "Left": [
185+ "Uuid",
186+ "Text",
187+ "Text",
188+ "Text",
189+ "Int8",
190+ "Float8",
191+ "Int8"
192+ ]
193+ },
194+ "nullable": [
195+ false,
196+ false,
197+ false,
198+ true,
199+ false,
200+ false,
201+ false,
202+ true,
203+ true,
204+ true,
205+ true,
206+ true,
207+ true,
208+ true,
209+ false,
210+ false
211+ ]
212+ },
213+ "hash": "f1a079e6c5978b7d9458172705e0c66f070d71e3435dc8f359d09675c5fcccdc"
214+}
.sqlx/query-f844815300b8be204b2cf5f2b1ef782b9fee47fde37708ee071f9002bd163888.jsonadded+16 -0
@@ -0,0 +1,16 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO zeka_run_pending (run, student, ord) VALUES ($1, $2, $3)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Text",
9+ "Uuid",
10+ "Int4"
11+ ]
12+ },
13+ "nullable": []
14+ },
15+ "hash": "f844815300b8be204b2cf5f2b1ef782b9fee47fde37708ee071f9002bd163888"
16+}
.sqlx/query-f93aab2536f71779fa9d1b973a9e5c4b7ca3c48dd8e9cebf91c745130de0ad4e.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM zeka_attention_item WHERE student <> ALL($1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "UuidArray"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "f93aab2536f71779fa9d1b973a9e5c4b7ca3c48dd8e9cebf91c745130de0ad4e"
14+}
README.mdmodified+14 -5
@@ -1325,10 +1325,19 @@ window filtering, before paging; negative values are a `400` naming the field.
1325 | 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`. |1325 | 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`. |
1326 | 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. |1326 | 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. |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+| GET | `/insights/pending` | manager | The students the freshest compute run left pending — where the next run starts. |
1329+| POST | `/insights/profiles` | manager | Store a batch of ZEKA's student segment profiles. |
1330+| POST | `/insights/purge` | manager | Delete the derived rows of every student who is no longer on the roster. |
1331+| POST | `/insights/recommendations` | manager | Store a batch of ZEKA's recommendation cards. |
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. |1332 | 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=`. |1333 | 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=`. |
1334+| POST | `/insights/runs` | manager | Store one compute run's ledger row (with its pending students and failed modules, both replaced). |
1335+| GET | `/insights/schools` | builder | The deployment's active schools, by slug — the directory a shared AI fleet schedules over. |
1336+| POST | `/insights/segments` | manager | Store a batch of ZEKA's question-segment labels (and each question's dimension split). |
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. |1337 | 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. |1338 | 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. |
1339+| POST | `/insights/summaries` | manager | Store a batch of ZEKA's student summaries (and their attention items). |
1340+| POST | `/insights/sweep` | manager | Delete every `zeka_*` row whose retention window has closed. |
1332 | 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. |1341 | 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. |
1333 | 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. |1342 | 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. |
1334 | 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. |1343 | 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. |
@@ -1400,11 +1409,11 @@ window filtering, before paging; negative values are a `400` naming the field.
1400 | POST | `/payments/reversals` | manager | Undo a line entered by mistake, for its exact amount — the line itself stays, with an opposing one appended beside it. Only a `charge` or a `refund` may be reversed (`400` otherwise): a mistaken payment is corrected with a refund, so money leaving the school is always spelled the one way. **Idempotent** — a line has at most one reversal, however often the call is retried. |1409 | POST | `/payments/reversals` | manager | Undo a line entered by mistake, for its exact amount — the line itself stays, with an opposing one appended beside it. Only a `charge` or a `refund` may be reversed (`400` otherwise): a mistaken payment is corrected with a refund, so money leaving the school is always spelled the one way. **Idempotent** — a line has at most one reversal, however often the call is retried. |
1401 | GET | `/payments/statement/me` | student | The caller's own statement. The per-charge rows are paged via `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the same on every page, because the fold behind it reads every line. |1410 | GET | `/payments/statement/me` | student | The caller's own statement. The per-charge rows are paged via `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the same on every page, because the fold behind it reads every line. |
1402 | GET | `/payments/statement/{user}` | manager | One student's statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is overdue. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). The rows are paged via `?limit=&offset=`; `balance_minor` is the same on every page. |1411 | GET | `/payments/statement/{user}` | manager | One student's statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is overdue. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). The rows are paged via `?limit=&offset=`; `balance_minor` is the same on every page. |
1403-| GET | `/podcast/audio` | student | Stream one produced audio file. `path` is the `audio_id` `podcast.result` answered, resolved under **this caller's school** output directory — the same directory the service's `PODCAST_OUTPUT_ROOT` points at — and streamed in 64 KiB chunks, so a long episode costs the backend a bounded buffer rather than its whole length in memory. |1412+| POST | `/podcast/jobs` | student | Start one podcast job. Answers `202` with the backend's own receipt the moment the service accepts it. |
1404-| POST | `/podcast/jobs` | student | Start one podcast job. Answers `202` with the service's receipt the moment the service accepts it; the pipeline then runs in the service's own worker pool, so poll `GET /jobs/{id}` for progress. |1413+| GET | `/podcast/jobs/{id}` | student | One job's current state — the backend's own row, so this door answers with the service down, restarted, or never connected at all. A job nobody has updated inside its ETA-scaled window reads as `failed`/`interrupted`; that projection is read-side only and never written. |
1405-| GET | `/podcast/jobs/{id}` | student | One job's current state. Poll this; the answer is the service's own snapshot. |1414+| GET | `/podcast/jobs/{id}/audio` | student | Stream one produced episode. The bytes are this school's own — ingested under this school's blob directory — and the content type is the one the upload declared, replayed from the row. |
1406-| POST | `/podcast/jobs/{id}/cancel` | student | Cancel one job. `cancelled` says whether *this call* stopped work — a job that had already finished, or was already cancelled, answers `false` and is not an error. |1415+| POST | `/podcast/jobs/{id}/cancel` | student | Cancel one job. `cancelled` says whether *this call* stopped work — a job that had already finished, or was already cancelled, answers `false` and is not an error. Only a live job needs the service; a terminal one is answered from the row without a worker. A service that has never heard of a live job (its store was wiped) leaves the row `failed`/`interrupted`: the job cannot finish, and the row says so. |
1407-| GET | `/podcast/jobs/{id}/result` | student | A finished job's artifacts — above all the `audio_id` the audio door streams. A job that has not finished yet is refused by the service with `not_ready` (409); one it has never heard of with `not_found` (404). |1416+| GET | `/podcast/jobs/{id}/result` | student | A finished job's artifact references. A job that has not finished is a `409 not_ready`; one the caller does not own, a `404`. |
1408 | POST | `/pomodoro/finish` | student | Finish the running pomodoro session, closing it with a server-stamped instant (`409` when nothing is running); answers `counted` — whether it moved the badge counters (ran at least `pomodoro.min_counted_ms`, within that UTC day's `pomodoro.max_counted_per_day`). |1417 | POST | `/pomodoro/finish` | student | Finish the running pomodoro session, closing it with a server-stamped instant (`409` when nothing is running); answers `counted` — whether it moved the badge counters (ran at least `pomodoro.min_counted_ms`, within that UTC day's `pomodoro.max_counted_per_day`). |
1409 | GET | `/pomodoro/me` | student | The caller's own pomodoro log, newest first — the running session (if any) included (`finished_at: null`) — plus `total_focus_ms`, the unpaged sum of finished-session durations. Paged via `?limit=&offset=` (omit `limit` for the whole log). |1418 | GET | `/pomodoro/me` | student | The caller's own pomodoro log, newest first — the running session (if any) included (`finished_at: null`) — plus `total_focus_ms`, the unpaged sum of finished-session durations. Paged via `?limit=&offset=` (omit `limit` for the whole log). |
1410 | POST | `/pomodoro/start` | student | Start a pomodoro focus session. Students only. The instant is stamped by the server clock — clients never supply it. Always succeeds for a student: a dangling unfinished session (the browser died mid-timer) is discarded and replaced, so there is no way to lock yourself out of starting. The frontend runs the visible countdown and the break rhythm; the backend records only the focus stint. The body is optional and names the stint: a `label` rides the response and every log it lists in — a blank or absent body starts an unnamed stint, an over-long label is `400`. |1419 | POST | `/pomodoro/start` | student | Start a pomodoro focus session. Students only. The instant is stamped by the server clock — clients never supply it. Always succeeds for a student: a dangling unfinished session (the browser died mid-timer) is discarded and replaced, so there is no way to lock yourself out of starting. The frontend runs the visible countdown and the break rhythm; the backend records only the focus stint. The body is optional and names the stint: a `label` rides the response and every log it lists in — a blank or absent body starts an unnamed stint, an over-long label is `400`. |
src/ai/capability.rsadded+101 -0
@@ -0,0 +1,101 @@
1+//! The table of capabilities the **backend** serves — the operations a
2+//! service calls over the bridge's client-initiated `CapabilityRequest` shape
3+//! (`hab/2`'s third request kind), and each one's scope.
4+//!
5+//! There is one table per capability family, and this module is the walk over
6+//! them: [`crate::ai::insight`] serves ZEKA's storage surface,
7+//! [`crate::ai::podcast`] serves the podcast job's state reports. Both answer
8+//! the same frame, both are dispatched from the same place — the bridge's
9+//! capability dispatcher in `ai::server` — and neither owns the other's
10+//! names: a name neither table holds is `unknown_capability`, with no prefix
11+//! match and no fallback, exactly as the two tables' own doc comments say.
12+//!
13+//! The scope decides one thing only: whether the bridge resolves the frame's
14+//! school before the operation runs. A [`Scope::School`] operation runs against
15+//! the named school's own database — the frame's school is the *only* tenancy
16+//! input, and a slug that matches nothing is `unknown_school`, never a
17+//! fallback to another school or to the control database.
18+
19+use serde_json::Value;
20+
21+use crate::ai::podcast;
22+use crate::constant::AI_PODCAST_REPORT_CAPABILITY;
23+use crate::database::Database;
24+use crate::tenant::ResolvedTenant;
25+
26+pub use crate::ai::insight::Scope;
27+
28+/// The refusal shape every backend-served capability answers with: a flat,
29+/// stable code and a message that names the field or reason. Same alias as
30+/// [`crate::ai::insight::Refusal`] — one vocabulary across families.
31+pub type Refusal = (&'static str, String);
32+
33+/// Every capability the podcast family serves, and its scope. One entry today;
34+/// a table rather than a match arm so the walk in [`scope_of`] and the
35+/// dispatch in [`serve`] are structurally the same decision, and a second
36+/// podcast operation is one added row.
37+pub const PODCAST_SERVED: &[(&str, Scope)] = &[(AI_PODCAST_REPORT_CAPABILITY, Scope::School)];
38+
39+/// The scope of one backend-served capability, or `None` if no family serves
40+/// it. Matched exactly, family by family, in a fixed order.
41+pub fn scope_of(capability: &str) -> Option<Scope> {
42+ crate::ai::insight::scope_of(capability).or_else(|| {
43+ PODCAST_SERVED
44+ .iter()
45+ .find(|(name, _)| *name == capability)
46+ .map(|(_, scope)| *scope)
47+ })
48+}
49+
50+/// Run one backend-served capability. The caller (the bridge) resolves the
51+/// school *before* this is called, from [`scope_of`]'s answer — a
52+/// [`Scope::Deployment`] operation gets `None`, and a [`Scope::School`] one
53+/// always gets the tenant.
54+pub async fn serve(
55+ capability: &str,
56+ school: Option<&ResolvedTenant>,
57+ control: &Database,
58+ payload: &Value,
59+) -> Result<Value, Refusal> {
60+ if crate::ai::insight::scope_of(capability).is_some() {
61+ return crate::ai::insight::serve(capability, school, control, payload).await;
62+ }
63+ match capability {
64+ AI_PODCAST_REPORT_CAPABILITY => {
65+ let Some(tenant) = school else {
66+ return Err((
67+ "internal",
68+ format!("`{AI_PODCAST_REPORT_CAPABILITY}` is school-scoped but no school was resolved"),
69+ ));
70+ };
71+ // The frame's payload is cloned once per report call, and a report
72+ // is a handful of short fields — this is the price of one dispatch
73+ // table across two families that decode differently.
74+ podcast::report(&tenant.db, payload.clone()).await
75+ }
76+ _ => Err((
77+ "unknown_capability",
78+ format!("the backend serves no `{capability}` operation"),
79+ )),
80+ }
81+}
82+
83+#[cfg(test)]
84+mod tests {
85+ use super::*;
86+
87+ #[test]
88+ fn every_family_name_resolves_and_a_stranger_does_not() {
89+ assert_eq!(scope_of(AI_PODCAST_REPORT_CAPABILITY), Some(Scope::School));
90+ assert_eq!(scope_of("podcast.submit"), None, "worker-only, not served");
91+ assert_eq!(scope_of("podcast.status"), None, "deleted: the row answers");
92+ assert_eq!(scope_of("podcast.nothing"), None);
93+ assert_eq!(scope_of(""), None);
94+ }
95+
96+ #[test]
97+ fn the_podcast_table_is_exactly_its_documented_vocabulary() {
98+ assert_eq!(PODCAST_SERVED.len(), 1);
99+ assert!(PODCAST_SERVED.iter().all(|(_, scope)| *scope == Scope::School));
100+ }
101+}
src/ai/insight.rsmodified+212 -16
@@ -1,21 +1,20 @@
1-//! Payload contract for the `insight.*` capabilities, and the dispatch behind1+//! Payload contract for the `insight.*` capabilities, in both directions.
2-//! the two the backend can route today.
3 //!2 //!
4 //! ZEKA (`hezarfen_zeka`) computes student and class insights from a school's3 //! 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 backend4+//! own data. The family has two halves and they travel opposite ways:
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 //!5 //!
11-//! That split is why the dispatches here return the service's answer rather6+//! * **Outbound** (the backend dispatches to the service):
12-//! than store it — the answer is a receipt, and the rows are the product. A7+//! [`AI_INSIGHT_STUDENT_CAPABILITY`] — one student, on demand;
13-//! dispatch that times out, or a service that refuses, leaves the previously8+//! [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand. The
14-//! computed rows exactly as they are: a stale insight beats a hole. The two9+//! dispatches below carry them ([`compute_student`], [`refresh`]).
15-//! capabilities this module dispatches:10+//! * **Inbound** (the service calls the backend): the nine operations of
16-//!11+//! [`AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY`]'s family — the storage surface
17-//! * [`AI_INSIGHT_STUDENT_CAPABILITY`] — one student, on demand;12+//! ZEKA's `zeka_*` rows are written and read through, because **no AI
18-//! * [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand.13+//! service may touch a school database**. [`serve`] runs them; the SQL
14+//! lives in [`crate::db::insight`], and [`crate::web::insights`] mounts the
15+//! same functions as HTTP doors. This is the shape the whole family exists
16+//! for: an operation named on the wire, scoped to the frame's school, with
17+//! no path, no table and no query any caller can name.
19 //!18 //!
20 //! [`AI_INSIGHT_CLASS_CAPABILITY`] is declared (the service announces it) but19 //! [`AI_INSIGHT_CLASS_CAPABILITY`] is declared (the service announces it) but
21 //! deliberately not dispatched: its request names a course the service would20 //! deliberately not dispatched: its request names a course the service would
@@ -27,7 +26,9 @@
27 //! Every payload member is optional on the response side on purpose: the26 //! 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 legal27 //! 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 a28 //! answer, and a strict struct here would turn a service update into a
30-//! backend error.29+//! backend error. The inbound rows are the opposite: they are a *write*
30+//! contract, so a missing field is refused rather than defaulted — except
31+//! where this module says an omission is meaningful.
31 32
32 use std::time::Duration;33 use std::time::Duration;
33 34
@@ -221,6 +222,201 @@ fn malformed(err: serde_json::Error) -> AiError {
221 AiError::Protocol(FrameError::Malformed(err))222 AiError::Protocol(FrameError::Malformed(err))
222 }223 }
223 224
225+// ---- the operations the backend serves -------------------------------------
226+//
227+// The half of this module that runs *towards* the backend. ZEKA computes, but
228+// it may not write: no AI service holds a school database credential on this
229+// deployment, so its `zeka_*` rows are written and read here, by name, over
230+// the same bridge — one operation per call, each scoped to the school the
231+// frame named. [`crate::db::insight`] is the SQL; this is the contract: which
232+// names exist, what each payload is, and how a refusal reads.
233+
234+pub use crate::db::insight::{
235+ AttentionRow, PendingList, ProfileRow, ProfileWriteRequest, PurgeRequest, RecommendationRow,
236+ RecommendationWriteRequest, RunRow, RunWriteRequest, SchoolDirectory, SegmentConfidences,
237+ SegmentLabels, SegmentRow, SegmentWriteRequest, SummaryRow, SummaryWriteRequest,
238+ TableVerdicts, WriteReceipt,
239+};
240+
241+use crate::constant::{
242+ AI_INSIGHT_DEPARTED_PURGE_CAPABILITY, AI_INSIGHT_PENDING_LIST_CAPABILITY,
243+ AI_INSIGHT_PROFILE_UPSERT_CAPABILITY, AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY,
244+ AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, AI_INSIGHT_RUN_UPSERT_CAPABILITY,
245+ AI_INSIGHT_SCHOOLS_LIST_CAPABILITY, AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY,
246+ AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
247+};
248+use crate::database::Database;
249+use crate::db;
250+use crate::domain::timestamp::Timestamp;
251+use crate::error::AppError;
252+use crate::module::Module;
253+use crate::tenant::ResolvedTenant;
254+
255+/// A refusal headed for a [`CapabilityResponse::Err`](crate::ai::protocol::CapabilityResponse::Err):
256+/// the documented code, and a message that names the field a caller can fix.
257+pub type Refusal = (&'static str, String);
258+
259+/// What a served capability is scoped to.
260+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261+pub enum Scope {
262+ /// It runs against the school the frame named, and nothing else.
263+ School,
264+ /// Its answer does not come from a school's database at all — the
265+ /// directory the fleet schedules over. The frame sends no school.
266+ Deployment,
267+}
268+
269+/// Every capability the backend serves, and its scope. Matched exactly: a
270+/// name that is not here is `unknown_capability`, with no prefix match and no
271+/// fallback — an operation a caller cannot name is one it cannot run.
272+pub const SERVED: &[(&str, Scope)] = &[
273+ (AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, Scope::School),
274+ (
275+ AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY,
276+ Scope::School,
277+ ),
278+ (AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY, Scope::School),
279+ (AI_INSIGHT_PROFILE_UPSERT_CAPABILITY, Scope::School),
280+ (AI_INSIGHT_RUN_UPSERT_CAPABILITY, Scope::School),
281+ (AI_INSIGHT_PENDING_LIST_CAPABILITY, Scope::School),
282+ (AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, Scope::School),
283+ (AI_INSIGHT_DEPARTED_PURGE_CAPABILITY, Scope::School),
284+ (AI_INSIGHT_SCHOOLS_LIST_CAPABILITY, Scope::Deployment),
285+];
286+
287+/// The scope of one served capability, or `None` if the backend serves no
288+/// operation by that name.
289+pub fn scope_of(capability: &str) -> Option<Scope> {
290+ SERVED
291+ .iter()
292+ .find(|(name, _)| *name == capability)
293+ .map(|(_, scope)| *scope)
294+}
295+
296+/// Run one capability call and hand back its payload.
297+///
298+/// `school` is the tenant the bridge resolved for the frame — `None` only for
299+/// a [`Scope::Deployment`] capability, whose frame names no school. The
300+/// school's own feature set is checked here as well as at the HTTP nest: a
301+/// school that is not being served insights should not be accumulating rows
302+/// for them either.
303+pub async fn serve(
304+ capability: &str,
305+ school: Option<&ResolvedTenant>,
306+ control: &Database,
307+ payload: &Value,
308+) -> Result<Value, Refusal> {
309+ if scope_of(capability).is_none() {
310+ return Err((
311+ "unknown_capability",
312+ format!("the backend serves no `{capability}` operation"),
313+ ));
314+ }
315+ if capability == AI_INSIGHT_SCHOOLS_LIST_CAPABILITY {
316+ let directory = db::insight::active_schools(control).await.map_err(refusal)?;
317+ return encode(&directory);
318+ }
319+ let Some(tenant) = school else {
320+ return Err((
321+ "unknown_school",
322+ "this operation runs against a school and the frame named none".to_string(),
323+ ));
324+ };
325+ if !tenant.modules.contains(Module::Chatbot) {
326+ return Err((
327+ "not_permitted",
328+ "this school does not have the insights module enabled".to_string(),
329+ ));
330+ }
331+ let db = &tenant.db;
332+ let answer = match capability {
333+ AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY => {
334+ let request: SummaryWriteRequest = decode(payload)?;
335+ encode(&db::insight::write_summaries(db, request.rows).await.map_err(refusal)?)
336+ }
337+ AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY => {
338+ let request: RecommendationWriteRequest = decode(payload)?;
339+ encode(
340+ &db::insight::write_recommendations(db, request.rows)
341+ .await
342+ .map_err(refusal)?,
343+ )
344+ }
345+ AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY => {
346+ let request: SegmentWriteRequest = decode(payload)?;
347+ encode(&db::insight::write_segments(db, request.rows).await.map_err(refusal)?)
348+ }
349+ AI_INSIGHT_PROFILE_UPSERT_CAPABILITY => {
350+ let request: ProfileWriteRequest = decode(payload)?;
351+ encode(&db::insight::write_profiles(db, request.rows).await.map_err(refusal)?)
352+ }
353+ AI_INSIGHT_RUN_UPSERT_CAPABILITY => {
354+ let request: RunWriteRequest = decode(payload)?;
355+ encode(&db::insight::write_run(db, request.run).await.map_err(refusal)?)
356+ }
357+ AI_INSIGHT_PENDING_LIST_CAPABILITY => {
358+ encode(&db::insight::last_pending(db).await.map_err(refusal)?)
359+ }
360+ AI_INSIGHT_RETENTION_SWEEP_CAPABILITY => {
361+ // The backend's own clock decides expiry — a service's clock is
362+ // not a second authority on when a row's retention has closed.
363+ let now_ms = Timestamp::now().as_millis();
364+ encode(&db::insight::sweep(db, now_ms).await.map_err(refusal)?)
365+ }
366+ AI_INSIGHT_DEPARTED_PURGE_CAPABILITY => {
367+ let request: PurgeRequest = decode(payload)?;
368+ encode(
369+ &db::insight::purge_departed(db, request.students)
370+ .await
371+ .map_err(refusal)?,
372+ )
373+ }
374+ // `scope_of` matched above, so the table and this match agree; the
375+ // arm exists so a table entry without an operation is a compile-time
376+ // miss instead of a runtime surprise.
377+ other => {
378+ return Err((
379+ "unknown_capability",
380+ format!("the backend serves no `{other}` operation"),
381+ ));
382+ }
383+ };
384+ answer
385+}
386+
387+/// Decode one payload into the operation's own type. A payload that does not
388+/// fit is `invalid_payload`, never `malformed`: the frame was a capability
389+/// call, the body was not this operation's body, and the caller can fix it.
390+fn decode<T: DeserializeOwned>(payload: &Value) -> Result<T, Refusal> {
391+ serde_json::from_value(payload.clone())
392+ .map_err(|err| ("invalid_payload", format!("payload: {err}")))
393+}
394+
395+fn encode<T: Serialize>(value: &T) -> Result<Value, Refusal> {
396+ serde_json::to_value(value).map_err(|err| ("internal", format!("could not encode the answer: {err}")))
397+}
398+
399+/// [`AppError`] as the protocol's refusal vocabulary. The mapping is the
400+/// whole reason the db layer returns `AppError` rather than its own type:
401+/// HTTP answers these through [`crate::error`], and a capability call answers
402+/// the same verdict with the code a service branches on.
403+fn refusal(err: AppError) -> Refusal {
404+ match err {
405+ AppError::Validation(err) => ("invalid_payload", err.to_string()),
406+ AppError::PayloadTooLarge(message) => ("too_many_rows", message),
407+ AppError::ModuleDisabled(module) => (
408+ "not_permitted",
409+ format!("this school does not have the `{module}` module enabled"),
410+ ),
411+ AppError::NotFound => ("not_found", "the named row does not exist".to_string()),
412+ AppError::DbUnavailable | AppError::DbTimeout => (
413+ "unavailable",
414+ "this school's database could not be reached".to_string(),
415+ ),
416+ other => ("internal", other.to_string()),
417+ }
418+}
419+
224 #[cfg(test)]420 #[cfg(test)]
225 mod tests {421 mod tests {
226 use super::*;422 use super::*;
src/ai/protocol.rsmodified+243 -2
@@ -30,8 +30,48 @@
30 //! and then the stream is finished. That is how a service gets a course30 //! and then the stream is finished. That is how a service gets a course
31 //! note's file bytes, which no JSON frame could carry.31 //! note's file bytes, which no JSON frame could carry.
32 //!32 //!
33-//! The two client-initiated request shapes are told apart by their required33+//! * Each **capability call** also goes the service's way, on its own
34-//! field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has `file`.34+//! client-initiated bidirectional stream: the service writes one
35+//! [`CapabilityRequest`], finishes its send side, and reads one
36+//! [`CapabilityResponse`]. This is the reverse of the [`Request`]/
37+//! [`Response`] pair above, and it exists for the same reason the api read
38+//! does: capabilities live on both sides. The backend *dispatches*
39+//! `chat.reply` and `insight.student` to a service; a service *calls*
40+//! `insight.summary.upsert` and the rest of the backend's storage surface
41+//! to have the backend write rows an AI service may not write itself.
42+//!
43+//! The three client-initiated request shapes are told apart by their
44+//! required field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has
45+//! `file`, a [`CapabilityRequest`] has `capability`.
46+//!
47+//! * Each **blob upload** is the blob read's mirror image: the service writes
48+//! one [`BlobUploadRequest`], then exactly `size` **raw** bytes — again not a
49+//! frame — and finishes its send side; the backend stores them and answers
50+//! one [`BlobUploadResponse`] header frame. That is how a service hands back
51+//! an artifact it produced (today the podcast service's finished mp3), which
52+//! no JSON frame could carry. Distinguished from a [`BlobRequest`] by its
53+//! required `upload` marker and `job_id`.
54+//!
55+//! # Refusal codes
56+//!
57+//! [`ApiResponse::Err`], [`BlobResponse::Err`] and [`CapabilityResponse::Err`]
58+//! all carry a `code`: a stable, machine-readable string a service branches
59+//! on, never a message. The vocabulary, in one place:
60+//!
61+//! * `malformed` — the frame is not this shape (a missing or mistyped field).
62+//! * `unknown_capability` — no operation this backend serves has that name.
63+//! * `unknown_school` — the named slug is not a school on this deployment.
64+//! * `school_suspended` — it exists and is switched off; worth retrying later.
65+//! * `not_permitted` — the school's own feature set refuses the operation.
66+//! * `invalid_payload` — the payload does not fit the operation's contract
67+//! (`message` names the field).
68+//! * `too_many_rows` — a count bound was exceeded (`message` names it); the
69+//! operation was refused whole, never applied in part.
70+//! * `unavailable` — the school's database could not be reached.
71+//! * `timed_out` — the operation outlived the bridge's deadline; whether it
72+//! landed is unknown, so retrying is the caller's decision.
73+//! * `internal` — the backend failed while doing the work.
74+//! * `path_not_allowed`, `unknown_user`, `method_not_allowed` — api-read only.
35 //!75 //!
36 //! # School scoping76 //! # School scoping
37 //!77 //!
@@ -264,6 +304,124 @@ pub enum BlobResponse {
264 },304 },
265 }305 }
266 306
307+/// A call of one capability the *backend* serves, written by the service on a
308+/// fresh client-initiated stream. The mirror image of [`Request`], which the
309+/// backend writes when it calls a capability the *service* serves.
310+///
311+/// Distinguished from an [`ApiRequest`] by its required `capability` field and
312+/// from a [`BlobRequest`] by its required `school` and `payload`. There is no
313+/// path and no method: an operation is named, never addressed — the backend's
314+/// storage surface is a list of operations, and a frame that could name a
315+/// table, a schema or a query would be the door this shape exists to not have.
316+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
317+pub struct CapabilityRequest {
318+ /// Trace id (ULID). Not used for correlation — the stream does that.
319+ pub id: String,
320+ /// Slug of the school the call is scoped to. Required, exactly as on
321+ /// every other frame — one capability is deployment-scoped
322+ /// (`insight.schools.list`, whose answer *is* the school directory) and
323+ /// sends the empty string there.
324+ pub school: String,
325+ /// The operation to run. Matched exactly against the backend's served
326+ /// capabilities; anything else is `unknown_capability`.
327+ pub capability: String,
328+ /// Operation-specific body, opaque to the transport.
329+ pub payload: Value,
330+}
331+
332+/// The backend's single answer frame, mirroring [`Response`] field for field:
333+/// `status` is the discriminator, and both variants echo the school the call
334+/// named so a service can tell which of its in-flight calls was answered.
335+///
336+/// `Err` is a *handled* refusal (unknown capability, a payload that does not
337+/// fit, the school's database unreachable). A service that dies mid-call just
338+/// drops the stream, which surfaces as a transport error instead.
339+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
340+#[serde(tag = "status", rename_all = "snake_case")]
341+pub enum CapabilityResponse {
342+ Ok {
343+ /// Echo of [`CapabilityRequest::id`].
344+ id: String,
345+ /// Echo of [`CapabilityRequest::school`].
346+ school: String,
347+ payload: Value,
348+ },
349+ Err {
350+ /// Echo of [`CapabilityRequest::id`].
351+ id: String,
352+ /// Echo of [`CapabilityRequest::school`], as sent.
353+ school: String,
354+ /// One of this module's documented refusal codes.
355+ code: String,
356+ message: String,
357+ },
358+}
359+
360+/// A write of one produced artifact's *bytes*, written by the *service* on a
361+/// fresh client-initiated stream. The mirror image of [`BlobRequest`]: the
362+/// service names what it is handing over, exactly `size` raw bytes follow this
363+/// frame, and the backend stores them somewhere that belongs to the school —
364+/// never to the service's own volume.
365+///
366+/// Distinguished from a [`BlobRequest`] (the read) by the required `upload`
367+/// marker and its `job_id`: an upload is always *about* one backend-minted
368+/// job, and the backend links the stored blob to that job's row.
369+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
370+pub struct BlobUploadRequest {
371+ /// Trace id (ULID). Not used for correlation — the stream does that.
372+ pub id: String,
373+ /// The shape marker. Must be `true`; any other value is `malformed`.
374+ pub upload: bool,
375+ /// Slug of the school the artifact belongs to. Required — the bytes land
376+ /// in that school's own blob directory, never anywhere else.
377+ pub school: String,
378+ /// The backend-minted podcast job the artifact belongs to.
379+ pub job_id: String,
380+ /// The artifact's display name (an episode's file name). Stored as
381+ /// metadata; never used to build a path.
382+ pub name: String,
383+ /// The artifact's MIME type. Must be an `audio/*` type today.
384+ pub content_type: String,
385+ /// Exactly how many raw bytes follow this frame.
386+ pub size: u64,
387+ /// The episode's length, when the producer knows it. Metadata for the
388+ /// read doors; `None` is allowed.
389+ #[serde(default)]
390+ pub duration_secs: Option<f64>,
391+}
392+
393+/// The single answer frame an upload gets. There are no bytes after it: the
394+/// artifact travels service → backend only, and `Ok.key` is the handle the
395+/// read doors publish (`GET /podcast/jobs/{id}/audio` resolves it). A refusal
396+/// carries nothing after the frame, and the backend resets the stream rather
397+/// than reading a body it will not store.
398+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
399+#[serde(tag = "status", rename_all = "snake_case")]
400+pub enum BlobUploadResponse {
401+ Ok {
402+ /// Echo of [`BlobUploadRequest::id`].
403+ id: String,
404+ /// Echo of [`BlobUploadRequest::school`].
405+ school: String,
406+ /// The key the bytes were stored under, relative to the school's blob
407+ /// root (`podcast/<job-id>.<ext>`).
408+ key: String,
409+ /// How many bytes were written — always the request's `size`.
410+ size: u64,
411+ },
412+ Err {
413+ /// Echo of [`BlobUploadRequest::id`].
414+ id: String,
415+ /// Echo of [`BlobUploadRequest::school`], as sent.
416+ school: String,
417+ /// This module's documented refusal codes, plus the operation's own
418+ /// (`unknown_job`, `expired`, `audio_missing`, …) — flat and stable,
419+ /// never nested.
420+ code: String,
421+ message: String,
422+ },
423+}
424+
267 /// Write one length-prefixed JSON frame.425 /// Write one length-prefixed JSON frame.
268 pub async fn write_frame<W, T>(w: &mut W, message: &T) -> Result<(), FrameError>426 pub async fn write_frame<W, T>(w: &mut W, message: &T) -> Result<(), FrameError>
269 where427 where
@@ -468,6 +626,89 @@ mod tests {
468 assert_eq!(err["code"], "path_not_allowed");626 assert_eq!(err["code"], "path_not_allowed");
469 }627 }
470 628
629+ #[tokio::test]
630+ async fn capability_frame_tags_are_the_documented_wire_names() {
631+ // The answer mirrors `Response` exactly — same `status` discriminator,
632+ // same field names — so a service decodes both with one function.
633+ // Pinned because other-language services match these literals.
634+ let ok = serde_json::to_value(CapabilityResponse::Ok {
635+ id: "1".into(),
636+ school: "demo".into(),
637+ payload: json!({ "written": 2 }),
638+ })
639+ .unwrap();
640+ assert_eq!(ok["status"], "ok");
641+ assert_eq!(ok["id"], "1");
642+ assert_eq!(ok["school"], "demo");
643+ assert_eq!(ok["payload"]["written"], 2);
644+ let err = serde_json::to_value(CapabilityResponse::Err {
645+ id: "1".into(),
646+ school: "demo".into(),
647+ code: "unknown_capability".into(),
648+ message: "nope".into(),
649+ })
650+ .unwrap();
651+ assert_eq!(err["status"], "err");
652+ assert_eq!(err["code"], "unknown_capability");
653+ assert_eq!(err["school"], "demo");
654+ // A refusal carries no payload: there is no half-answer to read.
655+ assert!(err.get("payload").is_none());
656+ }
657+
658+ #[tokio::test]
659+ async fn a_capability_request_needs_an_id_a_school_a_capability_and_a_payload() {
660+ let call: CapabilityRequest = serde_json::from_value(json!({
661+ "id": "01J",
662+ "school": "demo",
663+ "capability": "insight.summary.upsert",
664+ "payload": { "rows": [] },
665+ }))
666+ .unwrap();
667+ assert_eq!(call.capability, "insight.summary.upsert");
668+ // Each of the three fields is required: a frame missing its
669+ // capability names no operation to run, and a frame missing its
670+ // school could only be answered out of a database nobody named.
671+ for missing in ["id", "school", "capability", "payload"] {
672+ let mut frame = json!({
673+ "id": "01J",
674+ "school": "demo",
675+ "capability": "insight.pending.list",
676+ "payload": {},
677+ });
678+ frame.as_object_mut().unwrap().remove(missing);
679+ assert!(
680+ serde_json::from_value::<CapabilityRequest>(frame).is_err(),
681+ "a frame without `{missing}` must not parse"
682+ );
683+ }
684+ }
685+
686+ #[tokio::test]
687+ async fn the_client_initiated_shapes_do_not_parse_as_each_other() {
688+ // Routing is by required field (`path` / `file` / `capability`), so
689+ // this is the property that keeps a capability call from being
690+ // mistaken for an api read — or for a blob read, which is what the
691+ // frame would look like if `capability` were ever optional.
692+ let call = json!({
693+ "id": "01J",
694+ "school": "demo",
695+ "capability": "insight.pending.list",
696+ "payload": {},
697+ });
698+ assert!(
699+ serde_json::from_value::<CapabilityRequest>(call.clone()).is_ok(),
700+ "the capability frame must parse as a capability call"
701+ );
702+ assert!(
703+ serde_json::from_value::<ApiRequest>(call.clone()).is_err(),
704+ "a capability call must not parse as an api read"
705+ );
706+ assert!(
707+ serde_json::from_value::<BlobRequest>(call).is_err(),
708+ "a capability call must not parse as a blob read"
709+ );
710+ }
711+
471 #[tokio::test]712 #[tokio::test]
472 async fn an_api_request_needs_only_an_id_a_school_and_a_path() {713 async fn an_api_request_needs_only_an_id_a_school_and_a_path() {
473 let bare: ApiRequest = serde_json::from_value(json!({714 let bare: ApiRequest = serde_json::from_value(json!({
src/ai/server.rsmodified+257 -2
@@ -15,8 +15,9 @@ use tracing::Instrument;
15 15
16 use crate::ai::error::AiError;16 use crate::ai::error::AiError;
17 use crate::ai::protocol::{17 use crate::ai::protocol::{
18- ApiRequest, ApiResponse, BlobRequest, BlobResponse, FrameError, Greeting, Hello, RejectCode,18+ ApiRequest, ApiResponse, BlobRequest, BlobResponse, BlobUploadRequest, BlobUploadResponse,
19- Request, Response, protocol_matches, read_frame, write_frame,19+ CapabilityRequest, CapabilityResponse, FrameError, Greeting, Hello, RejectCode, Request,
20+ Response, protocol_matches, read_frame, write_frame,
20 };21 };
21 use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency};22 use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency};
22 use crate::ai::tls;23 use crate::ai::tls;
@@ -495,6 +496,42 @@ async fn serve_client_stream(
495 }496 }
496 return;497 return;
497 }498 }
499+ // The third client-initiated shape: a call of a capability the *backend*
500+ // serves (ZEKA's storage surface). Routed on `capability`, which neither
501+ // of the shapes above carries.
502+ if raw.get("capability").is_some() {
503+ match serde_json::from_value::<CapabilityRequest>(raw) {
504+ Ok(request) => {
505+ let response = serve_capability(&inner, request).await;
506+ answer_capability(&mut send, response).await;
507+ }
508+ Err(e) => {
509+ answer_capability(
510+ &mut send,
511+ capability_refusal(&id, &school, "malformed", e.to_string()),
512+ )
513+ .await;
514+ }
515+ }
516+ return;
517+ }
518+ // The fourth client-initiated shape: an artifact's bytes coming *in* (the
519+ // podcast service's finished mp3). Routed on `upload`, the marker neither
520+ // of the shapes above carries; the `size` raw bytes follow the frame on
521+ // this same stream.
522+ if raw.get("upload").is_some() {
523+ match serde_json::from_value::<BlobUploadRequest>(raw) {
524+ Ok(request) => serve_upload(&inner, &mut send, recv, request).await,
525+ Err(e) => {
526+ let refused = upload_refusal(id, school, "malformed", e.to_string());
527+ if let Err(e) = write_frame(&mut send, &refused).await {
528+ tracing::warn!("could not refuse an AI service's malformed upload: {e}");
529+ }
530+ let _ = send.finish();
531+ }
532+ }
533+ return;
534+ }
498 // Neither shape. Reported as the api-read refusal it has always been —535 // Neither shape. Reported as the api-read refusal it has always been —
499 // `path` is the field a frame this far off most likely meant to carry.536 // `path` is the field a frame this far off most likely meant to carry.
500 let api_err = serde_json::from_value::<ApiRequest>(raw)537 let api_err = serde_json::from_value::<ApiRequest>(raw)
@@ -580,6 +617,107 @@ async fn write_blob_body(
580 }617 }
581 }618 }
582 619
620+/// Serve one artifact upload: validate the frame, store exactly `size` bytes
621+/// under the school's blob root, stamp the job's row, and answer one
622+/// [`BlobUploadResponse`] frame. Nothing follows the answer — the artifact
623+/// travels one way only.
624+///
625+/// A refusal answers the frame and resets the read side: the service may still
626+/// be writing its bytes, and none of them will be stored, so letting the
627+/// stream drain would only spend the sender's bandwidth on a file that is
628+/// already refused.
629+async fn serve_upload(
630+ inner: &Inner,
631+ send: &mut quinn::SendStream,
632+ mut recv: quinn::RecvStream,
633+ request: BlobUploadRequest,
634+) {
635+ let id = request.id.clone();
636+ let school = request.school.clone();
637+ let response = match ingest_upload(inner, &request, &mut recv).await {
638+ Ok((key, size)) => BlobUploadResponse::Ok {
639+ id,
640+ school,
641+ key,
642+ size,
643+ },
644+ Err((code, message)) => {
645+ // The bytes that would have followed are not wanted; tell the
646+ // sender so its write stops rather than filling a stream nobody
647+ // reads.
648+ let _ = recv.stop(1u32.into());
649+ upload_refusal(
650+ request.id.clone(),
651+ request.school.clone(),
652+ &code,
653+ message,
654+ )
655+ }
656+ };
657+ if let Err(e) = write_frame(send, &response).await {
658+ tracing::warn!("could not answer an AI service's blob upload {}: {e}", request.id);
659+ }
660+ let _ = send.finish();
661+}
662+
663+/// The body of an upload: resolve the school, check the job, stream exactly
664+/// `size` bytes into a temp file under the school's own blob root, rename it
665+/// into place, and stamp the row. `Err` is the refusal `(code, message)`.
666+///
667+/// The order is the point: metadata and the job's existence are checked before
668+/// a byte is read (a refusal must not cost the sender the whole file), and the
669+/// bytes are complete on disk — renamed, not half-written — before the row
670+/// names them. A row write that finds the job gone deletes the file it just
671+/// stored rather than leaving an orphan.
672+async fn ingest_upload(
673+ inner: &Inner,
674+ request: &BlobUploadRequest,
675+ body: &mut quinn::RecvStream,
676+) -> Result<(String, u64), (&'static str, String)> {
677+ if !request.upload {
678+ return Err((
679+ "malformed",
680+ "`upload` must be true on a blob upload".to_string(),
681+ ));
682+ }
683+ let api = inner.api.get().ok_or((
684+ "unavailable",
685+ "the api is not serving yet — retry".to_string(),
686+ ))?;
687+ let tenant = api.school(&request.school).await?;
688+ let (slug, db) = (tenant.slug, tenant.db);
689+ // This stream bypasses the router, so it also bypasses the route_layer the
690+ // module gate is — the entitlement is checked here by hand instead. The
691+ // podcast nest is the `chatbot` module's, exactly as it is over HTTP.
692+ if !tenant.modules.contains(Module::Chatbot) {
693+ return Err((
694+ "not_permitted",
695+ format!("the `{slug}` school has no `chatbot` module"),
696+ ));
697+ }
698+ let refusal = crate::ai::podcast::refusal;
699+ let root = api.files_dir(&slug);
700+ let (key, size) = crate::ai::podcast::ingest(&db, &root, request, body)
701+ .await
702+ .map_err(|r| refusal(&r))?;
703+ Ok((key, size))
704+}
705+
706+/// One upload refusal frame. The school is echoed as the caller spelled it.
707+fn upload_refusal(
708+ id: String,
709+ school: String,
710+ code: &str,
711+ message: String,
712+) -> BlobUploadResponse {
713+ BlobUploadResponse::Err {
714+ id,
715+ school,
716+ code: code.to_string(),
717+ message,
718+ }
719+}
720+
583 /// Resolve, authorize and open one blob. `Err` is the refusal that becomes a721 /// Resolve, authorize and open one blob. `Err` is the refusal that becomes a
584 /// [`BlobResponse::Err`] code.722 /// [`BlobResponse::Err`] code.
585 ///723 ///
@@ -909,6 +1047,123 @@ async fn write_answer<W: tokio::io::AsyncWrite + Unpin>(
909 written1047 written
910 }1048 }
911 1049
1050+/// Run one capability the backend serves, and frame its answer.
1051+///
1052+/// The school is resolved the same way an api read's is — through the same
1053+/// registry, with the same three refusals — because it decides *which
1054+/// database* the operation runs against; a deployment-scoped capability
1055+/// (the school directory) resolves none, and is the only one that may.
1056+/// The work is bounded by the bridge's own request deadline: past it the
1057+/// service gets `timed_out` and decides for itself whether to retry, which is
1058+/// the honest answer, since the statement may well have landed.
1059+async fn serve_capability(inner: &Inner, request: CapabilityRequest) -> CapabilityResponse {
1060+ // The backend-served families walk one composed table
1061+ // ([`crate::ai::capability`]): ZEKA's storage surface and the podcast
1062+ // job's state reports. The scope decides whether the frame's school is
1063+ // resolved below — it is, for every family today.
1064+ use crate::ai::capability::{self, Scope};
1065+
1066+ let Some(api) = inner.api.get() else {
1067+ return capability_refusal(
1068+ &request.id,
1069+ &request.school,
1070+ "unavailable",
1071+ "this process has no api surface to run capabilities against".to_string(),
1072+ );
1073+ };
1074+ let tenant = match capability::scope_of(&request.capability) {
1075+ Some(Scope::Deployment) => None,
1076+ Some(Scope::School) => match api.school(&request.school).await {
1077+ Ok(tenant) => Some(tenant),
1078+ Err((code, message)) => {
1079+ return capability_refusal(&request.id, &request.school, code, message);
1080+ }
1081+ },
1082+ None => {
1083+ return capability_refusal(
1084+ &request.id,
1085+ &request.school,
1086+ "unknown_capability",
1087+ format!("the backend serves no `{}` operation", request.capability),
1088+ );
1089+ }
1090+ };
1091+ let control = api.tenants.control();
1092+ let call = capability::serve(
1093+ &request.capability,
1094+ tenant.as_ref(),
1095+ &control,
1096+ &request.payload,
1097+ );
1098+ match tokio::time::timeout(inner.request_timeout, call).await {
1099+ Ok(Ok(payload)) => CapabilityResponse::Ok {
1100+ id: request.id,
1101+ school: request.school,
1102+ payload,
1103+ },
1104+ Ok(Err((code, message))) => {
1105+ capability_refusal(&request.id, &request.school, code, message)
1106+ }
1107+ Err(_) => capability_refusal(
1108+ &request.id,
1109+ &request.school,
1110+ "timed_out",
1111+ format!(
1112+ "the operation did not finish within {}s",
1113+ inner.request_timeout.as_secs()
1114+ ),
1115+ ),
1116+ }
1117+}
1118+
1119+/// One refusal frame, with the school echoed as the caller spelled it.
1120+fn capability_refusal(
1121+ id: &str,
1122+ school: &str,
1123+ code: &str,
1124+ message: String,
1125+) -> CapabilityResponse {
1126+ CapabilityResponse::Err {
1127+ id: id.to_string(),
1128+ school: school.to_string(),
1129+ code: code.to_string(),
1130+ message,
1131+ }
1132+}
1133+
1134+async fn answer_capability(send: &mut quinn::SendStream, response: CapabilityResponse) {
1135+ if let Err(e) = write_capability_answer(send, &response).await {
1136+ tracing::warn!("could not answer an AI service's capability call: {e}");
1137+ }
1138+ let _ = send.finish();
1139+}
1140+
1141+/// Frame one capability answer, downgrading an oversize `Ok` exactly as
1142+/// [`write_answer`] does for an api read: an answer too big to frame becomes a
1143+/// `too_large` refusal rather than silence, since a caller that got no frame
1144+/// at all would wait out its own deadline to learn nothing.
1145+async fn write_capability_answer<W: tokio::io::AsyncWrite + Unpin>(
1146+ w: &mut W,
1147+ response: &CapabilityResponse,
1148+) -> Result<(), FrameError> {
1149+ let written = write_frame(w, response).await;
1150+ if let (Err(FrameError::TooLarge(_)), CapabilityResponse::Ok { id, school, .. }) =
1151+ (&written, response)
1152+ {
1153+ return write_frame(
1154+ w,
1155+ &capability_refusal(
1156+ id,
1157+ school,
1158+ "too_large",
1159+ format!("the answer exceeds the {AI_MAX_FRAME_BYTES}-byte frame limit"),
1160+ ),
1161+ )
1162+ .await;
1163+ }
1164+ written
1165+}
1166+
912 /// Read the `Hello`, decide, answer, and register on success.1167 /// Read the `Hello`, decide, answer, and register on success.
913 ///1168 ///
914 /// `Err(())` means the connection was refused and already closed — the caller1169 /// `Err(())` means the connection was refused and already closed — the caller
src/constant.rsmodified+132 -17
@@ -598,7 +598,9 @@ pub const AI_RAG_CHAT_TIMEOUT_SECS: u64 = 90;
598 /// `hezarfen_zeka`). It is the on-demand half of ZEKA — the service also598 /// `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" is599 /// 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 the600 /// 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.601+/// bridge's api reads and has the backend write its `zeka_*` rows — no AI
602+/// service holds a school database credential here (see the storage-surface
603+/// constants below).
602 pub const AI_INSIGHT_STUDENT_CAPABILITY: &str = "insight.student";604 pub const AI_INSIGHT_STUDENT_CAPABILITY: &str = "insight.student";
603 605
604 /// Deadline on one `insight.student` round trip. Computing one student reads606 /// Deadline on one `insight.student` round trip. Computing one student reads
@@ -619,7 +621,7 @@ pub const AI_INSIGHT_CLASS_CAPABILITY: &str = "insight.class";
619 621
620 /// The capability an AI service declares to recompute a whole school's622 /// The capability an AI service declares to recompute a whole school's
621 /// insights. A batch job: the service works through its configured student623 /// 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 own624+/// list under its own time budget and has the backend write its run ledger. Like ZEKA's own
623 /// schedule, this is optional on top of the service's own cadence — it is625 /// 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.626 /// what lets the office trigger a sweep from the UI.
625 pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh";627 pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh";
@@ -633,6 +635,81 @@ pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh";
633 /// summary.635 /// summary.
634 pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300;636 pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300;
635 637
638+// ---- zeka's storage surface (capabilities the *backend* serves) ------------
639+//
640+// The three constants above are capabilities an AI service *declares*: the
641+// backend dispatches `insight.student`/`insight.refresh` to ZEKA and ZEKA
642+// answers. The nine below run the other way and are the reason this section
643+// exists: no AI service may touch a school database directly, so every read
644+// and write ZEKA needs against its own `zeka_*` tables is a named operation
645+// the backend performs on its behalf, on the same bridge, on a
646+// client-initiated stream (`src/ai/server.rs::serve_client_stream`).
647+//
648+// They are deliberately *not* declared here as worker capabilities: a worker
649+// never announces them, and `AiBridge::dispatch` never routes them. They are
650+// the backend's own surface, dispatched by capability name against
651+// `crate::ai::insight`'s table — an operation, never a query: no capability
652+// takes a database, a schema, a table or a SQL fragment, and the school is
653+// the frame's own field, resolved to that school's database before any
654+// statement runs.
655+
656+/// ZEKA stores one student's computed summary (and that student's attention
657+/// items, replaced wholesale) for one school.
658+pub const AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY: &str = "insight.summary.upsert";
659+
660+/// ZEKA stores the recommendation cards a run produced. The backend mints the
661+/// rows' ids — an id is the writer's, and the writer is now the backend.
662+pub const AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY: &str = "insight.recommendation.upsert";
663+
664+/// ZEKA stores its question-segment labels (and each question's dimension
665+/// split, replaced wholesale).
666+pub const AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY: &str = "insight.segment.upsert";
667+
668+/// ZEKA stores a student's per-dimension segment profile.
669+pub const AI_INSIGHT_PROFILE_UPSERT_CAPABILITY: &str = "insight.profile.upsert";
670+
671+/// ZEKA stores one compute run's ledger row (and the run's pending students
672+/// and failed modules, both replaced wholesale).
673+pub const AI_INSIGHT_RUN_UPSERT_CAPABILITY: &str = "insight.run.upsert";
674+
675+/// ZEKA reads back the students the freshest run left pending — where the
676+/// next run starts.
677+pub const AI_INSIGHT_PENDING_LIST_CAPABILITY: &str = "insight.pending.list";
678+
679+/// ZEKA asks the backend to sweep every `zeka_*` table of rows whose
680+/// retention window has closed.
681+pub const AI_INSIGHT_RETENTION_SWEEP_CAPABILITY: &str = "insight.retention.sweep";
682+
683+/// ZEKA asks the backend to delete the derived rows of students who are no
684+/// longer enrolled.
685+pub const AI_INSIGHT_DEPARTED_PURGE_CAPABILITY: &str = "insight.departed.purge";
686+
687+/// The one deployment-scoped operation: the active schools a shared AI fleet
688+/// schedules over. The frame carries no school because its answer is the
689+/// directory itself — the same reason [`crate::ai::protocol::Hello`] carries
690+/// none.
691+pub const AI_INSIGHT_SCHOOLS_LIST_CAPABILITY: &str = "insight.schools.list";
692+
693+/// The most rows one of the four bulk writes may carry in a single call. The
694+/// service's own batch size (`store.BATCH_SIZE` in `hezarfen_zeka`) — it
695+/// chunks its nightly output at exactly this, and a call one row past it is
696+/// refused (`too_many_rows`) rather than truncated, because a silently
697+/// shortened batch would read as a written student.
698+pub const MAX_INSIGHT_BATCH_ROWS: usize = 500;
699+
700+/// The most students `insight.pending.list` will answer with. The list is
701+/// handed over whole — the service resumes its next run from it, so a
702+/// clipped list would silently drop students — and a school past this bound
703+/// is refused (`too_many_rows`) instead.
704+pub const MAX_INSIGHT_PENDING_STUDENTS: usize = 20_000;
705+
706+/// The most students one `insight.departed.purge` call may name. Same shape
707+/// as [`MAX_INSIGHT_PENDING_STUDENTS`]: over it the call is refused, and the
708+/// empty list is refused too — an empty roster is a fetch that failed, and
709+/// deleting every derived row on that reading would be the worst available
710+/// mistake.
711+pub const MAX_INSIGHT_PURGE_STUDENTS: usize = 20_000;
712+
636 /// How long a `rag.chat` turn may sit `pending` before a reader projects it as713 /// How long a `rag.chat` turn may sit `pending` before a reader projects it as
637 /// failed. The RAG nest mirrors the chatbot's asynchronous send714 /// failed. The RAG nest mirrors the chatbot's asynchronous send
638 /// ([`CHATBOT_PENDING_STALE_SECS`]): the round trip outlives the request that715 /// ([`CHATBOT_PENDING_STALE_SECS`]): the round trip outlives the request that
@@ -643,25 +720,30 @@ pub const RAG_PENDING_STALE_SECS: i64 = CHATBOT_PENDING_STALE_SECS;
643 // ---- podcast ---------------------------------------------------------------720 // ---- podcast ---------------------------------------------------------------
644 //721 //
645 // The podcast service turns one stored source into an audio episode, which is722 // The podcast service turns one stored source into an audio episode, which is
646-// a *job*: submitted, polled, collected, and maybe cancelled — the service723+// a *job*. The backend owns the job's record: `POST /podcast/jobs` mints the
647-// owns the record, and the backend relays each HTTP call to the worker that724+// id, writes the `podcast_job` row, and dispatches `podcast.submit`; the
648-// declares the matching capability. All four capabilities answer immediately725+// service reports every transition back through the client-initiated
649-// (the pipeline runs in the service's own pool), so unlike `rag.index` and726+// `podcast.report` capability and uploads the finished mp3 as raw bytes. The
650-// `rag.chat` none of them needs a per-capability deadline: the bridge's727+// read doors (`GET /podcast/jobs/{id}`, `.../result`, `.../audio`) answer from
651-// ordinary request timeout already covers a job-store read.728+// the row, so a service restart or a wiped service volume costs liveness at
729+// most. Only submit and cancel are dispatched to a worker, and both answer
730+// immediately — the pipeline runs in the service's own pool — so neither needs
731+// a per-capability deadline: the bridge's ordinary request timeout covers a
732+// job-store write.
652 733
653 /// The capability an AI service declares to accept a podcast job. The backend734 /// The capability an AI service declares to accept a podcast job. The backend
654-/// dispatches on it from `POST /podcast/jobs`, and the service mints the job735+/// dispatches on it from `POST /podcast/jobs`, and the payload carries the
655-/// id every other `podcast.*` call then names.736+/// **backend-minted** job id — the id the row, the service's own record, and
737+/// the audio blob are all keyed by.
656 pub const AI_PODCAST_SUBMIT_CAPABILITY: &str = "podcast.submit";738 pub const AI_PODCAST_SUBMIT_CAPABILITY: &str = "podcast.submit";
657 739
658-/// The capability an AI service declares to report one podcast job's state,740+/// The capability the **backend** serves for one podcast job's state reports.
659-/// read back by `GET /podcast/jobs/{id}`.741+/// The service calls it — on a client-initiated stream, the same shape as
660-pub const AI_PODCAST_STATUS_CAPABILITY: &str = "podcast.status";742+/// ZEKA's storage surface — once per transition, echoing the job's identity
661-743+/// (`job_id`, `source_id`, `user_id`) and the state it moved to. The backend
662-/// The capability an AI service declares to hand back a finished job's744+/// validates the echo, the transition and the retention window, and writes its
663-/// artifacts — above all the `audio_id` the `/podcast/audio` door streams.745+/// own row; there is no state the service holds that the backend does not.
664-pub const AI_PODCAST_RESULT_CAPABILITY: &str = "podcast.result";746+pub const AI_PODCAST_REPORT_CAPABILITY: &str = "podcast.report";
665 747
666 /// The capability an AI service declares to cancel one podcast job. Its own748 /// The capability an AI service declares to cancel one podcast job. Its own
667 /// capability rather than a flag on submit: the cancel is a write on the749 /// capability rather than a flag on submit: the cancel is a write on the
@@ -669,6 +751,39 @@ pub const AI_PODCAST_RESULT_CAPABILITY: &str = "podcast.result";
669 /// can offer the door at all.751 /// can offer the door at all.
670 pub const AI_PODCAST_CANCEL_CAPABILITY: &str = "podcast.cancel";752 pub const AI_PODCAST_CANCEL_CAPABILITY: &str = "podcast.cancel";
671 753
754+/// The largest episode the backend will ingest from a service
755+/// (`BlobUploadRequest`). A ceiling, not a quota: a two-hour episode at a
756+/// generous bitrate is well under it, and anything above is refused before a
757+/// byte reaches disk — a service bug must not be able to fill the host.
758+pub const PODCAST_AUDIO_MAX_BYTES: usize = 256 * 1024 * 1024;
759+
760+/// How long a finished podcast job's record and audio stay readable. Past it
761+/// the doors answer `410` — the record is history, and the blob is no longer
762+/// served. Sized like the RAG outputs' retention window: long enough for a
763+/// listener to come back for yesterday's episode, short enough that a shared
764+/// host does not accumulate every episode ever made.
765+pub const PODCAST_JOB_RETENTION_SECS: i64 = 7 * 24 * 60 * 60;
766+
767+/// The floor of the read-side staleness window: a `queued`/`running` job
768+/// nobody has updated for at least this long is presented as
769+/// `failed`/`interrupted`. The window is
770+/// `max(PODCAST_JOB_STALE_FLOOR_SECS, eta_secs × PODCAST_JOB_STALE_ETA_FACTOR)`
771+/// so a queue wait the service itself estimated as long is never declared
772+/// dead mid-flight.
773+pub const PODCAST_JOB_STALE_FLOOR_SECS: i64 = 600;
774+
775+/// How many times a job's own ETA the service may exceed before the read side
776+/// stops believing it is still running. Three: past three times its own
777+/// estimate, the honest reading is that the process that owned it is gone.
778+pub const PODCAST_JOB_STALE_ETA_FACTOR: i64 = 3;
779+
780+/// The `error_code` a job carries when *this backend* concluded it died: a
781+/// dispatch that never reached a worker, a cancel of a job the service no
782+/// longer has, or a read-side projection of a stale row. Deliberately the
783+/// service's own word for the same fact (its restart sweep writes it too), so
784+/// a client sees one vocabulary however the job died.
785+pub const PODCAST_INTERRUPTED_CODE: &str = "interrupted";
786+
672 /// The most `(sınıf, ders)` scope pairs one `rag.chat` request may carry. The787 /// The most `(sınıf, ders)` scope pairs one `rag.chat` request may carry. The
673 /// corpus is routed by the **pair** — a grade and a subject list sent788 /// corpus is routed by the **pair** — a grade and a subject list sent
674 /// separately would cross-product into combinations the asker never named — so789 /// separately would cross-product into combinations the asker never named — so
src/db/insight.rsadded+986 -0
@@ -0,0 +1,986 @@
1+//! ZEKA's own tables, and the operations that write and read them.
2+//!
3+//! ZEKA (`hezarfen_zeka`) computes student and class insights, but it does
4+//! **not** touch a school database: every statement against the `zeka_*`
5+//! tables runs here, on the backend, under the school the caller named. That
6+//! is a standing rule of this deployment, not a preference — an AI service
7+//! process holding a database credential of its own would be a second, silent
8+//! door into every school's rows, one no request-scoped check can close. So
9+//! the service's storage surface is nine named operations ([`crate::ai::insight`]
10+//! carries the wire contract and the dispatch), and this module is what they
11+//! execute.
12+//!
13+//! The row types here are therefore **both** the SQL's input and the bridge's
14+//! payload: a nightly batch arrives as JSON, is parsed into these structs
15+//! (`invalid_payload` on anything that does not fit), and is written verbatim —
16+//! the backend is a trust boundary for the *shape*, never an author of the
17+//! content. Fields are spelled exactly as the tables' columns are, because a
18+//! consumer that has to guess a mapping between two spellings will eventually
19+//! guess wrong.
20+//!
21+//! Three invariants are worth stating up front, since they are what the SQL
22+//! below is arranged around:
23+//!
24+//! * **A batch is one transaction.** Every bulk write is all-or-nothing: a
25+//! refusal means nothing landed, so a service that retries a batch cannot
26+//! half-apply it. Row-at-a-time statements inside one transaction keep that
27+//! honesty without a multi-row statement whose bind count would be a second
28+//! bound to police; the batch ceiling [`MAX_INSIGHT_BATCH_ROWS`] keeps the
29+//! statement count bounded.
30+//! * **Child rows are replaced, never merged.** `attention`, the segment
31+//! `dimension` rows, and a run's `pending`/`failed_module` rows are deleted
32+//! for their owners and re-inserted from the payload. Merging would leave a
33+//! fact the service stopped producing on the screen forever.
34+//! * **The school is the database.** Every function here takes the school's
35+//! own pool and nothing else: there is no `school` column to filter on
36+//! because there is no row from another school in reach. Foreign keys carry
37+//! the rest — an id from another school's database is not a row this
38+//! database will accept, and that refusal is mapped to a validation error
39+//! rather than a `500` so the caller learns which id was wrong.
40+
41+use std::collections::BTreeMap;
42+
43+use serde::{Deserialize, Serialize};
44+use serde_json::Value as JsonValue;
45+use sqlx::AssertSqlSafe;
46+use utoipa::ToSchema;
47+use uuid::Uuid;
48+
49+use crate::constant::{
50+ MAX_INSIGHT_BATCH_ROWS, MAX_INSIGHT_PENDING_STUDENTS, MAX_INSIGHT_PURGE_STUDENTS,
51+};
52+use crate::database::{Database, foreign_key_violation, tx_with_retry};
53+use crate::domain::monotonic_id::next_uuid;
54+use crate::error::{AppError, ValidationError};
55+
56+// ---- the wire rows ---------------------------------------------------------
57+
58+/// One student's computed summary, and the attention items that travel with
59+/// it. The two tables are replaced together — see the module docs.
60+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
61+pub struct SummaryRow {
62+ /// `app_user.id` of the student this summary is about.
63+ pub student: String,
64+ /// The four evidence blocks, stored verbatim as JSONB. `null` is a legal
65+ /// value: it means the section had no source rows, which is not the same
66+ /// fact as a section that was not computed.
67+ #[serde(default)]
68+ pub marks: Option<JsonValue>,
69+ #[serde(default)]
70+ pub attendance: Option<JsonValue>,
71+ #[serde(default)]
72+ pub submission: Option<JsonValue>,
73+ #[serde(default)]
74+ pub study: Option<JsonValue>,
75+ /// `none` | `exploratory` | `stable` — the service's own confidence in
76+ /// the summary; the table's CHECK is the authority on the vocabulary.
77+ pub confidence: String,
78+ /// When the service computed this row, unix milliseconds.
79+ pub computed_at: i64,
80+ /// Unix milliseconds after which the sweep deletes the row. The service
81+ /// owns its retention policy; the backend writes what it is told.
82+ pub retain_until: i64,
83+ /// The student's attention items, in the service's own order. Omitted
84+ /// means "this student has none", which clears the previous ones.
85+ #[serde(default)]
86+ pub attention: Vec<AttentionRow>,
87+}
88+
89+/// One attention item: a fact about a student that a teacher should see.
90+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
91+pub struct AttentionRow {
92+ /// The rule's trigger name, e.g. `not_egilimi_dusuyor`.
93+ pub trigger: String,
94+ /// The course the trigger fired in, when it fired in one.
95+ #[serde(default)]
96+ pub course: Option<String>,
97+ /// The one-line fact a reader sees.
98+ pub fact: String,
99+ /// The window the fact was measured over, unix milliseconds.
100+ pub window_from: i64,
101+ pub window_to: i64,
102+ /// The evidence object: the numbers behind the fact. Required — an item
103+ /// whose evidence is missing is dropped by the service before it is sent,
104+ /// and one that arrives without it is a payload error, not a silent write.
105+ pub evidence: JsonValue,
106+}
107+
108+/// One recommendation card.
109+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
110+pub struct RecommendationRow {
111+ /// The user the card is addressed to (`audience_role` says as what).
112+ pub audience: String,
113+ /// The product surface it belongs to, e.g. `student_home`.
114+ pub product: String,
115+ /// The rule that produced it, and the rule set's version.
116+ pub rule_id: String,
117+ pub rule_version: i64,
118+ /// The rule's own scope marker (a segment label, a course) — part of the
119+ /// natural key, so two scopes of one rule are two cards.
120+ #[serde(default)]
121+ pub scope: Option<String>,
122+ /// The student the card is *about*, when it is about one.
123+ #[serde(default)]
124+ pub about: Option<String>,
125+ /// `student` | `teacher` | `parent` | `manager`.
126+ pub audience_role: String,
127+ #[serde(default)]
128+ pub course: Option<String>,
129+ /// The evidence object. A row whose evidence carries nothing but
130+ /// `limitation` is **not written** and is counted `rejected` in the
131+ /// receipt — the service's own rule, kept where it can be audited.
132+ pub evidence: JsonValue,
133+ /// The stated limitation of the measurement, merged into the stored
134+ /// evidence object under `limitation`.
135+ #[serde(default)]
136+ pub limitation: Option<String>,
137+ /// `none` | `exploratory` | `stable`.
138+ pub confidence: String,
139+ pub computed_at: i64,
140+ pub expires_at: i64,
141+ pub retain_until: i64,
142+}
143+
144+/// The four rubric labels of one question, in the service's nested shape.
145+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
146+pub struct SegmentLabels {
147+ pub bilissel_talep: String,
148+ pub dikkat_tuzagi: String,
149+ pub okuma_yuku: String,
150+ pub adim_sayisi: String,
151+}
152+
153+/// The model's confidence in each of the four labels, `0..=1`.
154+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
155+pub struct SegmentConfidences {
156+ pub bilissel_talep: f64,
157+ pub dikkat_tuzagi: f64,
158+ pub okuma_yuku: f64,
159+ pub adim_sayisi: f64,
160+}
161+
162+/// One question's segment labels, and the dimension split that travels with
163+/// them (replaced together).
164+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
165+pub struct SegmentRow {
166+ /// The exam question this row labels.
167+ pub question: String,
168+ pub exam: String,
169+ pub course: String,
170+ pub subject: String,
171+ pub labels: SegmentLabels,
172+ pub confidences: SegmentConfidences,
173+ /// The row's overall confidence, `none` | `exploratory` | `stable`.
174+ pub confidence: String,
175+ /// The distractors the question's wrong answers point at, when known.
176+ #[serde(default)]
177+ pub trap_choice: Option<String>,
178+ /// Why the labels are what they are — the reader's audit trail.
179+ pub rationale: String,
180+ /// The model (and prompt) that produced the labels.
181+ pub model: String,
182+ pub prompt_version: String,
183+ /// The prompt variant, when the service is A/B-ing one.
184+ #[serde(default)]
185+ pub variant: Option<String>,
186+ pub computed_at: i64,
187+ pub retain_until: i64,
188+ /// Dimensions the downstream rules may use.
189+ #[serde(default)]
190+ pub downstream_dimensions: Vec<String>,
191+ /// Dimensions still being measured.
192+ #[serde(default)]
193+ pub experimental_dimensions: Vec<String>,
194+}
195+
196+/// One student's accuracy inside one rubric segment, against the same
197+/// student's overall rate. `contrast` is the only field rules may fire on.
198+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
199+pub struct ProfileRow {
200+ pub student: String,
201+ /// `bilissel_talep` | `dikkat_tuzagi` | `okuma_yuku` (production only).
202+ pub dimension: String,
203+ pub label: String,
204+ pub n_answers: i64,
205+ pub n_correct: i64,
206+ pub accuracy: f64,
207+ pub overall_n_answers: i64,
208+ pub overall_accuracy: f64,
209+ pub contrast: f64,
210+ /// `none` | `exploratory` | `stable`.
211+ pub confidence: String,
212+ pub computed_at: i64,
213+ pub retain_until: i64,
214+}
215+
216+/// One compute run's ledger row, with the run's own children.
217+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
218+pub struct RunRow {
219+ /// `YYYY-MM-DD` (TR day). The primary key: a re-run of the same night
220+ /// overwrites rather than duplicating.
221+ pub run_day: String,
222+ pub started_at: i64,
223+ #[serde(default)]
224+ pub finished_at: Option<i64>,
225+ /// `running` | `ok` | `partial` | `failed` | `skipped`.
226+ pub status: String,
227+ #[serde(default)]
228+ pub duration_ms: Option<i64>,
229+ pub students_total: i64,
230+ pub students_ok: i64,
231+ pub students_failed: i64,
232+ pub students_skipped: i64,
233+ pub rows_written: i64,
234+ pub budget_exceeded: bool,
235+ pub budget_ms: i64,
236+ pub retain_until: i64,
237+ /// Students the budget ran out on — the next run's starting point.
238+ #[serde(default)]
239+ pub pending_students: Vec<String>,
240+ /// Modules that failed in this run.
241+ #[serde(default)]
242+ pub failed_modules: Vec<String>,
243+}
244+
245+// ---- the request/receipt envelopes ----------------------------------------
246+
247+/// `insight.summary.upsert` / `POST /insights/summaries`.
248+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
249+pub struct SummaryWriteRequest {
250+ pub rows: Vec<SummaryRow>,
251+}
252+
253+/// `insight.recommendation.upsert` / `POST /insights/recommendations`.
254+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
255+pub struct RecommendationWriteRequest {
256+ pub rows: Vec<RecommendationRow>,
257+}
258+
259+/// `insight.segment.upsert` / `POST /insights/segments`.
260+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
261+pub struct SegmentWriteRequest {
262+ pub rows: Vec<SegmentRow>,
263+}
264+
265+/// `insight.profile.upsert` / `POST /insights/profiles`.
266+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
267+pub struct ProfileWriteRequest {
268+ pub rows: Vec<ProfileRow>,
269+}
270+
271+/// `insight.run.upsert` / `POST /insights/runs`.
272+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
273+pub struct RunWriteRequest {
274+ pub run: RunRow,
275+}
276+
277+/// `insight.departed.purge` / `POST /insights/purge`. The **active** roster:
278+/// every student not named loses their derived rows.
279+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
280+pub struct PurgeRequest {
281+ pub students: Vec<String>,
282+}
283+
284+/// What a bulk write did: rows written, and (for recommendations only) rows
285+/// the service's own evidence rule kept out.
286+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
287+pub struct WriteReceipt {
288+ pub written: u64,
289+ #[serde(default, skip_serializing_if = "is_zero")]
290+ pub rejected: u64,
291+}
292+
293+fn is_zero(value: &u64) -> bool {
294+ *value == 0
295+}
296+
297+/// The freshest run's pending students, in the service's order.
298+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
299+pub struct PendingList {
300+ pub students: Vec<String>,
301+}
302+
303+/// The per-table verdict of a sweep or a purge, keyed by table name — the
304+/// shape the service's CLI prints and exits non-zero on.
305+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
306+pub struct TableVerdicts {
307+ pub tables: BTreeMap<String, bool>,
308+}
309+
310+/// The deployment's active schools, by slug.
311+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
312+pub struct SchoolDirectory {
313+ pub schools: Vec<String>,
314+}
315+
316+// ---- shared validation -----------------------------------------------------
317+
318+/// Refuse a batch past [`MAX_INSIGHT_BATCH_ROWS`] rather than taking it
319+/// piecemeal: a batch is the unit the service retries, so accepting part of
320+/// one would turn its retry into a duplicate.
321+fn check_batch(field: &'static str, rows: &[impl Sized]) -> Result<(), AppError> {
322+ if rows.len() > MAX_INSIGHT_BATCH_ROWS {
323+ return Err(AppError::PayloadTooLarge(format!(
324+ "{field}: {} rows is over the ceiling of {MAX_INSIGHT_BATCH_ROWS} rows per call",
325+ rows.len()
326+ )));
327+ }
328+ Ok(())
329+}
330+
331+/// A foreign-key violation is a payload error here, not a server fault: the
332+/// statement named a row this school's database does not have (most often an
333+/// id belonging to another school), and the caller can fix it.
334+fn as_validation(err: AppError) -> AppError {
335+ match &err {
336+ AppError::Db(source) if foreign_key_violation(source) => {
337+ AppError::Validation(ValidationError::Invalid {
338+ field: "rows",
339+ reason: "a referenced row does not exist in this school",
340+ })
341+ }
342+ _ => err,
343+ }
344+}
345+
346+/// One hyphenated uuid from the wire. Ids cross the bridge as strings — the
347+/// `uuid` crate's serde support is not enabled here, and a string that is not
348+/// a uuid should read as a field error, not as a decode failure with no field.
349+fn parse_uuid(field: &'static str, value: &str) -> Result<Uuid, AppError> {
350+ Uuid::parse_str(value).map_err(|_| {
351+ AppError::Validation(ValidationError::Invalid {
352+ field,
353+ reason: "must be a hyphenated uuid",
354+ })
355+ })
356+}
357+
358+/// `YYYY-MM-DD`, the ledger's key. Checked here so a malformed day is the
359+/// caller's `invalid_payload` and not a CHECK violation dressed as a `500`.
360+fn run_day_ok(day: &str) -> bool {
361+ let bytes = day.as_bytes();
362+ bytes.len() == 10
363+ && bytes
364+ .iter()
365+ .enumerate()
366+ .all(|(i, b)| if matches!(i, 4 | 7) { *b == b'-' } else { b.is_ascii_digit() })
367+}
368+
369+// ---- writes ----------------------------------------------------------------
370+
371+/// Store a batch of student summaries, replacing each student's attention
372+/// items. One transaction: a batch lands whole or not at all.
373+pub async fn write_summaries(db: &Database, rows: Vec<SummaryRow>) -> Result<WriteReceipt, AppError> {
374+ check_batch("rows", &rows)?;
375+ let written = rows.len() as u64;
376+ tx_with_retry(db, false, async move |tx| write_summaries_in(tx, &rows).await)
377+ .await
378+ .map_err(as_validation)?;
379+ Ok(WriteReceipt {
380+ written,
381+ rejected: 0,
382+ })
383+}
384+
385+/// The transaction body of [`write_summaries`], a named fn rather than an async
386+/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
387+/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
388+async fn write_summaries_in(tx: &mut sqlx::PgConnection, rows: &[SummaryRow]) -> Result<(), AppError> {
389+
390+ for row in rows {
391+ let student = parse_uuid("student", &row.student)?;
392+ sqlx::query!(
393+ "INSERT INTO zeka_student_summary
394+ (student, marks, attendance, submission, study, confidence,
395+ computed_at, retain_until)
396+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
397+ ON CONFLICT (student) DO UPDATE SET
398+ marks = EXCLUDED.marks, attendance = EXCLUDED.attendance,
399+ submission = EXCLUDED.submission, study = EXCLUDED.study,
400+ confidence = EXCLUDED.confidence, computed_at = EXCLUDED.computed_at,
401+ retain_until = EXCLUDED.retain_until",
402+ student,
403+ row.marks.clone(),
404+ row.attendance.clone(),
405+ row.submission.clone(),
406+ row.study.clone(),
407+ row.confidence,
408+ row.computed_at,
409+ row.retain_until,
410+ )
411+ .execute(&mut *tx)
412+ .await?;
413+ sqlx::query!(
414+ "DELETE FROM zeka_attention_item WHERE student = $1",
415+ student,
416+ )
417+ .execute(&mut *tx)
418+ .await?;
419+ for (ord, item) in row.attention.iter().enumerate() {
420+ let course = item
421+ .course
422+ .as_deref()
423+ .map(|id| parse_uuid("course", id))
424+ .transpose()?;
425+ sqlx::query!(
426+ "INSERT INTO zeka_attention_item
427+ (student, trigger, course, fact, window_from, window_to, evidence, ord)
428+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
429+ student,
430+ item.trigger,
431+ course,
432+ item.fact,
433+ item.window_from,
434+ item.window_to,
435+ item.evidence.clone(),
436+ ord as i16,
437+ )
438+ .execute(&mut *tx)
439+ .await?;
440+ }
441+ }
442+ Ok(())
443+}
444+
445+/// The service's own evidence rule, applied where the write happens: a card
446+/// whose evidence carries nothing but its limitation is not a finding. Such a
447+/// row is counted `rejected` in the receipt and left unwritten — silently
448+/// dropping it would be the one thing this rule exists to prevent.
449+fn carries_evidence(evidence: &JsonValue) -> bool {
450+ evidence.as_object().is_some_and(|object| {
451+ object
452+ .iter()
453+ .any(|(key, value)| key != "limitation" && !value.is_null())
454+ })
455+}
456+
457+/// Store a batch of recommendation cards. The backend mints each row's id:
458+/// an id belongs to whoever writes the row, and that is now this process.
459+pub async fn write_recommendations(
460+ db: &Database,
461+ rows: Vec<RecommendationRow>,
462+) -> Result<WriteReceipt, AppError> {
463+ check_batch("rows", &rows)?;
464+ let (written, rejected) =
465+ tx_with_retry(db, false, async move |tx| write_recommendations_in(tx, &rows).await)
466+ .await
467+ .map_err(as_validation)?;
468+ Ok(WriteReceipt { written, rejected })
469+}
470+
471+/// The service's own evidence rule, applied where the write happens: a card
472+/// whose evidence carries nothing but its limitation is not a finding. Such a
473+/// row is counted `rejected` and left unwritten — silently dropping it would
474+/// be the one thing this rule exists to prevent. Returns `(written, rejected)`.
475+async fn write_recommendations_in(
476+ tx: &mut sqlx::PgConnection,
477+ rows: &[RecommendationRow],
478+) -> Result<(u64, u64), AppError> {
479+ let mut written = 0u64;
480+ let mut rejected = 0u64;
481+ for row in rows {
482+ if !carries_evidence(&row.evidence) {
483+ rejected += 1;
484+ continue;
485+ }
486+ let evidence = merge_limitation(&row.evidence, row.limitation.as_deref())?;
487+ let audience = parse_uuid("audience", &row.audience)?;
488+ let about = row
489+ .about
490+ .as_deref()
491+ .map(|id| parse_uuid("about", id))
492+ .transpose()?;
493+ let course = row
494+ .course
495+ .as_deref()
496+ .map(|id| parse_uuid("course", id))
497+ .transpose()?;
498+ sqlx::query!(
499+ "INSERT INTO zeka_recommendation
500+ (id, audience, product, rule_id, rule_version, scope, about, audience_role,
501+ course, evidence, confidence, created_at, expires_at, retain_until)
502+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
503+ ON CONFLICT (audience, product, rule_id, about, scope) DO UPDATE SET
504+ rule_version = EXCLUDED.rule_version,
505+ audience_role = EXCLUDED.audience_role,
506+ course = EXCLUDED.course,
507+ evidence = EXCLUDED.evidence,
508+ confidence = EXCLUDED.confidence,
509+ created_at = EXCLUDED.created_at,
510+ expires_at = EXCLUDED.expires_at,
511+ retain_until = EXCLUDED.retain_until",
512+ next_uuid(),
513+ audience,
514+ row.product,
515+ row.rule_id,
516+ row.rule_version,
517+ row.scope,
518+ about,
519+ row.audience_role,
520+ course,
521+ evidence,
522+ row.confidence,
523+ row.computed_at,
524+ row.expires_at,
525+ row.retain_until,
526+ )
527+ .execute(&mut *tx)
528+ .await?;
529+ written += 1;
530+ }
531+ Ok((written, rejected))
532+}
533+
534+/// The stored evidence object: the payload's own object with `limitation`
535+/// written into it, exactly as the service kept it. A payload whose `evidence`
536+/// is not an object cannot be merged and is refused.
537+fn merge_limitation(
538+ evidence: &JsonValue,
539+ limitation: Option<&str>,
540+) -> Result<JsonValue, AppError> {
541+ let mut object = evidence
542+ .as_object()
543+ .cloned()
544+ .ok_or(AppError::Validation(ValidationError::Invalid {
545+ field: "evidence",
546+ reason: "must be a JSON object",
547+ }))?;
548+ if let Some(limitation) = limitation {
549+ object.insert(
550+ "limitation".to_string(),
551+ JsonValue::String(limitation.to_string()),
552+ );
553+ }
554+ Ok(JsonValue::Object(object))
555+}
556+
557+/// Store a batch of question segments, replacing each question's dimension
558+/// split.
559+pub async fn write_segments(db: &Database, rows: Vec<SegmentRow>) -> Result<WriteReceipt, AppError> {
560+ check_batch("rows", &rows)?;
561+ let written = rows.len() as u64;
562+ tx_with_retry(db, false, async move |tx| write_segments_in(tx, &rows).await)
563+ .await
564+ .map_err(as_validation)?;
565+ Ok(WriteReceipt {
566+ written,
567+ rejected: 0,
568+ })
569+}
570+
571+/// The transaction body of [`write_segments`], a named fn rather than an async
572+/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
573+/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
574+async fn write_segments_in(tx: &mut sqlx::PgConnection, rows: &[SegmentRow]) -> Result<(), AppError> {
575+
576+ for row in rows {
577+ let question = parse_uuid("question", &row.question)?;
578+ let exam = parse_uuid("exam", &row.exam)?;
579+ let course = parse_uuid("course", &row.course)?;
580+ let subject = parse_uuid("subject", &row.subject)?;
581+ sqlx::query!(
582+ "INSERT INTO zeka_question_segment
583+ (question, exam, course, subject, bilissel_talep, dikkat_tuzagi, okuma_yuku,
584+ adim_sayisi, confidence_bilissel_talep, confidence_dikkat_tuzagi,
585+ confidence_okuma_yuku, confidence_adim_sayisi, confidence, trap_choice,
586+ rationale, model, prompt_version, variant, computed_at, retain_until)
587+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
588+ $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
589+ ON CONFLICT (question) DO UPDATE SET
590+ exam = EXCLUDED.exam, course = EXCLUDED.course, subject = EXCLUDED.subject,
591+ bilissel_talep = EXCLUDED.bilissel_talep,
592+ dikkat_tuzagi = EXCLUDED.dikkat_tuzagi,
593+ okuma_yuku = EXCLUDED.okuma_yuku,
594+ adim_sayisi = EXCLUDED.adim_sayisi,
595+ confidence_bilissel_talep = EXCLUDED.confidence_bilissel_talep,
596+ confidence_dikkat_tuzagi = EXCLUDED.confidence_dikkat_tuzagi,
597+ confidence_okuma_yuku = EXCLUDED.confidence_okuma_yuku,
598+ confidence_adim_sayisi = EXCLUDED.confidence_adim_sayisi,
599+ confidence = EXCLUDED.confidence, trap_choice = EXCLUDED.trap_choice,
600+ rationale = EXCLUDED.rationale, model = EXCLUDED.model,
601+ prompt_version = EXCLUDED.prompt_version, variant = EXCLUDED.variant,
602+ computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until",
603+ question,
604+ exam,
605+ course,
606+ subject,
607+ row.labels.bilissel_talep,
608+ row.labels.dikkat_tuzagi,
609+ row.labels.okuma_yuku,
610+ row.labels.adim_sayisi,
611+ row.confidences.bilissel_talep,
612+ row.confidences.dikkat_tuzagi,
613+ row.confidences.okuma_yuku,
614+ row.confidences.adim_sayisi,
615+ row.confidence,
616+ row.trap_choice,
617+ row.rationale,
618+ row.model,
619+ row.prompt_version,
620+ row.variant,
621+ row.computed_at,
622+ row.retain_until,
623+ )
624+ .execute(&mut *tx)
625+ .await?;
626+ // A dimension that moved between downstream and experimental (or
627+ // a rubric version that dropped one) must not leave its old row
628+ // behind.
629+ sqlx::query!(
630+ "DELETE FROM zeka_question_segment_dimension WHERE question = $1",
631+ question,
632+ )
633+ .execute(&mut *tx)
634+ .await?;
635+ let mut ord: i16 = 0;
636+ for (role, names) in [
637+ ("downstream", &row.downstream_dimensions),
638+ ("experimental", &row.experimental_dimensions),
639+ ] {
640+ for name in names {
641+ sqlx::query!(
642+ "INSERT INTO zeka_question_segment_dimension
643+ (question, dimension, role, ord)
644+ VALUES ($1, $2, $3, $4)",
645+ question,
646+ name,
647+ role,
648+ ord,
649+ )
650+ .execute(&mut *tx)
651+ .await?;
652+ ord += 1;
653+ }
654+ }
655+ }
656+ Ok(())
657+}
658+
659+/// Store a batch of student segment profiles.
660+pub async fn write_profiles(db: &Database, rows: Vec<ProfileRow>) -> Result<WriteReceipt, AppError> {
661+ check_batch("rows", &rows)?;
662+ let written = rows.len() as u64;
663+ tx_with_retry(db, false, async move |tx| write_profiles_in(tx, &rows).await)
664+ .await
665+ .map_err(as_validation)?;
666+ Ok(WriteReceipt {
667+ written,
668+ rejected: 0,
669+ })
670+}
671+
672+/// The transaction body of [`write_profiles`], a named fn rather than an async
673+/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
674+/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
675+async fn write_profiles_in(tx: &mut sqlx::PgConnection, rows: &[ProfileRow]) -> Result<(), AppError> {
676+
677+ for row in rows {
678+ let student = parse_uuid("student", &row.student)?;
679+ sqlx::query!(
680+ "INSERT INTO zeka_student_segment_profile
681+ (student, dimension, label, n_answers, n_correct, accuracy,
682+ overall_n_answers, overall_accuracy, contrast, confidence,
683+ computed_at, retain_until)
684+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
685+ ON CONFLICT (student, dimension, label) DO UPDATE SET
686+ n_answers = EXCLUDED.n_answers, n_correct = EXCLUDED.n_correct,
687+ accuracy = EXCLUDED.accuracy,
688+ overall_n_answers = EXCLUDED.overall_n_answers,
689+ overall_accuracy = EXCLUDED.overall_accuracy,
690+ contrast = EXCLUDED.contrast, confidence = EXCLUDED.confidence,
691+ computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until",
692+ student,
693+ row.dimension,
694+ row.label,
695+ row.n_answers,
696+ row.n_correct,
697+ row.accuracy,
698+ row.overall_n_answers,
699+ row.overall_accuracy,
700+ row.contrast,
701+ row.confidence,
702+ row.computed_at,
703+ row.retain_until,
704+ )
705+ .execute(&mut *tx)
706+ .await?;
707+ }
708+ Ok(())
709+}
710+
711+/// Store one run's ledger row, replacing the run's pending/failed children.
712+pub async fn write_run(db: &Database, run: RunRow) -> Result<WriteReceipt, AppError> {
713+ if !run_day_ok(&run.run_day) {
714+ return Err(AppError::Validation(ValidationError::Invalid {
715+ field: "run_day",
716+ reason: "must be YYYY-MM-DD",
717+ }));
718+ }
719+ let pending: Vec<Uuid> = run
720+ .pending_students
721+ .iter()
722+ .map(|id| parse_uuid("pending_students", id))
723+ .collect::<Result<_, _>>()?;
724+ tx_with_retry(db, false, async move |tx| write_run_in(tx, &run, &pending).await)
725+ .await
726+ .map_err(as_validation)?;
727+ Ok(WriteReceipt {
728+ written: 1,
729+ rejected: 0,
730+ })
731+}
732+
733+/// The transaction body of [`write_run`], a named fn rather than an async
734+/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
735+/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
736+async fn write_run_in(tx: &mut sqlx::PgConnection, run: &RunRow, pending: &[Uuid]) -> Result<(), AppError> {
737+
738+ sqlx::query!(
739+ "INSERT INTO zeka_run
740+ (run_day, started_at, finished_at, status, duration_ms, students_total,
741+ students_ok, students_failed, students_skipped, rows_written,
742+ budget_exceeded, budget_ms, retain_until)
743+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
744+ ON CONFLICT (run_day) DO UPDATE SET
745+ started_at = EXCLUDED.started_at, finished_at = EXCLUDED.finished_at,
746+ status = EXCLUDED.status, duration_ms = EXCLUDED.duration_ms,
747+ students_total = EXCLUDED.students_total, students_ok = EXCLUDED.students_ok,
748+ students_failed = EXCLUDED.students_failed,
749+ students_skipped = EXCLUDED.students_skipped,
750+ rows_written = EXCLUDED.rows_written,
751+ budget_exceeded = EXCLUDED.budget_exceeded, budget_ms = EXCLUDED.budget_ms,
752+ retain_until = EXCLUDED.retain_until",
753+ run.run_day,
754+ run.started_at,
755+ run.finished_at,
756+ run.status,
757+ run.duration_ms,
758+ run.students_total,
759+ run.students_ok,
760+ run.students_failed,
761+ run.students_skipped,
762+ run.rows_written,
763+ run.budget_exceeded,
764+ run.budget_ms,
765+ run.retain_until,
766+ )
767+ .execute(&mut *tx)
768+ .await?;
769+ sqlx::query!("DELETE FROM zeka_run_pending WHERE run = $1", run.run_day)
770+ .execute(&mut *tx)
771+ .await?;
772+ sqlx::query!(
773+ "DELETE FROM zeka_run_failed_module WHERE run = $1",
774+ run.run_day
775+ )
776+ .execute(&mut *tx)
777+ .await?;
778+ for (ord, student) in pending.iter().enumerate() {
779+ sqlx::query!(
780+ "INSERT INTO zeka_run_pending (run, student, ord) VALUES ($1, $2, $3)",
781+ run.run_day,
782+ student,
783+ ord as i32,
784+ )
785+ .execute(&mut *tx)
786+ .await?;
787+ }
788+ for (ord, module) in run.failed_modules.iter().enumerate() {
789+ sqlx::query!(
790+ "INSERT INTO zeka_run_failed_module (run, module, ord) VALUES ($1, $2, $3)",
791+ run.run_day,
792+ module,
793+ ord as i16,
794+ )
795+ .execute(&mut *tx)
796+ .await?;
797+ }
798+ Ok(())
799+}
800+
801+// ---- reads -----------------------------------------------------------------
802+
803+/// The freshest run's pending students, in the order the run recorded them.
804+///
805+/// Refused rather than clipped past [`MAX_INSIGHT_PENDING_STUDENTS`]: the
806+/// service resumes its next run from this list, so a shortened one would drop
807+/// students silently. The read asks for one row past the ceiling so the
808+/// refusal never has to materialize the whole list.
809+pub async fn last_pending(db: &Database) -> Result<PendingList, AppError> {
810+ let ceiling = MAX_INSIGHT_PENDING_STUDENTS as i64;
811+ let rows = sqlx::query_scalar!(
812+ "SELECT p.student FROM zeka_run_pending p
813+ JOIN zeka_run r ON r.run_day = p.run
814+ WHERE r.run_day = (SELECT run_day FROM zeka_run
815+ ORDER BY started_at DESC, run_day DESC LIMIT 1)
816+ ORDER BY p.ord
817+ LIMIT $1",
818+ ceiling + 1,
819+ )
820+ .fetch_all(db)
821+ .await?;
822+ if rows.len() > MAX_INSIGHT_PENDING_STUDENTS {
823+ return Err(AppError::PayloadTooLarge(format!(
824+ "students: the freshest run left more than {MAX_INSIGHT_PENDING_STUDENTS} students pending"
825+ )));
826+ }
827+ Ok(PendingList {
828+ students: rows.iter().map(|id| id.to_string()).collect(),
829+ })
830+}
831+
832+/// The deployment's active schools, by slug — the one read that is not
833+/// scoped to a school, because it is how a shared AI fleet learns which
834+/// schools exist.
835+pub async fn active_schools(control: &Database) -> Result<SchoolDirectory, AppError> {
836+ let schools = sqlx::query_scalar!(
837+ "SELECT slug FROM school WHERE status = 'active' ORDER BY slug"
838+ )
839+ .fetch_all(control)
840+ .await?;
841+ Ok(SchoolDirectory { schools })
842+}
843+
844+// ---- retention -------------------------------------------------------------
845+
846+/// The nine tables a sweep walks, children before their parents: the foreign
847+/// keys are `ON DELETE NO ACTION`, so a parent cannot go while a child row
848+/// still names it.
849+const SWEEP_CHILDREN: &[(&str, &str, &str)] = &[
850+ ("zeka_attention_item", "zeka_student_summary", "student"),
851+ ("zeka_question_segment_dimension", "zeka_question_segment", "question"),
852+ ("zeka_run_pending", "zeka_run", "run"),
853+ ("zeka_run_failed_module", "zeka_run", "run"),
854+];
855+
856+/// The tables that carry their own `retain_until`.
857+const SWEEP_PARENTS: &[&str] = &[
858+ "zeka_student_summary",
859+ "zeka_recommendation",
860+ "zeka_run",
861+ "zeka_question_segment",
862+ "zeka_student_segment_profile",
863+];
864+
865+/// Delete every row whose retention window has closed. `now_ms` is the
866+/// backend's own clock — one clock decides expiry, never the caller's.
867+///
868+/// One table at a time, each in its own statement, and a table whose delete
869+/// fails is reported `false` rather than aborting the rest: a sweep is
870+/// housekeeping, and losing the whole night's cleanup because one table is
871+/// locked would leave every other table's expired rows in place. The caller
872+/// reads the verdict per table, exactly as the service's own sweep did.
873+pub async fn sweep(db: &Database, now_ms: i64) -> Result<TableVerdicts, AppError> {
874+ let mut tables = BTreeMap::new();
875+ for (child, parent, key) in SWEEP_CHILDREN {
876+ let parent_key = if *parent == "zeka_run" { "run_day" } else { *key };
877+ let sql = format!(
878+ "DELETE FROM {child} WHERE {key} IN \
879+ (SELECT {parent_key} FROM {parent} WHERE retain_until < $1)"
880+ );
881+ tables.insert(
882+ (*child).to_string(),
883+ run_sweep_statement(db, &sql, now_ms).await,
884+ );
885+ }
886+ for table in SWEEP_PARENTS {
887+ let sql = format!("DELETE FROM {table} WHERE retain_until < $1");
888+ tables.insert((*table).to_string(), run_sweep_statement(db, &sql, now_ms).await);
889+ }
890+ Ok(TableVerdicts { tables })
891+}
892+
893+/// The table names come from [`SWEEP_CHILDREN`]/[`SWEEP_PARENTS`], never from
894+/// a caller — the only dynamic SQL in this module, and the reason
895+/// [`AssertSqlSafe`] is licensed here.
896+async fn run_sweep_statement(db: &Database, sql: &str, now_ms: i64) -> bool {
897+ sqlx::query(AssertSqlSafe(sql.to_string()))
898+ .bind(now_ms)
899+ .execute(db)
900+ .await
901+ .is_ok()
902+}
903+
904+/// Delete the derived rows of everyone who is no longer on the roster. One
905+/// transaction: a purge is a decision about a cohort, not a per-row repair.
906+///
907+/// The empty list is **refused**, never obeyed: an empty roster is almost
908+/// always a fetch that failed, and reading it as "nobody is enrolled any
909+/// more" would delete every student's derived data in one call.
910+pub async fn purge_departed(
911+ db: &Database,
912+ students: Vec<String>,
913+) -> Result<TableVerdicts, AppError> {
914+ if students.is_empty() {
915+ return Err(AppError::Validation(ValidationError::Empty("students")));
916+ }
917+ if students.len() > MAX_INSIGHT_PURGE_STUDENTS {
918+ return Err(AppError::PayloadTooLarge(format!(
919+ "students: {} ids is over the ceiling of {MAX_INSIGHT_PURGE_STUDENTS} per call",
920+ students.len()
921+ )));
922+ }
923+ let active: Vec<Uuid> = students
924+ .iter()
925+ .map(|id| parse_uuid("students", id))
926+ .collect::<Result<_, _>>()?;
927+ tx_with_retry(db, false, async move |tx| purge_departed_in(tx, &active).await)
928+ .await
929+ .map_err(as_validation)?;
930+
931+ // One transaction, so the verdicts move together: every table succeeded
932+ // or the call was refused above.
933+ let tables = [
934+ "zeka_attention_item",
935+ "zeka_student_summary",
936+ "zeka_student_segment_profile",
937+ "zeka_recommendation",
938+ "zeka_run_pending",
939+ ]
940+ .into_iter()
941+ .map(|table| (table.to_string(), true))
942+ .collect();
943+ Ok(TableVerdicts { tables })
944+}
945+
946+/// The transaction body of [`purge_departed`], a named fn rather than an async
947+/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
948+/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
949+async fn purge_departed_in(tx: &mut sqlx::PgConnection, active: &[Uuid]) -> Result<(), AppError> {
950+
951+ // Children first (they reference the summary), then the parents.
952+ sqlx::query!(
953+ "DELETE FROM zeka_attention_item WHERE student <> ALL($1)",
954+ active,
955+ )
956+ .execute(&mut *tx)
957+ .await?;
958+ sqlx::query!(
959+ "DELETE FROM zeka_student_summary WHERE student <> ALL($1)",
960+ active,
961+ )
962+ .execute(&mut *tx)
963+ .await?;
964+ sqlx::query!(
965+ "DELETE FROM zeka_student_segment_profile WHERE student <> ALL($1)",
966+ active,
967+ )
968+ .execute(&mut *tx)
969+ .await?;
970+ // Cards about a departed student go; school-wide cards (`about` is
971+ // NULL) are addressed to someone still enrolled and stay.
972+ sqlx::query!(
973+ "DELETE FROM zeka_recommendation
974+ WHERE about IS NOT NULL AND about <> ALL($1)",
975+ active,
976+ )
977+ .execute(&mut *tx)
978+ .await?;
979+ sqlx::query!(
980+ "DELETE FROM zeka_run_pending WHERE student <> ALL($1)",
981+ active,
982+ )
983+ .execute(&mut *tx)
984+ .await?;
985+ Ok(())
986+}
src/db/mod.rsmodified+2 -0
@@ -40,6 +40,7 @@ pub mod homework;
40 pub mod homework_file;40 pub mod homework_file;
41 pub mod homework_result;41 pub mod homework_result;
42 pub mod homework_submission;42 pub mod homework_submission;
43+pub mod insight;
43 pub mod karne;44 pub mod karne;
44 pub mod meal_attendance;45 pub mod meal_attendance;
45 pub mod meal_booking;46 pub mod meal_booking;
@@ -53,6 +54,7 @@ pub mod page;
53 pub mod parent_link;54 pub mod parent_link;
54 pub mod payment_ledger;55 pub mod payment_ledger;
55 pub mod person;56 pub mod person;
57+pub mod podcast_job;
56 pub mod pomodoro;58 pub mod pomodoro;
57 pub mod pool_question;59 pub mod pool_question;
58 pub mod pool_question_image;60 pub mod pool_question_image;
src/lib.rsmodified+6 -2
@@ -57,8 +57,8 @@ use crate::web::module_gate::gate;
57 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),57 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),
58 (name = "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"),58 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
59 (name = "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."),59 (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sınıf, ders)` pairs, derived on each request from their live memberships — their şubeler' instances, a linked parent's children, and the school-wide club/etüt memberships they hold (which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it."),
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."),60+ (name = "insights", description = "ZEKA's computed student insights. The `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot, but it does **not** touch a school database: the backend owns every statement against the `zeka_*` tables, and the service calls the backend by name (`insight.*` capabilities on a client-initiated stream — see `src/ai/insight.rs`) to have its computed rows written and read back. So this nest reads what the service computed and asks it to compute on demand, and its write doors are the same operations the bridge serves: `POST /insights/summaries`, `/recommendations`, `/segments`, `/profiles` and `/runs` store one batch each (manager+, one call one transaction, rows about students school-wide), `GET /insights/pending` is the students the freshest run left pending, and `POST /insights/sweep` / `POST /insights/purge` are retention and graduation housekeeping — all scoped to the caller's own school by the nest's extractors, and none of them takes a school, a database or a query in its body. `GET /insights/schools` is the exception and is not this nest's usual principal: the active-school directory names every customer, so it is mounted on the **builder** principal outside the school gate (a school session answers `401`), exactly like the vendor surface's `GET /schools`. `GET /insights/me` is the caller's own view: a student's summary, their own recommendation cards and their segment profile — and **never** the attention list about themselves, which is a teacher's tool and is not returned to a student or to a linked parent. `GET /insights/students/{id}` is the observer's view of one student — teacher+ narrowed to the students they actually reach through a shared class×course instance, or a parent holding a live link — adding the attention list and the caller's own cards about that student; anyone else reads `404`, never `403`. `POST /insights/students/{id}` and `POST /insights/refresh` (manager+) queue a recompute through the bridge and answer `202` — the compute lands in the service's own rows, so a client polls the read routes; `GET /insights/runs` (manager+) is the run ledger, newest first. Both dispatch doors answer `503` when no service offers the capability, and nothing is queued. Expired and dismissed cards are filtered out of every card read, segment rows below 30 answers (`confidence: none`) are filtered out of every profile read, and a card's `about` is never returned to a student caller."),
61- (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — the backend owns authentication and the HTTP surface, the podcast service owns the job. `POST /podcast/jobs` (`{source_id, format?}`) starts one and answers `202` with the service's `{job_id, state, eta_secs}` receipt; `GET /podcast/jobs/{id}` polls its `{state, stage, progress, error_code}`, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, script_id, audio_ids, script_ids, format}` (`409` while it is still running), and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`). Each door refuses `503` when no connected service declares its capability, and each relays the service's own refusal code (`not_found`, `not_ready`, `busy`, `llm_unavailable`, …) with a matching status. The produced audio never crosses the bridge: `audio_id` is a path relative to the school's own output directory under `FILES_PATH` (the service's `PODCAST_OUTPUT_ROOT` points there), and `GET /podcast/audio?path=…` streams those bytes — refusing absolute paths, `.`/`..` segments, backslashes and symlinks that resolve outside the school's directory with `400`, so one school can never read another's episode even knowing its path. **None of these doors writes a row**: the job record and its files live in the service. Gated by the school's `chatbot` module (the AI package's only module), like `/chatbot` and `/rag`; any authenticated member of the school may call them, and the school wall is the bridge's (`hab/2` stamps the caller's school onto every request; the bridge does **not** verify the echo on replies — answers are correlated by frame id alone). What the backend cannot judge is *which* sources a caller may narrate — `source_id` is the service's own record id, and no backend query can say what it names."),61+ (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — and the **backend owns the job**, not just the HTTP surface. `POST /podcast/jobs` (`{source_id, format?}`) mints the job id, writes the row, then dispatches `podcast.submit` to the service and answers `202` with `{job_id, state, eta_secs}`; `GET /podcast/jobs/{id}` polls the backend's own row `{state, stage, progress, error_code}` with no service round trip, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, format}` (`409` while it is still running), `GET /podcast/jobs/{id}/audio` streams the episode the service uploaded into this school's own blob directory, and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`; a terminal job answers without the service). The service reports every transition back through the `podcast.report` capability and uploads the finished mp3 — so status, result and audio keep answering while the service is down or restarted, and a job nobody is updating reads as failed/interrupted after an ETA-scaled window. Submit and cancel refuse `503` when no worker is connected; none of the three read doors needs one (404 for an unknown or foreign job, 410 past the retention window, 409 before the job is done or when its blob is missing from this host)."),
62 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),62 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
63 (name = "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"),63 (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"),
64 (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"),64 (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"),
@@ -158,6 +158,10 @@ pub fn build_router(state: AppState) -> Router {
158 .nest("/ai", web::ai::routes())158 .nest("/ai", web::ai::routes())
159 .nest("/auth", web::auth::routes(&state))159 .nest("/auth", web::auth::routes(&state))
160 .merge(web::builder::routes(&state))160 .merge(web::builder::routes(&state))
161+ // The insights directory is the one route of that nest a school
162+ // session may not reach (it names every customer), so it is mounted
163+ // here on the builder principal instead of inside the gate below.
164+ .merge(web::insights::school_directory_routes())
161 .nest(165 .nest(
162 "/chatbot",166 "/chatbot",
163 gate(web::chatbot::routes(), &state, Module::Chatbot),167 gate(web::chatbot::routes(), &state, Module::Chatbot),
src/web/insights.rsmodified+314 -10
@@ -1,11 +1,15 @@
1-//! The insight nest: the read surface over ZEKA's own tables, plus the two1+//! The insight nest: the read surface over ZEKA's tables, the doors that ask
2-//! doors that ask ZEKA to compute.2+//! ZEKA to compute, and the storage doors its rows are written through.
3 //!3 //!
4-//! ZEKA (`hezarfen_zeka`) is an AI service that dials in over the QUIC bridge4+//! 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_*`5+//! It **does not touch a school database** — no AI service on this deployment
6-//! tables created by the school migrator. The backend never composes those6+//! does — so the `zeka_*` tables, created by the school migrator, are written
7-//! rows; it reads them here and, on request, asks the service to compute7+//! and read only by this process. Two surfaces, one implementation each: the
8-//! (the dispatch contract lives in [`crate::ai::insight`]).8+//! service calls the backend over the bridge (`insight.summary.upsert` and
9+//! the rest of the family — the wire contract is [`crate::ai::insight`], the
10+//! statements are [`crate::db::insight`]), and the same operations are
11+//! mounted here as HTTP doors for tooling. The backend never composes an
12+//! insight row; it stores what the service computed and hands it back.
9 //!13 //!
10 //! Reading is authorized the way every per-student report in this API is:14 //! Reading is authorized the way every per-student report in this API is:
11 //! [`service::parent_link::ensure_can_observe`] decides whether the caller15 //! [`service::parent_link::ensure_can_observe`] decides whether the caller
@@ -49,9 +53,14 @@ use utoipa::ToSchema;
49 use utoipa_axum::router::OpenApiRouter;53 use utoipa_axum::router::OpenApiRouter;
50 use utoipa_axum::routes;54 use utoipa_axum::routes;
51 55
52-use crate::ai::insight::{self, RefreshRequest, StudentRequest};56+use crate::ai::insight::{
57+ self, PendingList, ProfileWriteRequest, PurgeRequest, RecommendationWriteRequest,
58+ RefreshRequest, RunWriteRequest, SchoolDirectory, SegmentWriteRequest, StudentRequest,
59+ SummaryWriteRequest, TableVerdicts, WriteReceipt,
60+};
53 use crate::constant::{AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY};61 use crate::constant::{AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY};
54 use crate::database::Database;62 use crate::database::Database;
63+use crate::db;
55 use crate::domain::class_group::ClassGroupId;64 use crate::domain::class_group::ClassGroupId;
56 use crate::domain::course::CourseId;65 use crate::domain::course::CourseId;
57 use crate::domain::role::Role;66 use crate::domain::role::Role;
@@ -63,7 +72,7 @@ use crate::state::AppState;
63 use crate::tenant::ResolvedTenant;72 use crate::tenant::ResolvedTenant;
64 use crate::web::tenant_state::State;73 use crate::web::tenant_state::State;
65 74
66-use super::{CurrentUser, Page, PageParams, RequireManager, ai_unavailable, paginate};75+use super::{CurrentUser, Page, PageParams, RequireBuilder, RequireManager, ai_unavailable, paginate};
67 76
68 /// The single `now` every card read is filtered against. ZEKA stores unix77 /// The single `now` every card read is filtered against. ZEKA stores unix
69 /// milliseconds, so "expired" is a comparison, not a projection.78 /// milliseconds, so "expired" is a comparison, not a projection.
@@ -76,7 +85,28 @@ pub fn routes() -> OpenApiRouter<AppState> {
76 .routes(routes!(refresh))85 .routes(routes!(refresh))
77 .routes(routes!(my_insight))86 .routes(routes!(my_insight))
78 .routes(routes!(student_insight, compute_student))87 .routes(routes!(student_insight, compute_student))
79- .routes(routes!(list_runs))88+ .routes(routes!(list_runs, write_run))
89+ .routes(routes!(write_summaries))
90+ .routes(routes!(write_recommendations))
91+ .routes(routes!(write_segments))
92+ .routes(routes!(write_profiles))
93+ .routes(routes!(pending_students))
94+ .routes(routes!(sweep_retention))
95+ .routes(routes!(purge_departed))
96+}
97+
98+/// The one door of this nest that is **not** school-scoped: the deployment's
99+/// active-school directory.
100+///
101+/// ZEKA's storage operations are all scoped to the school a session belongs
102+/// to, and so are these doors — but the directory is not: it names every
103+/// customer. A school session must therefore never reach it, which is why
104+/// this route is mounted *outside* the school-scoped gate, on the builder
105+/// principal (the deployment operator), exactly like the vendor surface's own
106+/// `GET /schools`. A school cookie answers `401` here, as it does everywhere
107+/// the builder principal is required.
108+pub fn school_directory_routes() -> OpenApiRouter<AppState> {
109+ OpenApiRouter::new().routes(routes!(active_schools))
80 }110 }
81 111
82 // ---- the compute doors -----------------------------------------------------112 // ---- the compute doors -----------------------------------------------------
@@ -244,6 +274,280 @@ fn accepted() -> Response {
244 .into_response()274 .into_response()
245 }275 }
246 276
277+// ---- the storage doors -----------------------------------------------------
278+//
279+// ZEKA's own tables are written and read by the backend, never by the service
280+// (`crate::db::insight` holds the statements, `src/ai/insight.rs` the bridge
281+// contract). These are the same nine operations over HTTP — one service
282+// function, two surfaces — so a deployment's tooling can seed, inspect and
283+// maintain what the service computed without holding a bridge connection.
284+//
285+// Manager+ on all of them: every one reads or writes rows about students
286+// school-wide, which is the same floor `GET /insights/runs` and the refresh
287+// door carry. The school is the caller's own, resolved by the nest's own
288+// extractors; no door here takes a school, a database or a query in its body.
289+
290+/// Store a batch of ZEKA's student summaries (and their attention items).
291+///
292+/// This is what the AI service calls over the bridge as
293+/// `insight.summary.upsert`. One call is one batch and one transaction: the
294+/// batch lands whole or not at all, so a caller that retries cannot
295+/// half-apply it. Each student's attention items are **replaced**, never
296+/// merged — a fact the service stopped producing must not stay on screen.
297+/// At most [`MAX_INSIGHT_BATCH_ROWS`](crate::constant::MAX_INSIGHT_BATCH_ROWS)
298+/// rows per call.
299+#[utoipa::path(
300+ post,
301+ path = "/summaries",
302+ tag = "insights",
303+ security(("session_cookie" = [])),
304+ request_body = SummaryWriteRequest,
305+ responses(
306+ (status = 200, description = "The rows were written", body = WriteReceipt),
307+ (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse),
308+ (status = 401, description = "Not authenticated", body = ErrorResponse),
309+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
310+ (status = 413, description = "More rows than one call may carry", body = ErrorResponse),
311+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
312+ ),
313+)]
314+async fn write_summaries(
315+ State(st): State<AppState>,
316+ RequireManager(_user): RequireManager,
317+ Json(body): Json<SummaryWriteRequest>,
318+) -> Result<Json<WriteReceipt>, AppError> {
319+ Ok(Json(db::insight::write_summaries(&st.db, body.rows).await?))
320+}
321+
322+/// Store a batch of ZEKA's recommendation cards.
323+///
324+/// The bridge capability is `insight.recommendation.upsert`. The backend
325+/// mints each row's id. A row whose evidence carries nothing but a
326+/// `limitation` is **not written** and is counted `rejected` in the receipt —
327+/// the service's own rule, applied where the write happens instead of being
328+/// trusted to the writer.
329+#[utoipa::path(
330+ post,
331+ path = "/recommendations",
332+ tag = "insights",
333+ security(("session_cookie" = [])),
334+ request_body = RecommendationWriteRequest,
335+ responses(
336+ (status = 200, description = "The rows were written; `rejected` counts the cards the evidence rule kept out", body = WriteReceipt),
337+ (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse),
338+ (status = 401, description = "Not authenticated", body = ErrorResponse),
339+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
340+ (status = 413, description = "More rows than one call may carry", body = ErrorResponse),
341+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
342+ ),
343+)]
344+async fn write_recommendations(
345+ State(st): State<AppState>,
346+ RequireManager(_user): RequireManager,
347+ Json(body): Json<RecommendationWriteRequest>,
348+) -> Result<Json<WriteReceipt>, AppError> {
349+ Ok(Json(
350+ db::insight::write_recommendations(&st.db, body.rows).await?,
351+ ))
352+}
353+
354+/// Store a batch of ZEKA's question-segment labels (and each question's
355+/// dimension split).
356+///
357+/// The bridge capability is `insight.segment.upsert`; the dimension rows are
358+/// replaced with the payload, like the attention items above.
359+#[utoipa::path(
360+ post,
361+ path = "/segments",
362+ tag = "insights",
363+ security(("session_cookie" = [])),
364+ request_body = SegmentWriteRequest,
365+ responses(
366+ (status = 200, description = "The rows were written", body = WriteReceipt),
367+ (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse),
368+ (status = 401, description = "Not authenticated", body = ErrorResponse),
369+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
370+ (status = 413, description = "More rows than one call may carry", body = ErrorResponse),
371+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
372+ ),
373+)]
374+async fn write_segments(
375+ State(st): State<AppState>,
376+ RequireManager(_user): RequireManager,
377+ Json(body): Json<SegmentWriteRequest>,
378+) -> Result<Json<WriteReceipt>, AppError> {
379+ Ok(Json(db::insight::write_segments(&st.db, body.rows).await?))
380+}
381+
382+/// Store a batch of ZEKA's student segment profiles.
383+///
384+/// The bridge capability is `insight.profile.upsert`. `contrast` is the field
385+/// the service's rules fire on — the raw `accuracy` mostly measures a
386+/// student's general level and is stored for the evidence panel only.
387+#[utoipa::path(
388+ post,
389+ path = "/profiles",
390+ tag = "insights",
391+ security(("session_cookie" = [])),
392+ request_body = ProfileWriteRequest,
393+ responses(
394+ (status = 200, description = "The rows were written", body = WriteReceipt),
395+ (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse),
396+ (status = 401, description = "Not authenticated", body = ErrorResponse),
397+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
398+ (status = 413, description = "More rows than one call may carry", body = ErrorResponse),
399+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
400+ ),
401+)]
402+async fn write_profiles(
403+ State(st): State<AppState>,
404+ RequireManager(_user): RequireManager,
405+ Json(body): Json<ProfileWriteRequest>,
406+) -> Result<Json<WriteReceipt>, AppError> {
407+ Ok(Json(db::insight::write_profiles(&st.db, body.rows).await?))
408+}
409+
410+/// Store one compute run's ledger row (with its pending students and failed
411+/// modules, both replaced).
412+///
413+/// The bridge capability is `insight.run.upsert`; the run is keyed by
414+/// `run_day` (`YYYY-MM-DD`), so a re-run of the same night overwrites rather
415+/// than duplicating. `GET /insights/runs` reads the ledger back.
416+#[utoipa::path(
417+ post,
418+ path = "/runs",
419+ tag = "insights",
420+ security(("session_cookie" = [])),
421+ request_body = RunWriteRequest,
422+ responses(
423+ (status = 200, description = "The run's ledger row was written", body = WriteReceipt),
424+ (status = 400, description = "The payload does not fit the operation: `run_day` is not `YYYY-MM-DD`, or a referenced row is not in this school", body = ErrorResponse),
425+ (status = 401, description = "Not authenticated", body = ErrorResponse),
426+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
427+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
428+ ),
429+)]
430+async fn write_run(
431+ State(st): State<AppState>,
432+ RequireManager(_user): RequireManager,
433+ Json(body): Json<RunWriteRequest>,
434+) -> Result<Json<WriteReceipt>, AppError> {
435+ Ok(Json(db::insight::write_run(&st.db, body.run).await?))
436+}
437+
438+/// The students the freshest compute run left pending — where the next run
439+/// starts.
440+///
441+/// Manager+ only, like `GET /insights/runs`: `pending_students` is a list of
442+/// people, and this is the same list unpaged. The bridge capability is
443+/// `insight.pending.list`; the list is answered whole or refused past
444+/// [`MAX_INSIGHT_PENDING_STUDENTS`](crate::constant::MAX_INSIGHT_PENDING_STUDENTS),
445+/// never clipped, because the service resumes its next run from it.
446+#[utoipa::path(
447+ get,
448+ path = "/pending",
449+ tag = "insights",
450+ security(("session_cookie" = [])),
451+ responses(
452+ (status = 200, description = "The freshest run's pending students, in the run's own order", body = PendingList),
453+ (status = 401, description = "Not authenticated", body = ErrorResponse),
454+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
455+ (status = 413, description = "More pending students than one answer may carry", body = ErrorResponse),
456+ ),
457+)]
458+async fn pending_students(
459+ State(st): State<AppState>,
460+ RequireManager(_user): RequireManager,
461+) -> Result<Json<PendingList>, AppError> {
462+ Ok(Json(db::insight::last_pending(&st.db).await?))
463+}
464+
465+/// Delete every `zeka_*` row whose retention window has closed.
466+///
467+/// The bridge capability is `insight.retention.sweep`. Children go before
468+/// their parents (the foreign keys are `ON DELETE NO ACTION`), the backend's
469+/// own clock decides expiry, and each table answers its own verdict — a table
470+/// that could not be swept is reported `false` while the rest proceed, since
471+/// housekeeping must not lose a whole run over one locked table.
472+#[utoipa::path(
473+ post,
474+ path = "/sweep",
475+ tag = "insights",
476+ security(("session_cookie" = [])),
477+ responses(
478+ (status = 200, description = "One verdict per table: whether its expired rows were deleted", body = TableVerdicts),
479+ (status = 401, description = "Not authenticated", body = ErrorResponse),
480+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
481+ ),
482+)]
483+async fn sweep_retention(
484+ State(st): State<AppState>,
485+ RequireManager(_user): RequireManager,
486+) -> Result<Json<TableVerdicts>, AppError> {
487+ let now_ms = crate::domain::timestamp::Timestamp::now().as_millis();
488+ Ok(Json(db::insight::sweep(&st.db, now_ms).await?))
489+}
490+
491+/// Delete the derived rows of every student who is no longer on the roster.
492+///
493+/// The bridge capability is `insight.departed.purge`; `students` is the
494+/// **active** roster, and every student not named loses their summaries,
495+/// profiles, attention items, cards about them, and pending-run entries. One
496+/// transaction, so the verdicts move together. An empty list is refused: an
497+/// empty roster is a fetch that failed, and obeying it would delete the whole
498+/// school's derived data.
499+#[utoipa::path(
500+ post,
501+ path = "/purge",
502+ tag = "insights",
503+ security(("session_cookie" = [])),
504+ request_body = PurgeRequest,
505+ responses(
506+ (status = 200, description = "One verdict per table: whether the departed students' rows were deleted", body = TableVerdicts),
507+ (status = 400, description = "The payload does not fit the operation: the roster is empty", body = ErrorResponse),
508+ (status = 401, description = "Not authenticated", body = ErrorResponse),
509+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
510+ (status = 413, description = "More students than one call may name", body = ErrorResponse),
511+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
512+ ),
513+)]
514+async fn purge_departed(
515+ State(st): State<AppState>,
516+ RequireManager(_user): RequireManager,
517+ Json(body): Json<PurgeRequest>,
518+) -> Result<Json<TableVerdicts>, AppError> {
519+ Ok(Json(
520+ db::insight::purge_departed(&st.db, body.students).await?,
521+ ))
522+}
523+
524+/// The deployment's active schools, by slug — the directory a shared AI fleet
525+/// schedules over.
526+///
527+/// This is the one operation of the family that is not school-scoped, and the
528+/// one door of this nest that is not a school's: it names every customer, so
529+/// it runs on the **builder** principal (the deployment operator), mounted
530+/// outside the school gate exactly like the vendor surface's `GET /schools`.
531+/// A school session gets `401` here. The bridge capability is
532+/// `insight.schools.list`, which is the service's own deployment-scoped call:
533+/// the same function, two surfaces, and a school-scoped caller on neither.
534+#[utoipa::path(
535+ get,
536+ path = "/insights/schools",
537+ tag = "insights",
538+ security(("session_cookie" = [])),
539+ responses(
540+ (status = 200, description = "Every active school on this deployment, by slug", body = SchoolDirectory),
541+ (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
542+ ),
543+)]
544+async fn active_schools(
545+ axum::extract::State(st): axum::extract::State<AppState>,
546+ RequireBuilder(_builder): RequireBuilder,
547+) -> Result<Json<SchoolDirectory>, AppError> {
548+ Ok(Json(db::insight::active_schools(st.tenants.control()).await?))
549+}
550+
247 /// Canonicalize the ids a refresh body names — through the same parser every551 /// 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 spelling552 /// 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 uuid553 /// this backend itself would never produce. Anything that parses as no uuid
tests/ai_bridge.rsmodified+451 -0
@@ -3501,3 +3501,454 @@ async fn no_insight_refresh_worker_means_503_and_nothing_is_dispatched() {
3501 .await;3501 .await;
3502 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);3502 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
3503 }3503 }
3504+
3505+// ------------------------------------------- the backend-served capabilities --
3506+//
3507+// The other direction: a service calling the *backend*. ZEKA's storage
3508+// surface is nine `insight.*` operations the backend executes against the
3509+// school the frame names — no AI service holds a school database credential
3510+// on this deployment, so these calls are the only way its rows are written.
3511+// Everything below rides a real client-initiated QUIC stream, like the api
3512+// read it is shaped after.
3513+
3514+use hezarfen_backend::ai::protocol::{CapabilityRequest, CapabilityResponse};
3515+use hezarfen_backend::constant::{
3516+ AI_INSIGHT_PENDING_LIST_CAPABILITY, AI_INSIGHT_RETENTION_SWEEP_CAPABILITY,
3517+ AI_INSIGHT_RUN_UPSERT_CAPABILITY, AI_INSIGHT_SCHOOLS_LIST_CAPABILITY,
3518+ AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
3519+};
3520+use hezarfen_backend::domain::user::{Password, Username};
3521+use hezarfen_backend::service::builder;
3522+use hezarfen_backend::tenant::SchoolId;
3523+
3524+/// One capability call: a fresh client-initiated stream, one frame out, one
3525+/// back, stream dropped — the same lifecycle as `api_read` above.
3526+async fn capability_call(
3527+ conn: &quinn::Connection,
3528+ request: CapabilityRequest,
3529+) -> CapabilityResponse {
3530+ let (mut send, mut recv) = conn.open_bi().await.expect("capability stream");
3531+ write_frame(&mut send, &request).await.expect("write CapabilityRequest");
3532+ let _ = send.finish();
3533+ read_frame(&mut recv).await.expect("read CapabilityResponse")
3534+}
3535+
3536+fn insight_call(capability: &str, school: &str, payload: Value) -> CapabilityRequest {
3537+ CapabilityRequest {
3538+ id: format!("trace-{capability}"),
3539+ school: school.to_string(),
3540+ capability: capability.to_string(),
3541+ payload,
3542+ }
3543+}
3544+
3545+fn ok_capability(answer: CapabilityResponse) -> Value {
3546+ match answer {
3547+ CapabilityResponse::Ok { payload, .. } => payload,
3548+ CapabilityResponse::Err { code, message, .. } => {
3549+ panic!("expected the backend to run the operation, got {code}: {message}")
3550+ }
3551+ }
3552+}
3553+
3554+fn refused_capability(answer: CapabilityResponse) -> (String, String) {
3555+ match answer {
3556+ CapabilityResponse::Err { code, message, .. } => (code, message),
3557+ CapabilityResponse::Ok { payload, .. } => {
3558+ panic!("expected a refusal, got {payload}")
3559+ }
3560+ }
3561+}
3562+
3563+/// A summary row as the service sends it, for one student.
3564+fn summary_payload(student: &str, retain_until: i64) -> Value {
3565+ json!({ "rows": [{
3566+ "student": student,
3567+ "marks": { "ortalama": 72 },
3568+ "confidence": "stable",
3569+ "computed_at": 1_700_000_000_000i64,
3570+ "retain_until": retain_until,
3571+ "attention": [{
3572+ "trigger": "not_egilimi_dusuyor",
3573+ "fact": "Son üç sınavda ortalama 12 puan düştü.",
3574+ "window_from": 1_690_000_000_000i64,
3575+ "window_to": 1_700_000_000_000i64,
3576+ "evidence": { "delta": -12 },
3577+ }],
3578+ }] })
3579+}
3580+
3581+/// The demo school, an app with the bridge armed, a manager cookie and one
3582+/// student's id — the fixture every test below needs.
3583+async fn insight_fixture(
3584+ bridge: &AiBridge,
3585+) -> (FakeService, Router, hezarfen_backend::database::Database, String, String) {
3586+ let service =
3587+ connect_service(bridge, hello("zeka", &["insight.refresh"]), Behaviour::Echo).await;
3588+ await_workers(bridge, 1).await;
3589+ let (app, db) = common::app_with_ai(Some(bridge.clone())).await;
3590+ let mudur = common::login_as(&app, &db, "mudur", "manager").await;
3591+ let ayse = common::login_as(&app, &db, "ayse", "student").await;
3592+ let student = common::me_id(&app, &ayse).await;
3593+ (service, app, db, mudur, student)
3594+}
3595+
3596+#[tokio::test]
3597+async fn a_capability_call_writes_the_row_the_schools_own_read_door_serves() {
3598+ let bridge = bridge().await;
3599+ let (service, app, _db, mudur, student) = insight_fixture(&bridge).await;
3600+
3601+ let answer = capability_call(
3602+ &service.conn,
3603+ insight_call(
3604+ AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
3605+ DEMO_SLUG,
3606+ summary_payload(&student, 1_800_000_000_000i64),
3607+ ),
3608+ )
3609+ .await;
3610+ let CapabilityResponse::Ok { payload, school, id } = answer else {
3611+ panic!("expected the write to land: {answer:?}");
3612+ };
3613+ assert_eq!(id, format!("trace-{AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY}"));
3614+ assert_eq!(school, DEMO_SLUG, "the answer echoes the school the frame named");
3615+ assert_eq!(payload["written"], 1);
3616+
3617+ // The same row is what the nest's own read door serves the school's staff
3618+ // — one function behind the write, one behind the read, neither school
3619+ // able to see the other's row.
3620+ let res = common::send(
3621+ &app,
3622+ "GET",
3623+ &format!("/insights/students/{student}"),
3624+ Some(&mudur),
3625+ None,
3626+ )
3627+ .await;
3628+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
3629+ assert_eq!(res.body["summary"]["marks"]["ortalama"], 72);
3630+ assert_eq!(res.body["summary"]["confidence"], "stable");
3631+ assert_eq!(res.body["attention"].as_array().map(Vec::len), Some(1));
3632+ assert_eq!(res.body["attention"][0]["trigger"], "not_egilimi_dusuyor");
3633+}
3634+
3635+#[tokio::test]
3636+async fn the_insight_ledger_and_pending_list_round_trip_over_the_bridge() {
3637+ let bridge = bridge().await;
3638+ let (service, _app, _db, _mudur, student) = insight_fixture(&bridge).await;
3639+
3640+ let run = insight_call(
3641+ AI_INSIGHT_RUN_UPSERT_CAPABILITY,
3642+ DEMO_SLUG,
3643+ json!({ "run": {
3644+ "run_day": "2026-09-17",
3645+ "started_at": 1_700_000_000_000i64,
3646+ "status": "partial",
3647+ "students_total": 3,
3648+ "students_ok": 2,
3649+ "students_failed": 0,
3650+ "students_skipped": 1,
3651+ "rows_written": 2,
3652+ "budget_exceeded": true,
3653+ "budget_ms": 60_000,
3654+ "retain_until": 1_800_000_000_000i64,
3655+ "pending_students": [student],
3656+ "failed_modules": ["segment"],
3657+ } }),
3658+ );
3659+ assert_eq!(ok_capability(capability_call(&service.conn, run).await)["written"], 1);
3660+
3661+ let pending = ok_capability(
3662+ capability_call(
3663+ &service.conn,
3664+ insight_call(AI_INSIGHT_PENDING_LIST_CAPABILITY, DEMO_SLUG, json!({})),
3665+ )
3666+ .await,
3667+ );
3668+ assert_eq!(pending["students"], json!([student]));
3669+
3670+ // A run day that is not `YYYY-MM-DD` is the caller's payload error, not a
3671+ // CHECK violation dressed as a server fault.
3672+ let bad_day = insight_call(
3673+ AI_INSIGHT_RUN_UPSERT_CAPABILITY,
3674+ DEMO_SLUG,
3675+ json!({ "run": {
3676+ "run_day": "17.09.2026",
3677+ "started_at": 1,
3678+ "status": "running",
3679+ "students_total": 0, "students_ok": 0, "students_failed": 0,
3680+ "students_skipped": 0, "rows_written": 0,
3681+ "budget_exceeded": false, "budget_ms": 1,
3682+ "retain_until": 1,
3683+ } }),
3684+ );
3685+ let (code, message) = refused_capability(capability_call(&service.conn, bad_day).await);
3686+ assert_eq!(code, "invalid_payload");
3687+ assert!(message.contains("run_day"), "names the field: {message}");
3688+}
3689+
3690+#[tokio::test]
3691+async fn the_sweep_and_purge_capabilities_answer_per_table_verdicts() {
3692+ let bridge = bridge().await;
3693+ let (service, _app, _db, _mudur, student) = insight_fixture(&bridge).await;
3694+
3695+ // An expired row: the sweep's own clock decides, so it must go.
3696+ let answer = capability_call(
3697+ &service.conn,
3698+ insight_call(
3699+ AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
3700+ DEMO_SLUG,
3701+ summary_payload(&student, 1), // long past
3702+ ),
3703+ )
3704+ .await;
3705+ assert_eq!(ok_capability(answer)["written"], 1);
3706+
3707+ let verdicts = ok_capability(
3708+ capability_call(
3709+ &service.conn,
3710+ insight_call(AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, DEMO_SLUG, json!({})),
3711+ )
3712+ .await,
3713+ );
3714+ assert_eq!(verdicts["tables"]["zeka_student_summary"], true);
3715+ assert_eq!(verdicts["tables"].as_object().map(|t| t.len()), Some(9));
3716+
3717+ // An empty roster is a fetch that failed, never "nobody is enrolled":
3718+ // obeyed, it would delete every student's derived rows in one call.
3719+ let empty = insight_call(
3720+ "insight.departed.purge",
3721+ DEMO_SLUG,
3722+ json!({ "students": [] }),
3723+ );
3724+ let (code, _) = refused_capability(capability_call(&service.conn, empty).await);
3725+ assert_eq!(code, "invalid_payload");
3726+}
3727+
3728+#[tokio::test]
3729+async fn a_capability_call_cannot_touch_another_schools_rows() {
3730+ let bridge = bridge().await;
3731+ let service =
3732+ connect_service(&bridge, hello("zeka", &["insight.refresh"]), Behaviour::Echo).await;
3733+ await_workers(&bridge, 1).await;
3734+ let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
3735+ let _mudur = common::login_as(&app, &demo_db, "mudur", "manager").await;
3736+ let ayse = common::login_as(&app, &demo_db, "ayse", "student").await;
3737+ let student = common::me_id(&app, &ayse).await;
3738+ let beta = Slug::try_new("beta").unwrap();
3739+ let beta_db = tenants
3740+ .create(SchoolId::generate(), &beta, "Beta College", ModuleSet::all())
3741+ .await
3742+ .expect("beta");
3743+
3744+ // Same payload the demo school accepts, sent for beta: beta's database
3745+ // has no such student, so the foreign key refuses it. That refusal is the
3746+ // proof the statement ran inside *beta's* database — run against the
3747+ // demo school it would have landed, which is exactly what must not
3748+ // happen when a frame names another school.
3749+ let cross = insight_call(
3750+ AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
3751+ beta.as_str(),
3752+ summary_payload(&student, 1_800_000_000_000i64),
3753+ );
3754+ let (code, message) = refused_capability(capability_call(&service.conn, cross).await);
3755+ assert_eq!(code, "invalid_payload");
3756+ assert!(message.contains("referenced row"), "{message}");
3757+
3758+ // Nothing landed in beta, and nothing leaked into the demo school either.
3759+ let beta_rows: i64 = sqlx::query_scalar("SELECT count(*) FROM zeka_student_summary")
3760+ .fetch_one(&beta_db)
3761+ .await
3762+ .expect("beta count");
3763+ assert_eq!(beta_rows, 0);
3764+ let demo_rows: i64 = sqlx::query_scalar("SELECT count(*) FROM zeka_student_summary")
3765+ .fetch_one(&demo_db)
3766+ .await
3767+ .expect("demo count");
3768+ assert_eq!(demo_rows, 0, "the refused call wrote nothing anywhere");
3769+}
3770+
3771+#[tokio::test]
3772+async fn a_capability_call_refuses_unknown_names_and_payloads_that_do_not_fit() {
3773+ let bridge = bridge().await;
3774+ let (service, _app, _db, _mudur, student) = insight_fixture(&bridge).await;
3775+
3776+ // A name nobody serves — no prefix match, no fallback: the shape that
3777+ // would make this a generic door is the shape that is missing.
3778+ let unknown = insight_call("insight.database.query", DEMO_SLUG, json!({ "sql": "SELECT 1" }));
3779+ let (code, message) = refused_capability(capability_call(&service.conn, unknown).await);
3780+ assert_eq!(code, "unknown_capability");
3781+ assert!(message.contains("insight.database.query"), "{message}");
3782+
3783+ // A payload that does not fit the operation's contract.
3784+ let bad = insight_call(
3785+ AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
3786+ DEMO_SLUG,
3787+ json!({ "rows": [{ "student": "not-a-uuid", "confidence": "stable",
3788+ "computed_at": 1, "retain_until": 2 }] }),
3789+ );
3790+ let (code, message) = refused_capability(capability_call(&service.conn, bad).await);
3791+ assert_eq!(code, "invalid_payload");
3792+ assert!(message.contains("student"), "names the field: {message}");
3793+
3794+ // A frame that names a school nobody deploys.
3795+ let stranger = insight_call(
3796+ AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
3797+ "nowhere",
3798+ summary_payload(&student, 1),
3799+ );
3800+ let (code, _) = refused_capability(capability_call(&service.conn, stranger).await);
3801+ assert_eq!(code, "unknown_school");
3802+}
3803+
3804+#[tokio::test]
3805+async fn the_school_directory_is_the_one_deployment_scoped_operation() {
3806+ let bridge = bridge().await;
3807+ let service =
3808+ connect_service(&bridge, hello("zeka", &["insight.refresh"]), Behaviour::Echo).await;
3809+ await_workers(&bridge, 1).await;
3810+ let (app, _db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
3811+ let beta = Slug::try_new("beta").unwrap();
3812+ tenants
3813+ .create(SchoolId::generate(), &beta, "Beta College", ModuleSet::all())
3814+ .await
3815+ .expect("beta");
3816+
3817+ // The frame names no school (there is none to name: this is how a shared
3818+ // fleet learns which schools exist).
3819+ let answer = capability_call(
3820+ &service.conn,
3821+ insight_call(AI_INSIGHT_SCHOOLS_LIST_CAPABILITY, "", json!({})),
3822+ )
3823+ .await;
3824+ let payload = ok_capability(answer);
3825+ let schools: Vec<&str> = payload["schools"]
3826+ .as_array()
3827+ .expect("schools")
3828+ .iter()
3829+ .map(|s| s.as_str().expect("slug"))
3830+ .collect();
3831+ assert_eq!(schools, vec!["beta", DEMO_SLUG], "active schools, sorted");
3832+
3833+ // Over HTTP the same operation is the builder's: a school session must
3834+ // not be able to enumerate the deployment's other customers.
3835+ let ayse = common::login(&app, "ayse").await;
3836+ let refused = common::send(&app, "GET", "/insights/schools", Some(&ayse), None).await;
3837+ assert_eq!(refused.status, StatusCode::UNAUTHORIZED, "{}", refused.body);
3838+ let anonymous = common::send(&app, "GET", "/insights/schools", None, None).await;
3839+ assert_eq!(anonymous.status, StatusCode::UNAUTHORIZED);
3840+
3841+ // And the builder — the deployment operator — reads the same directory.
3842+ builder::ensure(
3843+ tenants.control(),
3844+ Username::try_new("operator").unwrap(),
3845+ Password::try_new("secret1").unwrap(),
3846+ )
3847+ .await
3848+ .expect("seed the builder");
3849+ let login = common::send(
3850+ &app,
3851+ "POST",
3852+ "/builder/login",
3853+ None,
3854+ Some(json!({ "username": "operator", "password": "secret1" })),
3855+ )
3856+ .await;
3857+ assert_eq!(login.status, StatusCode::OK, "{}", login.body);
3858+ let cookie = login.cookie.expect("builder cookie");
3859+ let listed = common::send(&app, "GET", "/insights/schools", Some(&cookie), None).await;
3860+ assert_eq!(listed.status, StatusCode::OK, "{}", listed.body);
3861+ assert_eq!(listed.body, payload);
3862+}
3863+
3864+#[tokio::test]
3865+async fn the_storage_doors_are_manager_only_and_write_the_callers_own_school() {
3866+ let bridge = bridge().await;
3867+ let (service, app, db, mudur, student) = insight_fixture(&bridge).await;
3868+ let _ = service;
3869+
3870+ // A teacher may read insights, but these doors write rows about students
3871+ // school-wide: manager+ is the floor, as it is on the ledger read.
3872+ let ogretmen = common::login_as(&app, &db, "ogretmen", "teacher").await;
3873+ let body = summary_payload(&student, 1_800_000_000_000i64);
3874+ let refused = common::send(
3875+ &app,
3876+ "POST",
3877+ "/insights/summaries",
3878+ Some(&ogretmen),
3879+ Some(body.clone()),
3880+ )
3881+ .await;
3882+ assert_eq!(refused.status, StatusCode::FORBIDDEN, "{}", refused.body);
3883+ let anonymous = common::send(&app, "POST", "/insights/summaries", None, Some(body.clone())).await;
3884+ assert_eq!(anonymous.status, StatusCode::UNAUTHORIZED);
3885+
3886+ // The same operation the bridge serves, on the caller's own school.
3887+ let written = common::send(
3888+ &app,
3889+ "POST",
3890+ "/insights/summaries",
3891+ Some(&mudur),
3892+ Some(body),
3893+ )
3894+ .await;
3895+ assert_eq!(written.status, StatusCode::OK, "{}", written.body);
3896+ assert_eq!(written.body["written"], 1);
3897+
3898+ // 413 for a batch past the ceiling, refused whole — never narrowed.
3899+ let over: Vec<Value> = (0..501)
3900+ .map(|_| {
3901+ json!({ "student": student, "confidence": "stable",
3902+ "computed_at": 1_700_000_000_000i64,
3903+ "retain_until": 1_800_000_000_000i64 })
3904+ })
3905+ .collect();
3906+ let too_many = common::send(
3907+ &app,
3908+ "POST",
3909+ "/insights/summaries",
3910+ Some(&mudur),
3911+ Some(json!({ "rows": over })),
3912+ )
3913+ .await;
3914+ assert_eq!(too_many.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", too_many.body);
3915+
3916+ // The run ledger's POST and the existing GET share one path.
3917+ let run = common::send(
3918+ &app,
3919+ "POST",
3920+ "/insights/runs",
3921+ Some(&mudur),
3922+ Some(json!({ "run": {
3923+ "run_day": "2026-09-18",
3924+ "started_at": 1_700_000_000_000i64,
3925+ "status": "ok",
3926+ "students_total": 1, "students_ok": 1, "students_failed": 0,
3927+ "students_skipped": 0, "rows_written": 1,
3928+ "budget_exceeded": false, "budget_ms": 60_000,
3929+ "retain_until": 1_800_000_000_000i64,
3930+ } })),
3931+ )
3932+ .await;
3933+ assert_eq!(run.status, StatusCode::OK, "{}", run.body);
3934+ let ledger = common::send(&app, "GET", "/insights/runs", Some(&mudur), None).await;
3935+ assert_eq!(ledger.status, StatusCode::OK, "{}", ledger.body);
3936+ assert_eq!(ledger.body["items"][0]["run_day"], "2026-09-18");
3937+ assert_eq!(ledger.body["items"][0]["status"], "ok");
3938+
3939+ // The sweep is a bodyless action route and answers one verdict per table.
3940+ let swept = common::send(&app, "POST", "/insights/sweep", Some(&mudur), None).await;
3941+ assert_eq!(swept.status, StatusCode::OK, "{}", swept.body);
3942+ assert_eq!(swept.body["tables"].as_object().map(|t| t.len()), Some(9));
3943+ // The retention the payload named is honoured: this row lives on.
3944+ let kept = common::send(
3945+ &app,
3946+ "GET",
3947+ &format!("/insights/students/{student}"),
3948+ Some(&mudur),
3949+ None,
3950+ )
3951+ .await;
3952+ assert_eq!(kept.status, StatusCode::OK);
3953+ assert_eq!(kept.body["summary"]["marks"]["ortalama"], 72);
3954+}
tests/ai_protocol.rsmodified+107 -0
@@ -1631,3 +1631,110 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() {
1631 assert_eq!(answer["code"], "malformed");1631 assert_eq!(answer["code"], "malformed");
1632 assert_eq!(answer["id"], "t-neither");1632 assert_eq!(answer["id"], "t-neither");
1633 }1633 }
1634+
1635+// ---------------------------------------------------- capability calls --
1636+//
1637+// The third client-initiated shape: a service calling an operation the
1638+// *backend* serves (ZEKA's storage surface — no AI service holds a school
1639+// database credential here). Nothing about the two shapes that existed before
1640+// may move: an api read is still routed on `path`, a blob read on `file`, and
1641+// a service that never calls a capability never receives one — the new frame
1642+// only ever appears on a stream the service itself opened, so a client that
1643+// does not speak it cannot be surprised by it. These tests pin the shape the
1644+// way a foreign service reads it: bytes in, untyped JSON out.
1645+
1646+#[tokio::test]
1647+async fn a_capability_call_carries_exactly_the_published_keys() {
1648+ let bridge = bridge().await;
1649+ let service = raw::handshake(&bridge, &raw::hello("zeka", "insight.refresh")).await;
1650+ await_workers(&bridge, 1).await;
1651+ // The storage surface runs against a real school database, so the bridge
1652+ // needs the api handle armed (`app_with_ai`) and a student that exists.
1653+ let (app, db) = common::app_with_ai(Some(bridge.clone())).await;
1654+ let _ = db;
1655+ let ayse = common::login(&app, "ayse").await;
1656+ let student = common::me_id(&app, &ayse).await;
1657+
1658+ let body = format!(
1659+ r#"{{"id":"t-cap","school":"{SCHOOL}","capability":"insight.summary.upsert","payload":{{"rows":[{{"student":"{student}","marks":{{"ortalama":72}},"confidence":"stable","computed_at":1700000000000,"retain_until":1800000000000}}]}}}}"#
1660+ );
1661+ let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await;
1662+
1663+ assert_eq!(
1664+ raw::keys(&answer),
1665+ ["id", "payload", "school", "status"],
1666+ "capability answer shape changed: {answer}"
1667+ );
1668+ assert_eq!(answer["status"], "ok", "{answer}");
1669+ assert_eq!(answer["id"], "t-cap");
1670+ assert_eq!(
1671+ answer["school"], SCHOOL,
1672+ "the answer echoes the school the call named"
1673+ );
1674+ assert_eq!(answer["payload"]["written"], 1, "{answer}");
1675+}
1676+
1677+#[tokio::test]
1678+async fn a_capability_refusal_is_flat_and_never_reports_ok() {
1679+ // A service branches on `status` first and on `code` second; both are
1680+ // pinned literals, and a refusal carries no payload — there is no
1681+ // half-answer to read.
1682+ let bridge = bridge().await;
1683+ let service = raw::handshake(&bridge, &raw::hello("zeka", "insight.refresh")).await;
1684+ await_workers(&bridge, 1).await;
1685+ let (_app, _db) = common::app_with_ai(Some(bridge.clone())).await;
1686+
1687+ let body = format!(
1688+ r#"{{"id":"t-nope","school":"{SCHOOL}","capability":"insight.database.query","payload":{{"sql":"select 1"}}}}"#
1689+ );
1690+ let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await;
1691+ assert_eq!(
1692+ raw::keys(&answer),
1693+ ["code", "id", "message", "school", "status"],
1694+ "capability refusal shape changed: {answer}"
1695+ );
1696+ assert_eq!(answer["status"], "err", "{answer}");
1697+ assert_eq!(answer["code"], "unknown_capability", "{answer}");
1698+ assert_eq!(answer["id"], "t-nope");
1699+ assert_eq!(answer["school"], SCHOOL);
1700+ assert!(
1701+ answer["message"].as_str().is_some_and(|m| !m.is_empty()),
1702+ "message must be a string a service can log"
1703+ );
1704+}
1705+
1706+#[tokio::test]
1707+async fn the_capability_shape_does_not_steal_the_shapes_that_existed_before() {
1708+ // Precedence, pinned: `path` wins over `file` wins over `capability`, so
1709+ // every frame that parsed as one of the older shapes still parses as it
1710+ // did — the capability branch is only reached when neither is present.
1711+ let bridge = bridge().await;
1712+ let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await;
1713+ await_workers(&bridge, 1).await;
1714+ let (app, _db) = common::app_with_ai(Some(bridge.clone())).await;
1715+ let ayse = common::login(&app, "ayse").await;
1716+ let student = common::me_id(&app, &ayse).await;
1717+
1718+ // A frame carrying both: still the api read it has always been.
1719+ let body = format!(
1720+ r#"{{"id":"t-both","school":"{SCHOOL}","path":"/auth/me","capability":"insight.pending.list","payload":{{}},"on_behalf_of":"{student}"}}"#
1721+ );
1722+ let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await;
1723+ assert_eq!(answer["outcome"], "ok", "{answer}");
1724+ assert_eq!(answer["status"], 200, "{answer}");
1725+
1726+ // A capability-only frame: the capability call, and a read the service
1727+ // asked for comes back in its own envelope.
1728+ let body = format!(
1729+ r#"{{"id":"t-pending","school":"{SCHOOL}","capability":"insight.pending.list","payload":{{}}}}"#
1730+ );
1731+ let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await;
1732+ assert_eq!(answer["status"], "ok", "{answer}");
1733+ assert_eq!(answer["payload"]["students"], json!([]), "{answer}");
1734+
1735+ // Neither: the same api-read refusal as before this shape existed.
1736+ let (answer, _) =
1737+ raw::api_read(&service.conn, br#"{"id":"t-neither","school":"demo"}"#).await;
1738+ assert_eq!(answer["outcome"], "err", "{answer}");
1739+ assert_eq!(answer["code"], "malformed");
1740+}
tests/limits_completeness.rsmodified+90 -6
@@ -145,22 +145,101 @@ const EXCLUDED: &[(&str, &str)] = &[
145 "deadline on one school-wide recompute; the run's own ledger is \145 "deadline on one school-wide recompute; the run's own ledger is \
146 `zeka_run`, which the client polls",146 `zeka_run`, which the client polls",
147 ),147 ),
148+ // The storage surface ZEKA's rows are written through (the service calls
149+ // these; the backend runs them). A browser never speaks the bridge, and
150+ // the HTTP doors that mirror them publish what a client can act on.
148 (151 (
149- "AI_PODCAST_SUBMIT_CAPABILITY",152+ "AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY",
150- "capability string an AI service declares",153+ "capability string the backend serves to an AI service",
151 ),154 ),
152 (155 (
153- "AI_PODCAST_STATUS_CAPABILITY",156+ "AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY",
154- "capability string an AI service declares",157+ "capability string the backend serves to an AI service",
158+ ),
159+ (
160+ "AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY",
161+ "capability string the backend serves to an AI service",
162+ ),
163+ (
164+ "AI_INSIGHT_PROFILE_UPSERT_CAPABILITY",
165+ "capability string the backend serves to an AI service",
166+ ),
167+ (
168+ "AI_INSIGHT_RUN_UPSERT_CAPABILITY",
169+ "capability string the backend serves to an AI service",
170+ ),
171+ (
172+ "AI_INSIGHT_PENDING_LIST_CAPABILITY",
173+ "capability string the backend serves to an AI service",
174+ ),
175+ (
176+ "AI_INSIGHT_RETENTION_SWEEP_CAPABILITY",
177+ "capability string the backend serves to an AI service",
178+ ),
179+ (
180+ "AI_INSIGHT_DEPARTED_PURGE_CAPABILITY",
181+ "capability string the backend serves to an AI service",
182+ ),
183+ (
184+ "AI_INSIGHT_SCHOOLS_LIST_CAPABILITY",
185+ "capability string the backend serves to an AI service",
186+ ),
187+ (
188+ "MAX_INSIGHT_BATCH_ROWS",
189+ "rows per bridge call: the AI service's own batch size, enforced by the \
190+ doors as a 413 and by the bridge as `too_many_rows`; a client of \
191+ neither cannot act on it",
192+ ),
193+ (
194+ "MAX_INSIGHT_PENDING_STUDENTS",
195+ "students one bridge answer may carry; over it the call is refused \
196+ (`too_many_rows`) rather than clipped, so there is no client-side \
197+ value to size against",
198+ ),
199+ (
200+ "MAX_INSIGHT_PURGE_STUDENTS",
201+ "students one bridge purge call may name; the roster is the AI \
202+ service's own list, not something a browser assembles",
155 ),203 ),
156 (204 (
157- "AI_PODCAST_RESULT_CAPABILITY",205+ "AI_PODCAST_SUBMIT_CAPABILITY",
158 "capability string an AI service declares",206 "capability string an AI service declares",
159 ),207 ),
208+ (
209+ "AI_PODCAST_REPORT_CAPABILITY",
210+ "capability string the backend serves; the AI service calls it",
211+ ),
160 (212 (
161 "AI_PODCAST_CANCEL_CAPABILITY",213 "AI_PODCAST_CANCEL_CAPABILITY",
162 "capability string an AI service declares",214 "capability string an AI service declares",
163 ),215 ),
216+ (
217+ "PODCAST_AUDIO_MAX_BYTES",
218+ "the largest episode the backend ingests from a service; a service-side \
219+ ingest bound a browser never assembles a body for",
220+ ),
221+ (
222+ "PODCAST_JOB_RETENTION_SECS",
223+ "how long a finished podcast job stays readable; the doors answer 410 \
224+ past it, which is the whole client-visible behavior — the number is \
225+ the operator's policy, not a value a client sizes against",
226+ ),
227+ (
228+ "PODCAST_JOB_STALE_FLOOR_SECS",
229+ "floor of the read-side staleness window a dead job is projected \
230+ failed in; a client reads the projected state, never sets this",
231+ ),
232+ (
233+ "PODCAST_JOB_STALE_ETA_FACTOR",
234+ "how many times its own ETA a podcast job may exceed before the read \
235+ side stops believing it runs; same as the floor — the projection is \
236+ the visible behavior",
237+ ),
238+ (
239+ "PODCAST_INTERRUPTED_CODE",
240+ "error_code value the backend writes for a job it concluded died; a \
241+ client reads it off the job, it is not a tunable",
242+ ),
164 (243 (
165 "CHAT_STREAM_POLL_MS",244 "CHAT_STREAM_POLL_MS",
166 "server-side poll cadence behind the SSE stream",245 "server-side poll cadence behind the SSE stream",
@@ -436,7 +515,12 @@ fn moved_value_tables_are_still_published_or_deliberately_excluded() {
436 /// constant: every former entry now lives there and is excused (or published)515 /// constant: every former entry now lives there and is excused (or published)
437 /// through `EXCLUDED` above instead. A new name here is a claim that a bound516 /// through `EXCLUDED` above instead. A new name here is a claim that a bound
438 /// belongs somewhere else, which needs an argument.517 /// belongs somewhere else, which needs an argument.
439-const NOT_A_CLIENT_BOUND: &[(&str, &str)] = &[];518+const NOT_A_CLIENT_BOUND: &[(&str, &str)] = &[(
519+ "MAX_CODE_LEN",
520+ "bound on the length of a podcast report's `stage`/`error_code` — values \
521+ the AI *service* writes onto the job row; a browser reads the stored \
522+ string back, it never sizes one against this",
523+)];
440 524
441 #[test]525 #[test]
442 fn validation_bounds_live_in_constant_rs() {526 fn validation_bounds_live_in_constant_rs() {