forge
Explore
Log in

Don't you dare go Hollow

hezarfen_zeka

Clone
★ 0

0 watching0 forksPython1.9 MiBe01a4faAhmet Kaan Gümüş2 months ago25 commits

capabilities.py385 lines, 16.1 KiBHistoryRawDownload
1"""ZEKA'nin ilan edecegi yetenekler ve payload sozlesmeleri.
2
3IKI YON VARDIR; karistirilmamalidir:
4
51. **Sunucu-baslatimli (backend -> ZEKA).** The backend dispatches `Request`
6 frames only for names its own dispatch table carries, and today
7 `insight.student` and `insight.refresh` are there: `ai/insight.rs`
8 `compute_student()` / `refresh()` send both, and the doors are in
9 `web/insights.rs` (merged 2026-09-18). `insight.class` is advertised but
10 never dispatched: its request names a course, and the bridge's read
11 allowlist hands a service no roster to enumerate it with
12 (`ai/insight.rs` module docs; `docs/BACKEND-GEREKSINIMLERI.md` item 3).
13 `insight.report` is the fourth name and the one whose answer is a DOCUMENT:
14 the backend reads its own `zeka_*` rows and dispatches them, and the service
15 renders the school report from them without reading anything itself. Its
16 door landed the same day the service side did (`constant.rs:645`,
17 `ai/insight.rs::report`, `web/insights.rs`), so the name is in
18 `BACKEND_CALLABLE_CAPABILITIES` -- unlike `insight.class`, whose door still
19 does not exist (`docs/BACKEND-GEREKSINIMLERI.md`, `## insight.report`).
20 Routing is an EXACT match (`ai/protocol.rs:91-94`): every advertised name
21 gets its handler from `handlers.wire()`, and `verify_dispatchable()` checks
22 the pair at startup -- if advertising and dispatch ever drift apart, the
23 service REFUSES TO BOOT.
24
252. **Istemci-baslatimli (ZEKA -> backend, depo yolu).** ZEKA'nin kendi `zeka_*`
26 satirlarini yazip okudugu yol budur: `store.BridgeStore`,
27 `BridgeProtocol.call_capability` ile `insight.schools.list`,
28 `insight.pending.list`, `insight.retention.sweep` gibi operasyonlari cagirir.
29 Bu yon backend'de 2026-09-17'de ACILDI (f84c29d) ve calisir.
30 `BACKEND_CALLABLE_CAPABILITIES` kumesi onu KAPSAMAZ: o kume yalnizca 1. yonu,
31 yani backend'in cagirabildigi adlari anlatir.
32
33Bu dosya 1. yon icin **sozlesme**dir (calisan bir yol degil); 2. yonun
34sozlesmesi `store.py` ve `protocol.py` icindedir.
35
36Gereksinim backend ekibine `docs/BACKEND-GEREKSINIMLERI.md` madde 1 ile
37iletilir.
38
39--- ilan disi kullanim ----------------------------------------------------
40`insight.refresh` ayrica ZEKA'nin KENDI zamanlayicisi tarafindan da cagrilir
41(`config.ZEKA_REFRESH_INTERVAL_SECS`). Yani hesaplar backend cagirmasa da
42kosar; backend'in yetenegi tanimasi yalnizca "istege bagli tetikleme"yi acar.
43"""
44
45from __future__ import annotations
46
47import logging
48from typing import Any, Callable, TypedDict
49
50from .protocol import CapabilityError
51
52log = logging.getLogger(__name__)
53
54# --- yetenek adlari --------------------------------------------------------
55# Ad alani `<servis>.<eylem>` desenini izler; backend'in `chat.reply` ve
56# `rag.index` adlari da boyledir.
57
58INSIGHT_STUDENT = "insight.student"
59"""Tek ogrenci icin analiz/tavsiye uret."""
60
61INSIGHT_CLASS = "insight.class"
62"""Bir sinif (ya da ders) icin toplu analiz uret."""
63
64INSIGHT_REFRESH = "insight.refresh"
65"""Bir okul icin hesaplari yeniden kosturur; parti isidir."""
66
67INSIGHT_REPORT = "insight.report"
68"""Verilen satirlardan okul raporu BELGESI uretir.
69
70Tek `insight.*` isleyicisi ki koprudan HICBIR SEY okumaz: satirlar payload'da
71gelir (backend kendi `zeka_*` tablolarindan okur), servis yalniz render eder.
72Istek/cevap sozlesmesi: `ReportRequest` / `ReportResponse` ve
73`docs/BACKEND-GEREKSINIMLERI.md` `## insight.report`.
74"""
75
76NAMES: tuple[str, ...] = (
77 INSIGHT_STUDENT,
78 INSIGHT_CLASS,
79 INSIGHT_REFRESH,
80 INSIGHT_REPORT,
81)
82
83
84#: The capability names the backend can send a `Request` FOR -- the half of
85#: its dispatch table that concerns ZEKA. It does NOT cover the `insight.*`
86#: storage operations the service calls (see the module docstring, direction
87#: 2). Sources: `constant.rs:568,574` (chat.reply, rag.index) and
88#: `ai/insight.rs::compute_student/refresh` + the `web/insights.rs` doors
89#: (insight.student, insight.refresh; merged 2026-09-18). `insight.class` is
90#: NOT in the set: the constant exists, the code that would send it does not.
91#: `insight.report` IS in the set (since 2026-09-18): the backend's constant
92#: (`constant.rs:645`) and its dispatch (`ai/insight.rs::report`, the
93#: `POST /runs/{run_day}/report` door in `web/insights.rs`) all landed, so the
94#: name left the "advertised but never dispatched" list the same day the
95#: service side was written. `tests/test_capabilities.py` pins this.
96BACKEND_CALLABLE_CAPABILITIES: tuple[str, ...] = (
97 "chat.reply",
98 "rag.index",
99 "insight.student",
100 "insight.refresh",
101 "insight.report",
102)
103
104#: The `sections` vocabulary: the summary's four compute modules. A request
105#: may name a subset; an unrequested module is NOT computed and reaches the
106#: row as `null` -- the backend's `SummaryRow` keeps `null` ("not computed")
107#: and `{}` ("read, and there was nothing") apart on purpose.
108SECTIONS: tuple[str, ...] = ("marks", "attendance", "submission", "study")
109
110
111# --- payload sozlesmeleri --------------------------------------------------
112# `Request.payload` ve `Response.payload` tasima icin OPAK'tir
113# (`ai/protocol.rs:146-147`); bicimi bu dosya tanimlar.
114
115
116class StudentRequest(TypedDict, total=False):
117 """`insight.student` istek payload'i.
118
119 `school` PAYLOAD'DA DEGILDIR: okul cerceve seviyesinde `Request.school`
120 alaninda gelir (`ai/protocol.rs:36-47`). Payload'a ikinci bir okul alani
121 koymak, iki kaynagin celisebilecegi bir yer yaratirdi.
122 """
123
124 user_id: str # zorunlu
125 since: str # ISO-8601 tarih; yoksa donem basi
126 sections: list[str] # istenen bolumler; yoksa hepsi
127 #: Cagriyi baslatan kullanicinin kimligi. Okumalar bu kimlikle
128 #: (`on_behalf_of`) gider; yoksa (eski backend) servis kendi `ai`
129 #: kimligiyle okur ve sonuc bos/403 olur (`handlers._principal`).
130 requested_by: str
131
132
133class StudentResponse(TypedDict, total=False):
134 """`insight.student` cevap payload'i (`handlers.student` doldurur)."""
135
136 user_id: str
137 generated_at: str # ISO-8601
138 archetype: str # BUGUN URETILMIYOR; alan gonderilmez (coverage.unavailable yazar)
139 signals: list[dict[str, Any]] # dikkat maddeleri: {trigger, course, fact, window_from, window_to, evidence}
140 recommendations: list[dict[str, Any]] # zeka_recommendation satirinin govdesi; `retain_until` gonderilmez
141 coverage: dict[str, Any] # okunan kaynak -> kayit sayisi + yazma muhasebesi + uretilemeyenler
142
143
144class ClassRequest(TypedDict, total=False):
145 """`insight.class` istek payload'i."""
146
147 course_id: str # zorunlu: hangi ders/sinif
148 term: str # donem anahtari; yoksa gecerli donem
149 top_n: int # dikkat listesi uzunlugu
150 requested_by: str # bkz. StudentRequest.requested_by
151
152
153class ClassResponse(TypedDict, total=False):
154 """`insight.class` cevap payload'i (`handlers.klass` doldurur)."""
155
156 course_id: str
157 generated_at: str
158 cohort_size: int
159 topic_gaps: list[dict[str, Any]] # BUGUN URETILMIYOR: bos liste + coverage.unavailable nedeni
160 attention_list: list[dict[str, Any]] # {user_id, trigger, fact, window_from, window_to, evidence} -- SKOR YOK
161 coverage: dict[str, Any]
162
163
164class RefreshRequest(TypedDict, total=False):
165 """`insight.refresh` istek payload'i. Parti isi: ogrenci listesi verilmezse
166 yapilandirmadaki liste kullanilir (backend'de kullanici listeleme yolu yok,
167 bkz. `docs/BACKEND-GEREKSINIMLERI.md` madde 3)."""
168
169 user_ids: list[str]
170 force: bool # onbellek gecerli olsa bile yeniden hesapla
171 requested_by: str # bkz. StudentRequest.requested_by
172
173
174class RefreshResponse(TypedDict, total=False):
175 """`insight.refresh` cevap payload'i (`handlers.refresh` doldurur)."""
176
177 started_at: str
178 requested: int
179 computed: int
180 skipped: int
181 failed: list[dict[str, Any]] # {user_id, code, message} -- code: unavailable|internal
182 #: Sozlesme disi ek alan: kosunun hukmu (`running|ok|partial|failed`).
183 #: Backend'in struct'i bunu tasimaz ve serde bilinmeyen alani yok sayar;
184 #: onsuz "0 istendi, 0 hesaplandi" temiz bir sifir gibi okunurdu.
185 status: str
186
187
188class ReportRequest(TypedDict, total=False):
189 """`insight.report` istek payload'i -- backend'in okudugu satirlar.
190
191 Satirlar backend'in KENDI yapilaridir (`db/insight.rs` `SummaryRow`,
192 `RecommendationRow`, `ProfileRow`, `RunRow`): ZEKA'nin depo yoluyla
193 yazdigi bicimin aynisi, yani ikinci bir esleme yok. Satirlarda `school`
194 YOKTUR -- ZEKA onu hic yazmaz; cercevede gelir ve isleyici her satira
195 damgalar (tek kimlik kaynagi). Payload'daki `school` yalniz GORUNUM icin
196 (`name` baslikta, `id` okul uuid'si). Backend `slug` gondermez.
197 """
198
199 kind: str
200 """Sunulan tek tip: `okul` (bkz. `handlers._SERVED_REPORT_KINDS`)."""
201 run_day: str
202 """`YYYY-MM-DD` (TR gunu); yoksa en yeni kosu satirindan turetilir."""
203 requested_by: str
204 """Belgeyi isteyen mudur. Okuma yapilmadigi icin yalniz log'a yazilir."""
205 school: dict[str, Any]
206 """`{"id": ..., "name": ...}` -- `id` okul uuid'si, `name` belge basligidir."""
207 classes: list[dict[str, Any]]
208 """`[{"id": ..., "name": ...}]` -- okulun butun subeleri (kimlik -> GORUNEN
209 ad). Satirlardaki `marks.classes` KIMLIK tasir; tabloya yazilan ad bu
210 haritadan gelir. Haritada olmayan kimlik `text.CLASS_LABEL_UNKNOWN` olur:
211 ham kimlik belgeye HICBIR kosulda girmez (canli kusur, 2026-09-18)."""
212 class_names: dict[str, Any]
213 """Kabul edilen ikinci bicim: `{"<kimlik>": "<ad>"}`. `classes` varsa o
214 kazanir; ikisi de yoksa belge yedek etiketle kurulur (eski backend)."""
215 summaries: list[dict[str, Any]]
216 """`zeka_student_summary` satirlari; `attention` listesi DAHIL (personel
217 raporunun dikkat tablosunu besleyen tek alan odur)."""
218 recommendations: list[dict[str, Any]]
219 """`zeka_recommendation` satirlari (kapatilan/suresi gecen satirlar
220 backend tarafindan suzulmezse paket onlari yine gostermez -- ama
221 `dismissed_at` satirda yoksa kapi bunu goremez; bkz. docs)."""
222 profiles: list[dict[str, Any]]
223 """`zeka_student_segment_profile` satirlari."""
224 runs: list[dict[str, Any]]
225 """`zeka_run` satirlari; `run_day` alani belgenin gununu verir."""
226
227
228class ReportResponse(TypedDict, total=False):
229 """`insight.report` cevap payload'i (`handlers.report` doldurur).
230
231 Tek `insight.*` cevabi ki BELGENIN KENDISINI tasir: blob yuklemesi yok,
232 depo yok. Degerler: `bad_request` (sozlesmeye uymayan payload),
233 `insufficient_rows` (dort liste de bos -- belge uretilecek satir yok),
234 `document_too_large` (HTML `_MAX_HTML_BYTES` ustunde; KESILMEZ, reddedilir),
235 `internal` (paket kurulamadi/cizilemedi).
236 """
237
238 kind: str
239 run_day: str # belgenin gunu: istekten aynen, yoksa turetildi
240 format: str # bugun her zaman "html"
241 html: str # tek dosyalik, kendi kendine yeten belge
242 byte_size: int # `html`in UTF-8 bayt uzunlugu
243 truncated: bool # her zaman False: sinir asilirsa reddedilir, kesilmez
244 notes: list[str] # paketin kendi kapsam/sinir cumleleri (report.notes)
245 #: Sozlesme disi ek alan (refresh'in `status`u gibi: serde yok sayar):
246 #: satir sayilari + paketin `empty` hukmu. "Belge neden bos" sorusunu
247 #: log'dan cevaplamak icin.
248 coverage: dict[str, Any]
249
250
251#: Yetenek adi -> (istek tipi, cevap tipi). Belge ve dogrulama icin.
252SCHEMAS: dict[str, tuple[type, type]] = {
253 INSIGHT_STUDENT: (StudentRequest, StudentResponse),
254 INSIGHT_CLASS: (ClassRequest, ClassResponse),
255 INSIGHT_REFRESH: (RefreshRequest, RefreshResponse),
256 INSIGHT_REPORT: (ReportRequest, ReportResponse),
257}
258
259
260# --- isleyici defteri ------------------------------------------------------
261
262Handler = Callable[[str, dict[str, Any]], dict[str, Any]]
263"""(`school`, `payload`) -> cevap payload'i. Okul cerceveden gelir."""
264
265_handlers: dict[str, Handler] = {}
266
267#: Servisin deposu (`store.BridgeStore`). Isleyiciler okulun deposunu
268#: BURADAN cozer: `capabilities.store().store_for(school)`. Cercevenin
269#: `school` alani tek kimlik kaynagidir; ikinci bir yol (ortam degiskeni,
270#: varsayilan okul) olmamasi bilincli -- yanlis okula yazan bir isleyici,
271#: bu alanin kapatmak istedigi tek arizadir.
272_store: Any = None
273
274
275def bind_store(store: Any) -> None:
276 """Acilista bir kez cagrilir (`bridge._serve`); testler de kullanir."""
277 global _store
278 _store = store
279
280
281def store() -> Any:
282 """Bagli depo. Baglanmamisken okul cozulemez -- sessizce bos bir depo
283 uydurmak, yazilan her seyi kaybederdi."""
284 if _store is None:
285 raise CapabilityError(
286 "unavailable",
287 "depo bagli degil; isleyici okul deposunu cozemez",
288 )
289 return _store
290
291
292def names() -> list[str]:
293 """`Hello.capabilities` icine yazilacak adlar."""
294 return list(NAMES)
295
296
297def register(name: str, handler: Handler) -> None:
298 """Bir yetenegi kaydet. Ilan edilmeyen ada kayit kabul edilmez -- ilan ile
299 dagitimin ayrisabilecegi tek yer burasi, o yuzden kapatiliyor.
300
301 Isleyici es zamanli (async) olabilir: `bridge._handle` boyle bir kancayi
302 olay dongusunde bekler, senkron olani is parcacigina verir
303 (`bridge.py:495-515`). ZEKA'nin isleyicileri async'tir cunku her okuma
304 kendi kopru cagrisidir (`handlers.py`)."""
305 if name not in NAMES:
306 raise KeyError(f"ilan edilmeyen yetenek kaydedilemez: {name!r}")
307 _handlers[name] = handler
308
309
310class RegistrationError(RuntimeError):
311 """Ilan edilen bir adin isleyicisi yok. Acilista, bilerek patlar."""
312
313
314def dispatchable_names() -> list[str]:
315 """Isleyicisi KAYITLI adlar. `names()` ne ilan edilecegini soyler."""
316 return [name for name in NAMES if name in _handlers]
317
318
319def verify_dispatchable() -> None:
320 """Ilani hak etmeyen tek bir ad varsa ACILISI durdur.
321
322 `bridge.run_once()` `Hello` cercevesini yazmadan hemen once cagirir, yani
323 ilan eden her yol bu denetimden gecmistir. Defter haftalarca BOSTU ve
324 `Hello` uc ad ilan ediyordu: backend'in gonderdigi her istek, ilan edilen
325 adi ayni cumlede sayan bir `unknown_capability` ile donuyordu. Bu sinifin
326 tekrar uretilmesini imkansiz kilan sey, ilan ile defterin ayni anda
327 dogrulanmasidir -- sonradan ozur dilemek degil.
328 """
329 missing = [name for name in NAMES if name not in _handlers]
330 if not missing:
331 return
332 message = (
333 f"ilan edilen yeteneklerin isleyicisi yok: {', '.join(missing)} "
334 f"(kayitli: {', '.join(dispatchable_names()) or 'yok'}) -- "
335 "servis bunlari ILAN EDEMEZ; handlers.wire() cagrildi mi?"
336 )
337 log.error(message)
338 raise RegistrationError(message)
339
340
341def dispatch(name: str, school: str, payload: Any) -> dict[str, Any]:
342 """Gelen `Request`'i isleyicisine ver.
343
344 Kayitli isleyici yoksa `unknown_capability` -- tam eslesme kurali burada da
345 gecerlidir; yaklasik eslesme ya da geri dusme YOKTUR.
346 """
347 handler = _handlers.get(name)
348 if handler is None:
349 raise CapabilityError(
350 "unknown_capability",
351 f"'{name}' bu serviste tanimli degil (ilan edilenler: {', '.join(NAMES)})",
352 )
353 if payload is None:
354 payload = {}
355 if not isinstance(payload, dict):
356 raise CapabilityError("bad_request", "payload bir nesne olmali")
357 return handler(school, payload)
358
359
360def require_text(payload: dict[str, Any], key: str) -> str:
361 value = payload.get(key)
362 if not isinstance(value, str) or not value.strip():
363 raise CapabilityError("bad_request", f"'{key}' bos olmayan bir metin olmali")
364 return value.strip()
365
366
367def summary() -> str:
368 """Acilis logu icin tek satir: iki yonu AYRI soyler.
369
370 Onceki hali "backend'in tanidigi: chat.reply, rag.index; N yetenek
371 TANIMSIZ" idi; depo yolu (2. yon) acildiktan ve backend `insight.student`
372 / `insight.refresh`i gonderdikten sonra bu cumle bayatladi. Uc gercek
373 ayri ayri yazilir: backend'in gonderebildigi adlar, servisin kayitli
374 isleyicileri, ve backend'in dagitim tablosunda hala olmayan adlar.
375 """
376 served = dispatchable_names()
377 unsent = [name for name in NAMES if name not in BACKEND_CALLABLE_CAPABILITIES]
378 return (
379 f"backend'in cagirabildigi yetenekler: "
380 f"{', '.join(BACKEND_CALLABLE_CAPABILITIES)} "
381 f"(servis->backend depo yolu: kopru/insight.* -- bu liste onu kapsamaz); "
382 f"servis tarafi isleyiciler: {len(served)}/{len(NAMES)} kayitli "
383 f"({', '.join(served) or 'yok'}); "
384 f"backend'in dagitim tablosunda olmayan: {', '.join(unsent) or 'yok'}"
385 )