forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rule_based_chatbot

Clone
★ 0

0 watching0 forksPython1.2 MiBa039b60Ahmet Kaan Gümüş2 months ago64 commits

role_spaces.py385 lines, 19.3 KiBHistoryRawDownload
1"""Compile independent, closed retrieval spaces for every Çelebi role.
2
3The action vocabulary mirrors the backend-owned role-space V2 contract. The
4bridge still treats the policy embedded in each V2 request as authoritative and
5echoes that request's version/hash; this local copy makes direct Engine/CLI use
6safe and deterministic instead of falling back to a privilege ladder.
7"""
8
9from __future__ import annotations
10
11import hashlib
12import json
13from functools import lru_cache
14from typing import Final
15
16from .access import (
17 AccessOutcome,
18 AccessScope,
19 CompiledRoleSpace,
20 ReasonCode,
21 RoleIntentView,
22)
23from .catalog import INTENTS, ROLE_HIERARCHY, RULE_ONLY_INTENTS
24from .domain import build_domain_vocab
25from .rules import RuleMatcher
26from .similarity import SimilarityMatcher
27
28
29ROLE_SPACE_VERSION: Final[str] = "2026-08-24.4"
30AUTHENTICATED_ROLES: Final[tuple[str, ...]] = (
31 "veli", "ogrenci", "ogretmen", "yonetici", "admin"
32)
33
34
35def _matrix(parent, student, teacher, manager, admin):
36 return dict(zip(AUTHENTICATED_ROLES, (parent, student, teacher, manager, admin)))
37
38
39A = AccessOutcome.ALLOW
40D = AccessOutcome.DENY
41G = AccessScope.GENERAL
42O = AccessScope.OWN
43E = AccessScope.ENROLLED_COURSE
44M = AccessScope.MANAGED_COURSE
45S = AccessScope.SCHOOL
46V = AccessScope.EVENT_AUDIENCE
47
48# (outcome, scope, navigation_key). İkili model: bir rol o işlemi backend'de
49# yapabiliyorsa (kapsamı ne olursa olsun) ALLOW — asistan adımları anlatır, kapsam
50# cevabın içinde nottur. Yapamıyorsa DENY — adım/rota/ayrıcalıklı rol adı sızmaz.
51# Kaynak: hezarfen_backend endpoint guard'ları (rol×yetki taraması). CLARIFY-for-
52# scope KALDIRILDI: bu asistan sistemi ANLATIR, kapsamı çalışma anında doğrulamaz.
53_ACTION_RULES: Final[dict[str, dict[str, tuple[AccessOutcome, AccessScope | None, str | None]]]] = {
54 "platform.help": _matrix((A, G, "guide"), (A, G, "guide"), (A, G, "guide"), (A, G, "guide"), (A, G, "guide")),
55 # Teknik tanılama intent'lerinin açılacak bir ürün sayfası yoktur. Rehber
56 # içeriğini kullanabilseler de V2 metadata'da sahte bir `guide` rotası taşımazlar.
57 "platform.diagnostic": _matrix((A, G, None), (A, G, None), (A, G, None), (A, G, None), (A, G, None)),
58 "account.self": _matrix((A, O, "profile"), (A, O, "profile"), (A, O, "profile"), (A, O, "profile"), (A, O, "profile")),
59 "messages.use": _matrix((A, O, "messages"), (A, O, "messages"), (A, O, "messages"), (A, O, "messages"), (A, O, "messages")),
60 "notes.use": _matrix((A, O, "notes"), (A, O, "notes"), (A, O, "notes"), (A, O, "notes"), (A, O, "notes")),
61 # Ders görüntüleme: Veli erişemez (kayıt/yönetim yok); öğrenci kayıtlı derslerini,
62 # öğretmen yönettiklerini görür — ikisi de ALLOW (kapsam nottur).
63 "courses.view": _matrix((D, None, None), (A, E, "courses"), (A, M, "courses"), (A, S, "courses"), (A, S, "courses")),
64 "courses.create": _matrix((D, None, None), (D, None, None), (A, O, "courses"), (A, S, "courses"), (A, S, "courses")),
65 "courses.manage": _matrix((D, None, None), (D, None, None), (A, M, "courses"), (A, S, "courses"), (A, S, "courses")),
66 "courses.enroll_student": _matrix((D, None, None), (D, None, None), (A, M, "courses"), (A, S, "courses"), (A, S, "courses")),
67 # Ders kadrosunu yalnız okul yönetimi değiştirir; dersi yöneten öğretmen bu
68 # yetkiyi başka hesaba devredemez.
69 "courses.staff": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "courses"), (A, S, "courses")),
70 "classes.view": _matrix((D, None, None), (D, None, None), (A, S, "classes"), (A, S, "classes"), (A, S, "classes")),
71 "classes.manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "classes"), (A, S, "classes")),
72 # Sınava girme yalnız Öğrenci (backend: tam olarak Student + enrolled). Personel giremez.
73 "exams.take": _matrix((D, None, None), (A, E, "exams"), (D, None, None), (D, None, None), (D, None, None)),
74 "exams.manage": _matrix((D, None, None), (D, None, None), (A, M, "exams"), (A, S, "exams"), (A, S, "exams")),
75 # Ödev: görüntüleme öğrenci+ (Veli /students'tan çocuğunu izler, /homework'ü
76 # kullanmaz -> D); teslim yalnız Öğrenci (backend: exactly Student + enrolled);
77 # oluşturma/notlandırma Öğretmen+ (yönettiği ders).
78 "homework.view": _matrix((D, None, None), (A, E, "homework"), (A, M, "homework"), (A, S, "homework"), (A, S, "homework")),
79 "homework.submit": _matrix((D, None, None), (A, E, "homework"), (D, None, None), (D, None, None), (D, None, None)),
80 "homework.manage": _matrix((D, None, None), (D, None, None), (A, M, "homework"), (A, S, "homework"), (A, S, "homework")),
81 "events.create": _matrix((D, None, None), (D, None, None), (A, O, "events"), (A, S, "events"), (A, S, "events")),
82 # Yoklama işaretleme yalnız Öğretmen+ (backend events.rs:481-500 "students never
83 # mark, not even themselves"). Öğrenci ve Veli için DENY -> backend paritesi.
84 "events.mark_attendance": _matrix((D, None, None), (D, None, None), (A, V, "events"), (A, V, "events"), (A, V, "events")),
85 "reports.read_own": _matrix((A, O, "reports_self"), (A, O, "reports_self"), (A, O, "reports_self"), (A, O, "reports_self"), (A, O, "reports_self")),
86 # Öğrenci not/yoklama arama = Öğretmen yönetim sayfası (Öğretmen+). Veli bu sayfayı
87 # kullanmaz (çocuğunun verisini ayrı akıştan görür) -> DENY.
88 "reports.observe_student": _matrix((D, None, None), (D, None, None), (A, M, "student_marks"), (A, S, "student_marks"), (A, S, "student_marks")),
89 "reports.observe_attendance": _matrix((D, None, None), (D, None, None), (A, M, "student_attendance"), (A, S, "student_attendance"), (A, S, "student_attendance")),
90 # Pomodoro backend'de yalnız Student (pomodoro.rs:30,117-131 "Requires the student
91 # role"). Sadece öğrenci ALLOW; veli/öğretmen/yönetici/admin DENY -> backend paritesi.
92 "pomodoro.start": _matrix((D, None, None), (A, O, "pomodoro"), (D, None, None), (D, None, None), (D, None, None)),
93 "pomodoro.observe_student": _matrix((D, None, None), (D, None, None), (A, S, "student_pomodoro"), (A, S, "student_pomodoro"), (A, S, "student_pomodoro")),
94 # Kendi mesaisi yalnız Öğretmen/Yönetici. ADMIN personel mesaisini yönetir
95 # fakat `/work` sayfasında kendi giriş-çıkış kaydı tutmaz.
96 "work.self": _matrix((D, None, None), (D, None, None), (A, O, "work"), (A, O, "work"), (D, None, None)),
97 "work.manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "staff_work"), (A, S, "staff_work")),
98 "school.settings_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "school_settings"), (A, S, "school_settings")),
99 "school.terms_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "school_terms"), (A, S, "school_terms")),
100 "school.payments_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "payments_manage"), (A, S, "payments_manage")),
101 "payments.read_own": _matrix((A, O, "payments_self"), (A, O, "payments_self"), (D, None, None), (D, None, None), (D, None, None)),
102 "users.roles_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (D, None, None), (A, S, "admin_users")),
103 # --- T1 özellikleri ---
104 # Randevu: alma yalnız Öğrenci+Veli (backend: Student|Parent); saat açma/talep
105 # onaylama Öğretmen+.
106 "appointments.book": _matrix((A, O, "appointments"), (A, O, "appointments"), (D, None, None), (D, None, None), (D, None, None)),
107 "appointments.manage": _matrix((D, None, None), (D, None, None), (A, O, "appointments"), (A, S, "appointments"), (A, S, "appointments")),
108 # Yemek: menü görüntüleme herkese; yer ayırma Öğrenci(self)+Veli; menü/kredi Yönetici+.
109 "meals.view": _matrix((A, O, "meals"), (A, O, "meals"), (A, O, "meals"), (A, S, "meals"), (A, S, "meals")),
110 "meals.book": _matrix((A, O, "meals"), (A, O, "meals"), (D, None, None), (D, None, None), (D, None, None)),
111 "meals.manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "meals"), (A, S, "meals")),
112 "meals.service": _matrix((D, None, None), (D, None, None), (A, S, "meals"), (A, S, "meals"), (A, S, "meals")),
113 "meals.dietary_profile": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "meals"), (A, S, "meals")),
114 "meals.credit": _matrix((D, None, None), (D, None, None), (D, None, None), (D, None, None), (A, S, "meals")),
115 # Soru sorma backend'de yalnız Student; çözüm yazma Öğrenci+ (Veli hariç),
116 # onaylama ise Öğretmen+ moderasyonudur.
117 "qpool.ask": _matrix((D, None, None), (A, O, "questions"), (D, None, None), (D, None, None), (D, None, None)),
118 "qpool.solve": _matrix((D, None, None), (A, O, "questions"), (A, O, "questions"), (A, S, "questions"), (A, S, "questions")),
119 "qpool.moderate": _matrix((D, None, None), (D, None, None), (A, M, "questions"), (A, S, "questions"), (A, S, "questions")),
120 # Soru bankası şablonunda öğretmen ve yönetici yalnız kendi kayıtlarını
121 # değiştirir; ADMIN sahiplikten bağımsız okul kapsamındadır.
122 "question_bank.manage": _matrix((D, None, None), (D, None, None), (A, O, "question_bank"), (A, O, "question_bank"), (A, S, "question_bank")),
123 # Beyaz tahta: görüntüleme/oluşturma Öğrenci+ (Veli hariç).
124 "boards.use": _matrix((D, None, None), (A, O, "whiteboards"), (A, O, "whiteboards"), (A, S, "whiteboards"), (A, S, "whiteboards")),
125}
126
127_ACTION_BY_INTENT: Final[dict[str, str]] = {
128 "greeting": "platform.help",
129 "smalltalk": "platform.help",
130 "thanks": "platform.help",
131 "farewell": "platform.help",
132 "bot_identity": "platform.help",
133 "platform_info": "platform.help",
134 "help_capabilities": "platform.help",
135 "guide_info": "platform.help",
136 "login_how": "platform.help",
137 "register_how": "platform.help",
138 "logout_how": "account.self",
139 "session_info": "account.self",
140 "account_access_problem": "platform.help",
141 "profile_view": "account.self",
142 "profile_edit": "account.self",
143 "personal_settings": "account.self",
144 "language_theme": "account.self",
145 "roles_permissions": "platform.help",
146 "access_denied_help": "platform.help",
147 "technical_error_help": "platform.diagnostic",
148 "upload_problem": "platform.diagnostic",
149 "chatbot_service_problem": "platform.diagnostic",
150 "navigation_help": "platform.help",
151 "course_view": "courses.view",
152 "course_create": "courses.create",
153 "course_enroll_student": "courses.enroll_student",
154 "course_remove_student": "courses.manage",
155 "course_subject_manage": "courses.manage",
156 "course_note_manage": "courses.manage",
157 "course_teacher_manage": "courses.staff",
158 "lesson_session_add": "courses.manage",
159 "roll_call": "courses.manage",
160 "exam_modes_info": "platform.help",
161 "exam_create": "exams.manage",
162 "exam_add_question": "exams.manage",
163 "exam_enter_room": "exams.take",
164 "exam_save_answer": "exams.take",
165 "exam_finish_result": "exams.take",
166 "exam_rejoin_retake": "exams.take",
167 "exam_grade_student": "exams.manage",
168 "exam_live_monitor": "exams.manage",
169 "homework_view": "homework.view",
170 "homework_submit": "homework.submit",
171 "homework_withdraw_submission": "homework.submit",
172 "homework_assign": "homework.manage",
173 "homework_manage": "homework.manage",
174 "homework_grade": "homework.manage",
175 "report_card_view": "reports.read_own",
176 "weighted_average_info": "platform.help",
177 "student_marks_lookup": "reports.observe_student",
178 "attendance_view": "reports.read_own",
179 "attendance_rate_info": "platform.help",
180 "event_attendance_mark": "events.mark_attendance",
181 "student_attendance_lookup": "reports.observe_attendance",
182 "event_create": "events.create",
183 "note_import_ocr": "notes.use",
184 "note_file_manage": "notes.use",
185 "note_create": "notes.use",
186 "note_edit": "notes.use",
187 "note_delete": "notes.use",
188 "work_checkin_out": "work.self",
189 "staff_work_manage": "work.manage",
190 "term_manage": "school.terms_manage",
191 "school_settings": "school.settings_manage",
192 "user_role_change": "users.roles_manage",
193 "privacy_security": "platform.help",
194 "pomodoro_use": "pomodoro.start",
195 "student_pomodoro_lookup": "pomodoro.observe_student",
196 "messages_use": "messages.use",
197 "study_club_info": "courses.view",
198 "parent_info": "platform.help",
199 # Kapsam genişletme: bilgi/açıklama intent'leri (herkese açık, ALLOW).
200 "fees_info": "payments.read_own",
201 "fees_manage": "school.payments_manage",
202 "branches_info": "classes.view",
203 "class_section_manage": "classes.manage",
204 "calendar_info": "platform.help",
205 "today_info": "platform.help",
206 "question_bank_info": "exams.manage",
207 "question_bank_manage": "question_bank.manage",
208 "notification_settings_info": "platform.help",
209 "nav_overview": "platform.help",
210 "event_view": "platform.help",
211 "exam_schedule_info": "platform.help",
212 "course_materials_info": "courses.view",
213 # T1 özellikleri
214 "appointment_book": "appointments.book",
215 "appointment_slot_open": "appointments.manage",
216 "appointment_requests": "appointments.manage",
217 "meal_view": "meals.view",
218 "meal_book": "meals.book",
219 "meal_service_mark": "meals.service",
220 "meal_menu_manage": "meals.manage",
221 "meal_dietary_profile_manage": "meals.dietary_profile",
222 "meal_credit_manage": "meals.credit",
223 "question_ask": "qpool.ask",
224 "question_solve": "qpool.solve",
225 "question_approve": "qpool.moderate",
226 "board_view": "boards.use",
227 "board_create": "boards.use",
228}
229
230_OWN_REPORT_RESPONSES: Final[dict[str, str]] = {
231 "veli": (
232 "Veli hesabının kendine ait bir karne veya yoklama kaydı yoktur. Bağlı "
233 "olduğun öğrencinin karne ve yoklama bilgilerini uygulamadaki öğrenci "
234 "takip ekranından izleyebilirsin."
235 ),
236 "ogretmen": (
237 "Öğretmen hesabında kişisel karne/yoklama yoktur. Yönettiğin derslerdeki "
238 "öğrencilerin raporlarını Öğrenci notları ve Öğrenci yoklaması sayfalarından "
239 "görüntülersin."
240 ),
241 "yonetici": (
242 "Yönetici hesabında kişisel karne yoktur. Okul genelindeki öğrenci raporları "
243 "yönetim ekranlarından görüntülenir."
244 ),
245 "admin": (
246 "ADMIN hesabında kişisel karne yoktur. Okul genelindeki öğrenci raporları "
247 "yönetim ekranlarından görüntülenir."
248 ),
249}
250
251def action_id_for_intent(intent: str) -> str:
252 return _ACTION_BY_INTENT[intent]
253
254
255def _local_rule(item: dict, role: str):
256 action_id = action_id_for_intent(item["intent"])
257 if role == "ziyaretci":
258 if item["auth_required"]:
259 return action_id, D, None, None
260 return action_id, A, G, None
261 outcome, scope, route_key = _ACTION_RULES[action_id][role]
262 return action_id, outcome, scope, route_key
263
264
265def _deny_text(reason: ReasonCode) -> str:
266 """Ret metni. Ayrıcalıklı adım, rota veya gerekli-rol adı ASLA sızmaz.
267
268 Giriş gereken durumda (ziyaretçi) yalnız kamuya açık `/login` yolu verilir —
269 bu bir sızıntı değil, herkesin erişebildiği giriş sayfasıdır.
270 """
271
272 if reason is ReasonCode.AUTHENTICATION_REQUIRED:
273 return (
274 "Bu konu için önce giriş yapman gerekiyor. `/login` sayfasından "
275 "güvenli biçimde giriş yapabilirsin."
276 )
277 return (
278 "Bu işlem rolünün kapsamı dışında görünüyor 🙂 O yüzden adımları ve "
279 "yönlendirmeyi paylaşmıyorum. Yetkin dahilindeki bir konuda yardımcı olayım."
280 )
281
282
283def _view(item: dict, role: str) -> RoleIntentView:
284 action_id, outcome, scope, route_key = _local_rule(item, role)
285 if outcome is D:
286 reason = (
287 ReasonCode.AUTHENTICATION_REQUIRED
288 if role == "ziyaretci" and item["auth_required"]
289 else ReasonCode.ROLE_NOT_PERMITTED
290 )
291 body = _deny_text(reason)
292 scope = None
293 route_key = None
294 else: # ALLOW
295 reason = ReasonCode.ALLOWED
296 body = item["response_template"]
297 # Karne/yoklama sayfası öğrenciye özeldir; üst roller için kişisel karne
298 # yerine kapsam notu döndürülür (adım değil, bilgi).
299 if item["intent"] in {"report_card_view", "attendance_view"} and role != "ogrenci":
300 body = _OWN_REPORT_RESPONSES.get(role, body)
301
302 return RoleIntentView(
303 role=role,
304 intent=item["intent"],
305 action_id=action_id,
306 outcome=outcome,
307 scope=scope,
308 reason_code=reason,
309 response_id=item["response_id"],
310 response_template=body,
311 examples=tuple(item["example_questions"]),
312 clarification=None,
313 # Sözleşme metadata'sı (frontend butonu pasifleştirmek için kullanabilir);
314 # kullanıcıya dönen METİN ayrıcalıklı rol adını/adımı ASLA içermez.
315 required_role=item["min_role"] if outcome is D else None,
316 route_key=route_key if outcome is A else None,
317 route_label=None,
318 )
319
320
321def _hash_views(role: str, views: dict[str, RoleIntentView]) -> str:
322 manifest = [
323 {
324 "view": view.view_id,
325 "action": view.action_id,
326 "outcome": view.outcome.value,
327 "scope": view.scope.value if view.scope else None,
328 "route": view.route_key,
329 }
330 for view in views.values()
331 ]
332 raw = json.dumps(
333 {"version": ROLE_SPACE_VERSION, "role": role, "views": manifest},
334 ensure_ascii=False,
335 sort_keys=True,
336 separators=(",", ":"),
337 ).encode("utf-8")
338 return hashlib.sha256(raw).hexdigest()
339
340
341@lru_cache(maxsize=len(ROLE_HIERARCHY))
342def get_role_space(role: str) -> CompiledRoleSpace:
343 if role not in ROLE_HIERARCHY:
344 raise KeyError(f"bilinmeyen rol uzayı: {role!r}")
345 views = {item["intent"]: _view(item, role) for item in INTENTS}
346 content_hash = _hash_views(role, views)
347 space_id = f"{ROLE_SPACE_VERSION}:{role}:{content_hash[:12]}"
348 # RULE_ONLY_INTENTS benzerlik + domain-vocab havuzuna GİRMEZ (ortak kelimeleri
349 # IDF/OOS ayrımını bozuyordu); yalnız kuralla tetiklenirler.
350 examples = [
351 (view.intent, question)
352 for view in views.values()
353 if view.intent not in RULE_ONLY_INTENTS
354 for question in view.examples
355 ]
356 return CompiledRoleSpace(
357 role=role,
358 version=ROLE_SPACE_VERSION,
359 content_hash=content_hash,
360 views=CompiledRoleSpace.immutable_views(views),
361 rule_matcher=RuleMatcher(set(views), space_id=space_id),
362 similarity_matcher=SimilarityMatcher(examples, space_id=space_id),
363 domain_vocab=frozenset(build_domain_vocab(question for _, question in examples)),
364 )
365
366
367def validate_role_spaces() -> None:
368 expected = {item["intent"] for item in INTENTS}
369 if set(_ACTION_BY_INTENT) != expected:
370 missing = expected - set(_ACTION_BY_INTENT)
371 extra = set(_ACTION_BY_INTENT) - expected
372 raise ValueError(f"intent/action eşlemesi eksik={missing}, fazla={extra}")
373 ids: set[str] = set()
374 for role in ROLE_HIERARCHY:
375 space = get_role_space(role)
376 if set(space.views) != expected:
377 raise ValueError(f"{role}: eksik/fazla intent görünümü")
378 if space.space_id in ids:
379 raise ValueError(f"{role}: rol uzayı kimliği benzersiz değil")
380 ids.add(space.space_id)
381 if any(view.role != role for view in space.views.values()):
382 raise ValueError(f"{role}: başka role ait görünüm sızdı")
383
384
385validate_role_spaces()