Merge pull request #2 from Hezarfen-Co/feat/role-space-v2
Browse files at this commit17 changed files +863 -165
- src/access.py +92 -0
- src/catalog.py +8 -7
- src/decision.py +51 -47
- src/domain.py +16 -6
- src/engine.py +121 -29
- src/observability.py +44 -4
- src/responder.py +27 -11
- src/role_spaces.py +292 -0
- src/rules.py +59 -36
- src/similarity.py +7 -1
- tests/e2e/test_behavior_matrix.py +19 -9
- tests/e2e/test_conversation.py +3 -1
- tests/e2e/test_role_isolation.py +106 -0
- tests/integration/test_engine.py +6 -7
- tests/unit/test_bridge.py +3 -2
- tests/unit/test_cli.py +4 -2
- tests/unit/test_responder.py +5 -3
src/access.pyadded+92 -0
| @@ -0,0 +1,92 @@ | ||
| 1 | +"""Typed role-space access contract. | |
| 2 | + | |
| 3 | +The legacy catalog describes content. This module describes whether a piece of | |
| 4 | +content is actionable for one concrete, trusted role. Keeping those concerns | |
| 5 | +separate prevents a global retrieval result from becoming authorised merely | |
| 6 | +because a rank-based ``min_role`` comparison happened to pass. | |
| 7 | +""" | |
| 8 | + | |
| 9 | +from __future__ import annotations | |
| 10 | + | |
| 11 | +from dataclasses import dataclass | |
| 12 | +from enum import Enum | |
| 13 | +from types import MappingProxyType | |
| 14 | +from typing import Any, Mapping | |
| 15 | + | |
| 16 | + | |
| 17 | +class AccessOutcome(str, Enum): | |
| 18 | + ALLOW = "allow" | |
| 19 | + DENY = "deny" | |
| 20 | + CLARIFY = "clarify" | |
| 21 | + FALLBACK = "fallback" | |
| 22 | + | |
| 23 | + | |
| 24 | +class AccessScope(str, Enum): | |
| 25 | + GENERAL = "general" | |
| 26 | + OWN = "own" | |
| 27 | + LINKED_CHILD = "linked_child" | |
| 28 | + ENROLLED_COURSE = "enrolled_course" | |
| 29 | + MANAGED_COURSE = "managed_course" | |
| 30 | + OWNED_RESOURCE = "owned_resource" | |
| 31 | + PARTICIPANT = "participant" | |
| 32 | + REQUESTER = "requester" | |
| 33 | + EVENT_AUDIENCE = "event_audience" | |
| 34 | + SCHOOL = "school" | |
| 35 | + | |
| 36 | + | |
| 37 | +class ReasonCode(str, Enum): | |
| 38 | + ALLOWED = "allowed" | |
| 39 | + AUTHENTICATION_REQUIRED = "authentication_required" | |
| 40 | + ROLE_NOT_PERMITTED = "role_not_permitted" | |
| 41 | + EXACT_STUDENT_ONLY = "exact_student_only" | |
| 42 | + LINKED_STUDENT_SCOPE = "linked_student_scope" | |
| 43 | + TEACHER_OR_HIGHER_REQUIRED = "teacher_or_higher_required" | |
| 44 | + UI_ROUTE_UNAVAILABLE = "ui_route_unavailable" | |
| 45 | + CONTEXT_REQUIRED = "context_required" | |
| 46 | + | |
| 47 | + | |
| 48 | +@dataclass(frozen=True) | |
| 49 | +class RoleIntentView: | |
| 50 | + """One intent as compiled for exactly one role.""" | |
| 51 | + | |
| 52 | + role: str | |
| 53 | + intent: str | |
| 54 | + outcome: AccessOutcome | |
| 55 | + scope: AccessScope | None | |
| 56 | + reason_code: ReasonCode | |
| 57 | + response_id: str | |
| 58 | + response_template: str | |
| 59 | + examples: tuple[str, ...] | |
| 60 | + action_id: str | |
| 61 | + clarification: str | None = None | |
| 62 | + required_role: str | None = None | |
| 63 | + route_key: str | None = None | |
| 64 | + route_label: str | None = None | |
| 65 | + | |
| 66 | + @property | |
| 67 | + def view_id(self) -> str: | |
| 68 | + return f"{self.role}:{self.intent}" | |
| 69 | + | |
| 70 | + | |
| 71 | +@dataclass(frozen=True) | |
| 72 | +class CompiledRoleSpace: | |
| 73 | + """Immutable retrieval and policy bundle for one trusted role.""" | |
| 74 | + | |
| 75 | + role: str | |
| 76 | + version: str | |
| 77 | + content_hash: str | |
| 78 | + views: Mapping[str, RoleIntentView] | |
| 79 | + rule_matcher: Any | |
| 80 | + similarity_matcher: Any | |
| 81 | + domain_vocab: frozenset[str] | |
| 82 | + | |
| 83 | + def view_for(self, intent: str) -> RoleIntentView | None: | |
| 84 | + return self.views.get(intent) | |
| 85 | + | |
| 86 | + @property | |
| 87 | + def space_id(self) -> str: | |
| 88 | + return f"{self.version}:{self.role}:{self.content_hash[:12]}" | |
| 89 | + | |
| 90 | + @classmethod | |
| 91 | + def immutable_views(cls, views: dict[str, RoleIntentView]) -> Mapping[str, RoleIntentView]: | |
| 92 | + return MappingProxyType(dict(views)) |
src/catalog.pymodified+8 -7
| @@ -1203,17 +1203,18 @@ INTENTS: Final[list[dict[str, Any]]] = [ | ||
| 1203 | 1203 | { |
| 1204 | 1204 | "intent": "pomodoro_use", |
| 1205 | 1205 | "category": "pomodoro", |
| 1206 | - "description": "Pomodoro odak oturumu başlatma/bitirme (Öğrenci).", | |
| 1206 | + "description": "Pomodoro odak oturumu başlatma/bitirme (tüm roller).", | |
| 1207 | 1207 | "response_id": "pomodoro_instructions", |
| 1208 | 1208 | "response_template": ( |
| 1209 | - "Pomodoro, sunucu saatiyle damgalanan kişisel odak kaydıdır (yalnız " | |
| 1210 | - "Öğrenci). 1) `/pomodoro` sayfasına git. 2) **Odağı başlat (Start focus)** " | |
| 1211 | - "ile oturumu aç — aynı anda tek açık oturum olabilir. 3) Çalışman bitince " | |
| 1212 | - "**Odağı bitir (Finish focus)**'a bas. Sayfada **Toplam odak** süreni ve " | |
| 1213 | - "**Son oturumlar** geçmişini görürsün; saatler sunucu tarafından damgalanır." | |
| 1209 | + "Pomodoro, sunucu saatiyle damgalanan kişisel odak kaydıdır; giriş yapan " | |
| 1210 | + "her kullanıcı kendi oturumunu tutabilir. 1) `/pomodoro` sayfasına git. " | |
| 1211 | + "2) **Odağı başlat (Start focus)** ile oturumu aç — aynı anda tek açık " | |
| 1212 | + "oturum olabilir. 3) Çalışman bitince **Odağı bitir (Finish focus)**'a bas. " | |
| 1213 | + "Sayfada **Toplam odak** süreni ve **Son oturumlar** geçmişini görürsün; " | |
| 1214 | + "saatler sunucu tarafından damgalanır." | |
| 1214 | 1215 | ), |
| 1215 | 1216 | "auth_required": True, |
| 1216 | - "min_role": "ogrenci", | |
| 1217 | + "min_role": "veli", | |
| 1217 | 1218 | "example_questions": [ |
| 1218 | 1219 | "Pomodoro nasıl kullanılır?", |
| 1219 | 1220 | "Odak oturumu nasıl başlatırım?", |
src/decision.pymodified+51 -47
| @@ -19,13 +19,10 @@ from dataclasses import dataclass, replace | ||
| 19 | 19 | from typing import Final |
| 20 | 20 | |
| 21 | 21 | from . import rules |
| 22 | -from .catalog import ( | |
| 23 | - MIN_AUTHENTICATED_ROLE, | |
| 24 | - get_intent, | |
| 25 | - meets_role, | |
| 26 | - role_rank, | |
| 27 | -) | |
| 22 | +from .access import AccessOutcome | |
| 23 | +from .catalog import get_intent | |
| 28 | 24 | from .domain import is_in_domain |
| 25 | +from .role_spaces import get_role_space | |
| 29 | 26 | from .similarity import ScoredIntent, SimilarityMatcher, get_default_matcher |
| 30 | 27 | |
| 31 | 28 | |
| @@ -61,6 +58,13 @@ class Decision: | ||
| 61 | 58 | role_redirect: str | None = None |
| 62 | 59 | auth_action: str | None = None # None | LOGIN_REQUIRED | ROLE_INSUFFICIENT |
| 63 | 60 | required_role: str | None = None |
| 61 | + role: str = "ziyaretci" | |
| 62 | + view_id: str | None = None | |
| 63 | + outcome: str | None = None | |
| 64 | + scope: str | None = None | |
| 65 | + reason_code: str | None = None | |
| 66 | + role_space_version: str | None = None | |
| 67 | + role_space_hash: str | None = None | |
| 64 | 68 | |
| 65 | 69 | |
| 66 | 70 | def _apply_role_gating( |
| @@ -71,33 +75,34 @@ def _apply_role_gating( | ||
| 71 | 75 | if decision.fallback or decision.intent is None: |
| 72 | 76 | return decision |
| 73 | 77 | |
| 74 | - info = get_intent(decision.intent) | |
| 75 | - if info is None: | |
| 76 | - return decision | |
| 77 | - | |
| 78 | - auth_required = bool(info["auth_required"]) | |
| 79 | - min_role = info["min_role"] | |
| 80 | - | |
| 81 | - if auth_required and not authenticated: | |
| 82 | - return replace(decision, auth_action=LOGIN_REQUIRED, required_role=min_role) | |
| 83 | - | |
| 84 | 78 | effective_role = role if authenticated else "ziyaretci" |
| 85 | - if authenticated and not meets_role(effective_role, min_role): | |
| 86 | - return replace(decision, auth_action=ROLE_INSUFFICIENT, required_role=min_role) | |
| 87 | - | |
| 88 | - return decision | |
| 79 | + space = get_role_space(effective_role) | |
| 80 | + view = space.view_for(decision.intent) | |
| 81 | + if view is None: | |
| 82 | + return decision | |
| 83 | + action: str | None = None | |
| 84 | + if view.outcome is AccessOutcome.DENY: | |
| 85 | + action = LOGIN_REQUIRED if not authenticated else ROLE_INSUFFICIENT | |
| 86 | + return replace( | |
| 87 | + decision, | |
| 88 | + auth_action=action, | |
| 89 | + required_role=view.required_role, | |
| 90 | + role=effective_role, | |
| 91 | + view_id=view.view_id, | |
| 92 | + outcome=view.outcome.value, | |
| 93 | + scope=view.scope.value if view.scope else None, | |
| 94 | + reason_code=view.reason_code.value, | |
| 95 | + role_space_version=space.version, | |
| 96 | + role_space_hash=space.content_hash, | |
| 97 | + ) | |
| 89 | 98 | |
| 90 | 99 | |
| 91 | 100 | def _accessible(intent: str, role: str, authenticated: bool) -> bool: |
| 92 | 101 | """Oturum bu intent'i (auth + min_role) gerçekten yapabilir mi?""" |
| 93 | 102 | |
| 94 | - info = get_intent(intent) | |
| 95 | - if info is None: | |
| 96 | - return True | |
| 97 | - if bool(info["auth_required"]) and not authenticated: | |
| 98 | - return False | |
| 99 | 103 | effective_role = role if authenticated else "ziyaretci" |
| 100 | - return meets_role(effective_role, info["min_role"]) | |
| 104 | + view = get_role_space(effective_role).view_for(intent) | |
| 105 | + return view is not None and view.outcome is AccessOutcome.ALLOW | |
| 101 | 106 | |
| 102 | 107 | |
| 103 | 108 | def _is_confusable_pair(intent_a: str, intent_b: str) -> bool: |
| @@ -160,26 +165,11 @@ def decide_core( | ||
| 160 | 165 | if margin < tie_margin and _is_confusable_pair(top1.intent, ranked[1].intent): |
| 161 | 166 | tie_break = f"{top1.intent}~{ranked[1].intent}" |
| 162 | 167 | |
| 163 | - # Rol-farkında yönlendirme: top1 oturuma KAPALI ve top-k içinde AÇIKÇA | |
| 164 | - # karışabilir (must_not_match), ERİŞİLEBİLİR, yakın bir aday varsa, kullanıcının | |
| 165 | - # gerçekten yapabileceği yorumu seç ("öğrenci: notumu gör" -> öğretmenin | |
| 166 | - # student_marks_lookup'ı yerine report_card_view). Yalnızca yazar-onaylı | |
| 167 | - # confusable çiftlerde tetiklenir; "sınav oluştur -> yapamazsın" gibi meşru | |
| 168 | - # retleri MASKELEMEZ (o çiftler karışabilir işaretli değildir). | |
| 168 | + # V2 closed-space invariant: candidates were produced inside one concrete | |
| 169 | + # role-space. Never redirect to another candidate based on a global role | |
| 170 | + # hierarchy; the chosen view carries its own allow/deny policy. | |
| 169 | 171 | chosen = top1 |
| 170 | 172 | role_redirect: str | None = None |
| 171 | - if authenticated and not _accessible(top1.intent, role, authenticated): | |
| 172 | - for cand in ranked[1:top_k]: | |
| 173 | - if cand.score < threshold: | |
| 174 | - break | |
| 175 | - if ( | |
| 176 | - (top1.score - cand.score) <= role_redirect_margin | |
| 177 | - and _is_confusable_pair(top1.intent, cand.intent) | |
| 178 | - and _accessible(cand.intent, role, authenticated) | |
| 179 | - ): | |
| 180 | - chosen = cand | |
| 181 | - role_redirect = f"{top1.intent}->{cand.intent}" | |
| 182 | - break | |
| 183 | 173 | |
| 184 | 174 | decision = Decision( |
| 185 | 175 | intent=chosen.intent, |
| @@ -206,10 +196,24 @@ def decide( | ||
| 206 | 196 | ) -> Decision: |
| 207 | 197 | """Bir sorgu için nihai kararı üretir.""" |
| 208 | 198 | |
| 209 | - matcher = matcher or get_default_matcher() | |
| 210 | - rule_match = rules.match(query) | |
| 199 | + effective_role = role if authenticated else "ziyaretci" | |
| 200 | + space = get_role_space(effective_role) | |
| 201 | + matcher = matcher or space.similarity_matcher | |
| 202 | + rule_match = space.rule_matcher.match(query) | |
| 211 | 203 | ranked = None if rule_match is not None else matcher.rank(query) |
| 212 | - in_domain = True if rule_match is not None else is_in_domain(query) | |
| 204 | + if ranked is not None: | |
| 205 | + # Legacy injected matchers remain supported, but their candidates are | |
| 206 | + # projected into this role's local view set and tagged accordingly. | |
| 207 | + ranked = [ | |
| 208 | + ScoredIntent(item.intent, item.score, space.space_id) | |
| 209 | + for item in ranked | |
| 210 | + if item.intent in space.views | |
| 211 | + ] | |
| 212 | + in_domain = ( | |
| 213 | + True | |
| 214 | + if rule_match is not None | |
| 215 | + else is_in_domain(query, set(space.domain_vocab)) | |
| 216 | + ) | |
| 213 | 217 | return decide_core( |
| 214 | 218 | rule_match, |
| 215 | 219 | ranked, |
src/domain.pymodified+16 -6
| @@ -13,7 +13,7 @@ bulunur ve ayırt edici değildir. | ||
| 13 | 13 | |
| 14 | 14 | from __future__ import annotations |
| 15 | 15 | |
| 16 | -from typing import Final | |
| 16 | +from typing import Final, Iterable | |
| 17 | 17 | |
| 18 | 18 | from .catalog import INTENTS |
| 19 | 19 | from .normalize import folded_tokens |
| @@ -55,13 +55,23 @@ def _content_tokens(text: str) -> list[str]: | ||
| 55 | 55 | ] |
| 56 | 56 | |
| 57 | 57 | |
| 58 | -def build_domain_vocab() -> set[str]: | |
| 59 | - """Katalog örneklerinden ayırt edici alan söz varlığını üretir.""" | |
| 58 | +def build_domain_vocab(examples: Iterable[str] | None = None) -> set[str]: | |
| 59 | + """Örneklerden ayırt edici alan söz varlığını üretir. | |
| 60 | + | |
| 61 | + ``examples=None`` eski public API'yi korur ve tüm kataloğu kullanır. Rol | |
| 62 | + uzayları ise yalnızca kendi derlenmiş örneklerini verir. | |
| 63 | + """ | |
| 60 | 64 | |
| 61 | 65 | vocab: set[str] = set() |
| 62 | - for item in INTENTS: | |
| 63 | - for question in item["example_questions"]: | |
| 64 | - vocab.update(_content_tokens(question)) | |
| 66 | + source = examples | |
| 67 | + if source is None: | |
| 68 | + source = ( | |
| 69 | + question | |
| 70 | + for item in INTENTS | |
| 71 | + for question in item["example_questions"] | |
| 72 | + ) | |
| 73 | + for question in source: | |
| 74 | + vocab.update(_content_tokens(question)) | |
| 65 | 75 | return vocab |
| 66 | 76 | |
| 67 | 77 |
src/engine.pymodified+121 -29
| @@ -40,8 +40,10 @@ from .catalog import ( | ||
| 40 | 40 | route_for, |
| 41 | 41 | suggestions_for, |
| 42 | 42 | ) |
| 43 | +from .access import AccessOutcome | |
| 43 | 44 | from .normalize import folded_tokens |
| 44 | 45 | from .observability import new_trace_id, process |
| 46 | +from .role_spaces import get_role_space | |
| 45 | 47 | |
| 46 | 48 | # Rol beyanını ("ben öğrenciyim") gerçek sorudan ayırmak için yok sayılan doldurma |
| 47 | 49 | # kelimeleri. Bunlar dışındaki her kelime rol kelimesi değilse -> beyan sayılmaz. |
| @@ -81,7 +83,7 @@ CLARIFICATION_PROMPT_TEXT: str = ( | ||
| 81 | 83 | "Ders, sınav, karne, yoklama, defter, mesaj veya hesap ayarları hakkında " |
| 82 | 84 | "'nasıl yaparım?' diye sorabilirsin." |
| 83 | 85 | ) |
| 84 | -from .similarity import SimilarityMatcher, get_default_matcher | |
| 86 | +from .similarity import SimilarityMatcher | |
| 85 | 87 | |
| 86 | 88 | # İsteğe bağlı log alıcısı: bir trace sözlüğü alır (dosyaya/akışa yazmak çağıranın işi). |
| 87 | 89 | LogSink = Callable[[dict[str, Any]], None] |
| @@ -121,7 +123,7 @@ def _parse_session(payload: dict[str, Any]) -> tuple[str, bool]: | ||
| 121 | 123 | _MULTI_SPLIT_RE: re.Pattern[str] = re.compile(r"\s+(?:ve|ayrıca)\s+|[;,]", re.IGNORECASE) |
| 122 | 124 | |
| 123 | 125 | |
| 124 | -def _multi_intent_segments(query: str) -> list[tuple[str, str]] | None: | |
| 126 | +def _multi_intent_segments(query: str, role: str = "ziyaretci") -> list[tuple[str, str]] | None: | |
| 125 | 127 | """Sorgu birden çok BAĞIMSIZ isteğe bölünüyor mu? -> [(parça, intent), ...]. |
| 126 | 128 | |
| 127 | 129 | Muhafazakâr tasarım: yalnızca KURAL katmanının (yüksek kesinlik) tanıdığı |
| @@ -135,8 +137,9 @@ def _multi_intent_segments(query: str) -> list[tuple[str, str]] | None: | ||
| 135 | 137 | return None |
| 136 | 138 | hits: list[tuple[str, str]] = [] |
| 137 | 139 | seen: set[str] = set() |
| 140 | + rule_matcher = get_role_space(role).rule_matcher | |
| 138 | 141 | for segment in raw_segments: |
| 139 | - match = rules.match(segment) | |
| 142 | + match = rule_matcher.match(segment) | |
| 140 | 143 | if match is not None and match.intent not in seen: |
| 141 | 144 | seen.add(match.intent) |
| 142 | 145 | hits.append((segment, match.intent)) |
| @@ -170,20 +173,103 @@ def _declared_role(query: str) -> str | None: | ||
| 170 | 173 | return found |
| 171 | 174 | |
| 172 | 175 | |
| 173 | -def _build_navigation(intent: str | None, auth_action: str | None) -> dict[str, Any] | None: | |
| 176 | +def _build_navigation( | |
| 177 | + intent: str | None, | |
| 178 | + auth_action: str | None, | |
| 179 | + role: str = "ziyaretci", | |
| 180 | +) -> dict[str, Any] | None: | |
| 174 | 181 | """Seçilen intent için yönlendirme hedefi (route) üretir. |
| 175 | 182 | |
| 176 | 183 | Frontend bunu "Git →" butonu olarak çizer. `available`, kullanıcının rolü |
| 177 | 184 | yeterliyse True'dur (yetersizse buton pasif gösterilir; neden `auth_action`'da). |
| 178 | 185 | """ |
| 179 | 186 | |
| 180 | - if intent is None: | |
| 187 | + if intent is None or auth_action is not None: | |
| 181 | 188 | return None |
| 189 | + view = get_role_space(role).view_for(intent) | |
| 190 | + if view is None or view.outcome is not AccessOutcome.ALLOW: | |
| 191 | + return None | |
| 192 | + # Rota, izin verilen intent'in gerçek sayfasıdır (rehber §4). Reddedilen/CLARIFY | |
| 193 | + # görünümlerde buraya gelinmez -> ret'te rota sızmaz. Bilgi intent'lerinde | |
| 194 | + # (route_for None) navigasyon yoktur. | |
| 182 | 195 | route = route_for(intent) |
| 183 | 196 | if route is None: |
| 184 | 197 | return None |
| 185 | 198 | path, label = route |
| 186 | - return {"route": path, "label": label, "available": auth_action is None} | |
| 199 | + return {"route": path, "label": label, "available": True} | |
| 200 | + | |
| 201 | + | |
| 202 | +_WIRE_ROLES: dict[str, str] = { | |
| 203 | + "ziyaretci": "visitor", | |
| 204 | + "veli": "parent", | |
| 205 | + "ogrenci": "student", | |
| 206 | + "ogretmen": "teacher", | |
| 207 | + "yonetici": "manager", | |
| 208 | + "admin": "admin", | |
| 209 | +} | |
| 210 | + | |
| 211 | + | |
| 212 | +def assistant_meta_from_result(result: dict[str, Any], role: str) -> dict[str, Any]: | |
| 213 | + """Build the role-space V2 metadata from one engine result. | |
| 214 | + | |
| 215 | + The legacy engine response remains intact; bridge V2 puts this metadata next | |
| 216 | + to ``text`` on the wire. | |
| 217 | + """ | |
| 218 | + | |
| 219 | + space = get_role_space(role) | |
| 220 | + intent = result.get("intent") | |
| 221 | + view = space.view_for(intent) if isinstance(intent, str) else None | |
| 222 | + response_id = result.get("response_id") | |
| 223 | + if response_id == "clarification_prompt": | |
| 224 | + outcome = "clarify" | |
| 225 | + reason_code = "ambiguous_query" | |
| 226 | + elif bool(result.get("fallback")): | |
| 227 | + outcome = "fallback" | |
| 228 | + reason_code = "out_of_scope" | |
| 229 | + elif result.get("auth_action") is not None: | |
| 230 | + outcome = "deny" | |
| 231 | + reason_code = view.reason_code.value if view else "role_not_permitted" | |
| 232 | + elif isinstance(response_id, str) and response_id.startswith("safety_"): | |
| 233 | + outcome = "deny" | |
| 234 | + safety = result.get("safety") or {} | |
| 235 | + reason_code = "safety_" + str(safety.get("category", "blocked")).lower() | |
| 236 | + else: | |
| 237 | + outcome = "allow" | |
| 238 | + reason_code = view.reason_code.value if view else "allowed" | |
| 239 | + | |
| 240 | + navigation = None | |
| 241 | + if outcome == "allow" and view is not None and view.route_key is not None: | |
| 242 | + navigation = {"route_key": view.route_key} | |
| 243 | + if view.route_label: | |
| 244 | + navigation["label"] = view.route_label | |
| 245 | + | |
| 246 | + clarification = None | |
| 247 | + existing_clarification = result.get("clarification") | |
| 248 | + if outcome == "clarify" and isinstance(existing_clarification, dict): | |
| 249 | + options = [ | |
| 250 | + str(candidate.get("intent")) | |
| 251 | + for candidate in existing_clarification.get("candidates", []) | |
| 252 | + if isinstance(candidate, dict) and candidate.get("intent") | |
| 253 | + ] | |
| 254 | + clarification = {"prompt": CLARIFICATION_PROMPT_TEXT, "options": options} | |
| 255 | + | |
| 256 | + return { | |
| 257 | + "contract_version": 2, | |
| 258 | + "served_role": _WIRE_ROLES[role], | |
| 259 | + "role_space_version": space.version, | |
| 260 | + "role_space_hash": space.content_hash, | |
| 261 | + "outcome": outcome, | |
| 262 | + "action_id": intent, | |
| 263 | + "reason_code": reason_code, | |
| 264 | + "navigation": navigation, | |
| 265 | + "clarification": clarification, | |
| 266 | + "suggestions": list(result.get("suggestions") or []), | |
| 267 | + } | |
| 268 | + | |
| 269 | + | |
| 270 | +def _attach_assistant_meta(result: dict[str, Any], role: str) -> dict[str, Any]: | |
| 271 | + result["assistant_meta"] = assistant_meta_from_result(result, role) | |
| 272 | + return result | |
| 187 | 273 | |
| 188 | 274 | |
| 189 | 275 | def _build_clarification(trace: dict[str, Any], *, force: bool = False) -> dict[str, Any] | None: |
| @@ -323,7 +409,9 @@ class Engine: | ||
| 323 | 409 | log_sink: LogSink | None = None, |
| 324 | 410 | rate_limiter: "safety_mod.RateLimiter | None" = None, |
| 325 | 411 | ) -> None: |
| 326 | - self._matcher = matcher or get_default_matcher() | |
| 412 | + # ``None`` means role-local default. A custom matcher is retained for | |
| 413 | + # tests/opt-in embedding and projected into the selected space later. | |
| 414 | + self._matcher = matcher | |
| 327 | 415 | self._log_sink = log_sink |
| 328 | 416 | self._rate_limiter = rate_limiter |
| 329 | 417 | |
| @@ -368,7 +456,7 @@ class Engine: | ||
| 368 | 456 | "authenticated": authenticated, "short_circuit": "empty_query", |
| 369 | 457 | "response_id": FALLBACK["response_id"], |
| 370 | 458 | }) |
| 371 | - return empty | |
| 459 | + return _attach_assistant_meta(empty, role) | |
| 372 | 460 | |
| 373 | 461 | # 0) Rate-limit / spam (opsiyonel; user_id gerekir). |
| 374 | 462 | if self._rate_limiter is not None and user_id: |
| @@ -376,7 +464,7 @@ class Engine: | ||
| 376 | 464 | if limited is not None: |
| 377 | 465 | if self._log_sink is not None: |
| 378 | 466 | self._log_sink(_safety_trace(trace_id, query, role, authenticated, limited)) |
| 379 | - return { | |
| 467 | + return _attach_assistant_meta({ | |
| 380 | 468 | "trace_id": trace_id, |
| 381 | 469 | "response_id": "safety_" + limited.category.lower(), |
| 382 | 470 | "text": limited.user_message, |
| @@ -390,7 +478,7 @@ class Engine: | ||
| 390 | 478 | "answers": None, |
| 391 | 479 | "suggestions": suggestions, |
| 392 | 480 | "safety": _safety_info(limited), |
| 393 | - } | |
| 481 | + }, role) | |
| 394 | 482 | |
| 395 | 483 | # 1) İçerik-güvenliği giriş kapısı. |
| 396 | 484 | safety = safety_mod.evaluate_input(query, role=role, authenticated=authenticated) |
| @@ -399,7 +487,7 @@ class Engine: | ||
| 399 | 487 | if safety.decision in safety_mod.BLOCKING_DECISIONS: |
| 400 | 488 | if self._log_sink is not None: |
| 401 | 489 | self._log_sink(_safety_trace(trace_id, query, role, authenticated, safety)) |
| 402 | - return { | |
| 490 | + return _attach_assistant_meta({ | |
| 403 | 491 | "trace_id": trace_id, |
| 404 | 492 | "response_id": "safety_" + safety.category.lower(), |
| 405 | 493 | "text": safety.user_message, |
| @@ -413,23 +501,28 @@ class Engine: | ||
| 413 | 501 | "answers": None, |
| 414 | 502 | "suggestions": suggestions, |
| 415 | 503 | "safety": safety_info, |
| 416 | - } | |
| 504 | + }, role) | |
| 417 | 505 | |
| 418 | 506 | # 1.5) Rol beyanı ("Öğrenci", "ben öğretmenim") -> role özel yetenek özeti. |
| 419 | 507 | # Bot 'rolünü söyle' dediğinde verilen tek kelimelik cevabı anlamlandırır; |
| 420 | 508 | # aksi hâlde 'Öğrenci' yanlışlıkla 'öğrenci kaydet' intent'ine benzerdi. |
| 509 | + # Rol beyanı/sorusu BİLGİ amaçlıdır: sorulan rolün yeteneklerini anlatır, | |
| 510 | + # oturumun gerçek yetkisini (gating) ASLA değiştirmez. Doğrulanmış bir öğrenci | |
| 511 | + # 'admin' yazarsa admin yeteneklerini bilgi olarak görür, admin OLMAZ. | |
| 421 | 512 | declared = _declared_role(query) |
| 422 | - caps = capabilities_for(declared) if declared else None | |
| 513 | + served_declaration = declared | |
| 514 | + caps = capabilities_for(served_declaration) if served_declaration else None | |
| 423 | 515 | if caps: |
| 424 | 516 | if self._log_sink is not None: |
| 425 | 517 | self._log_sink({ |
| 426 | 518 | "trace_id": trace_id, "query_masked": safety_mod.mask_pii(query)[0], "role": role, |
| 427 | 519 | "authenticated": authenticated, "short_circuit": "role_declaration", |
| 428 | - "declared_role": declared, "response_id": "role_capabilities_" + declared, | |
| 520 | + "declared_role": declared, "served_role": served_declaration, | |
| 521 | + "response_id": "role_capabilities_" + served_declaration, | |
| 429 | 522 | }) |
| 430 | - return { | |
| 523 | + return _attach_assistant_meta({ | |
| 431 | 524 | "trace_id": trace_id, |
| 432 | - "response_id": "role_capabilities_" + declared, | |
| 525 | + "response_id": "role_capabilities_" + served_declaration, | |
| 433 | 526 | "text": caps, |
| 434 | 527 | "intent": None, |
| 435 | 528 | "confidence": 1.0, |
| @@ -441,7 +534,7 @@ class Engine: | ||
| 441 | 534 | "answers": None, |
| 442 | 535 | "suggestions": suggestions, |
| 443 | 536 | "safety": safety_info, |
| 444 | - } | |
| 537 | + }, role) | |
| 445 | 538 | |
| 446 | 539 | # PII maskeleme: maskelenmiş sorguyu boru hattına ver. |
| 447 | 540 | effective_query = query |
| @@ -449,7 +542,7 @@ class Engine: | ||
| 449 | 542 | effective_query = safety.masked_message |
| 450 | 543 | |
| 451 | 544 | # 1.6) Çoklu istek ('X ve Y'): her bağımsız parça ayrı yanıtlanır. |
| 452 | - segments = _multi_intent_segments(effective_query) | |
| 545 | + segments = _multi_intent_segments(effective_query, role) | |
| 453 | 546 | if segments is not None: |
| 454 | 547 | answers: list[dict[str, Any]] = [] |
| 455 | 548 | parts: list[str] = [] |
| @@ -463,7 +556,9 @@ class Engine: | ||
| 463 | 556 | "response_id": seg_response.response_id, |
| 464 | 557 | "text": seg_response.text, |
| 465 | 558 | "auth_action": seg_response.auth_action, |
| 466 | - "navigation": _build_navigation(seg_response.intent, seg_response.auth_action), | |
| 559 | + "navigation": _build_navigation( | |
| 560 | + seg_response.intent, seg_response.auth_action, role | |
| 561 | + ), | |
| 467 | 562 | }) |
| 468 | 563 | info = get_intent(seg_response.intent) if seg_response.intent else None |
| 469 | 564 | title = (info["description"].rstrip(".") if info else segment) |
| @@ -485,7 +580,7 @@ class Engine: | ||
| 485 | 580 | "response_id": first["response_id"], |
| 486 | 581 | "safety": safety_info, |
| 487 | 582 | }) |
| 488 | - return { | |
| 583 | + result = { | |
| 489 | 584 | "trace_id": trace_id, |
| 490 | 585 | "response_id": first["response_id"], |
| 491 | 586 | "text": _with_brand_note(text, query), |
| @@ -500,6 +595,7 @@ class Engine: | ||
| 500 | 595 | "suggestions": suggestions, |
| 501 | 596 | "safety": safety_info, |
| 502 | 597 | } |
| 598 | + return _attach_assistant_meta(result, role) | |
| 503 | 599 | |
| 504 | 600 | # 2) Boru hattı. |
| 505 | 601 | response, trace = process( |
| @@ -570,7 +666,7 @@ class Engine: | ||
| 570 | 666 | text = safety.user_message + "\n" + text |
| 571 | 667 | if self._log_sink is not None: |
| 572 | 668 | self._log_sink(trace) |
| 573 | - return { | |
| 669 | + result = { | |
| 574 | 670 | "trace_id": trace["trace_id"], |
| 575 | 671 | "response_id": "clarification_prompt", |
| 576 | 672 | "text": text, |
| @@ -585,6 +681,7 @@ class Engine: | ||
| 585 | 681 | "suggestions": suggestions, |
| 586 | 682 | "safety": safety_info, |
| 587 | 683 | } |
| 684 | + return _attach_assistant_meta(result, role) | |
| 588 | 685 | |
| 589 | 686 | text = response.text |
| 590 | 687 | # "Neler yapabilirim?" -> oturum rolü belliyse jenerik "rolünü söyle" yerine |
| @@ -593,12 +690,6 @@ class Engine: | ||
| 593 | 690 | role_caps = capabilities_for(role) |
| 594 | 691 | if role_caps: |
| 595 | 692 | text = role_caps |
| 596 | - # ADMIN'de kişisel mesai kaydı yoktur (mesai öğretmen/yönetici içindir). | |
| 597 | - if response.intent == "work_checkin_out" and role == "admin": | |
| 598 | - text = ( | |
| 599 | - "ADMIN hesabında kişisel mesai kaydı bulunmaz — mesai giriş/çıkışı " | |
| 600 | - "öğretmen ve yöneticiler içindir. Yine de akış şöyle:\n\n" | |
| 601 | - ) + text | |
| 602 | 693 | if safety.decision == safety_mod.ALLOW_WITH_WARNING and safety.user_message: |
| 603 | 694 | text = safety.user_message + "\n" + text |
| 604 | 695 | |
| @@ -613,7 +704,7 @@ class Engine: | ||
| 613 | 704 | if self._log_sink is not None: |
| 614 | 705 | self._log_sink(trace) |
| 615 | 706 | |
| 616 | - return { | |
| 707 | + result = { | |
| 617 | 708 | "trace_id": trace["trace_id"], |
| 618 | 709 | "response_id": response.response_id, |
| 619 | 710 | "text": _with_brand_note(text, query), |
| @@ -622,12 +713,13 @@ class Engine: | ||
| 622 | 713 | "fallback": response.fallback, |
| 623 | 714 | "auth_action": response.auth_action, |
| 624 | 715 | "required_role": trace["decision"]["required_role"], |
| 625 | - "navigation": _build_navigation(response.intent, response.auth_action), | |
| 716 | + "navigation": _build_navigation(response.intent, response.auth_action, role), | |
| 626 | 717 | "clarification": _build_clarification(trace), |
| 627 | 718 | "answers": None, |
| 628 | 719 | "suggestions": suggestions, |
| 629 | 720 | "safety": safety_info, |
| 630 | 721 | } |
| 722 | + return _attach_assistant_meta(result, role) | |
| 631 | 723 | |
| 632 | 724 | |
| 633 | 725 | # Kolaylık: paylaşılan varsayılan motor. |
src/observability.pymodified+44 -4
| @@ -18,6 +18,7 @@ import time | ||
| 18 | 18 | import uuid |
| 19 | 19 | from typing import Any |
| 20 | 20 | |
| 21 | +from .access import AccessOutcome | |
| 21 | 22 | from .catalog import get_intent, meets_role |
| 22 | 23 | from .safety import mask_pii |
| 23 | 24 | from .decision import ( |
| @@ -31,6 +32,8 @@ from . import rules | ||
| 31 | 32 | from .normalize import normalize, roots |
| 32 | 33 | from .responder import Response, render |
| 33 | 34 | from .similarity import SimilarityMatcher, get_default_matcher |
| 35 | +from .similarity import ScoredIntent | |
| 36 | +from .role_spaces import get_role_space | |
| 34 | 37 | |
| 35 | 38 | |
| 36 | 39 | def new_trace_id() -> str: |
| @@ -54,6 +57,21 @@ def check_auth_alarms(decision: Decision, authenticated: bool, role: str) -> lis | ||
| 54 | 57 | if decision.fallback or decision.intent is None: |
| 55 | 58 | return alarms |
| 56 | 59 | |
| 60 | + if decision.view_id: | |
| 61 | + effective_role = role if authenticated else "ziyaretci" | |
| 62 | + view = get_role_space(effective_role).view_for(decision.intent) | |
| 63 | + if view is None: | |
| 64 | + return [f"ROLE_SPACE_LEAK: '{decision.intent}' bu rol uzayında yok."] | |
| 65 | + expected = None | |
| 66 | + if view.outcome is AccessOutcome.DENY: | |
| 67 | + expected = LOGIN_REQUIRED if not authenticated else ROLE_INSUFFICIENT | |
| 68 | + if decision.auth_action != expected: | |
| 69 | + return [ | |
| 70 | + f"ROLE_SPACE_LEAK: '{decision.intent}' outcome={view.outcome.value} " | |
| 71 | + f"ama auth_action={decision.auth_action!r}." | |
| 72 | + ] | |
| 73 | + return alarms | |
| 74 | + | |
| 57 | 75 | info = get_intent(decision.intent) |
| 58 | 76 | if info is None: |
| 59 | 77 | return alarms |
| @@ -82,7 +100,9 @@ def process( | ||
| 82 | 100 | ) -> tuple[Response, dict[str, Any]]: |
| 83 | 101 | """Boru hattını izleyerek çalıştırır; (Response, trace kaydı) döndürür.""" |
| 84 | 102 | |
| 85 | - matcher = matcher or get_default_matcher() | |
| 103 | + effective_role = role if authenticated else "ziyaretci" | |
| 104 | + space = get_role_space(effective_role) | |
| 105 | + matcher = matcher or space.similarity_matcher | |
| 86 | 106 | trace_id = trace_id or new_trace_id() |
| 87 | 107 | latency: dict[str, float] = {} |
| 88 | 108 | |
| @@ -96,13 +116,23 @@ def process( | ||
| 96 | 116 | |
| 97 | 117 | # 2) Kural katmanı. |
| 98 | 118 | t = time.perf_counter_ns() |
| 99 | - rule_match = rules.match(query) | |
| 119 | + rule_match = space.rule_matcher.match(query) | |
| 100 | 120 | latency["rules"] = _elapsed_ms(t) |
| 101 | 121 | |
| 102 | 122 | # 3) Benzerlik + alan kapısı (yalnızca kural boş dönerse). |
| 103 | 123 | t = time.perf_counter_ns() |
| 104 | 124 | ranked = None if rule_match is not None else matcher.rank(query) |
| 105 | - in_domain = True if rule_match is not None else is_in_domain(query) | |
| 125 | + if ranked is not None: | |
| 126 | + ranked = [ | |
| 127 | + ScoredIntent(item.intent, item.score, space.space_id) | |
| 128 | + for item in ranked | |
| 129 | + if item.intent in space.views | |
| 130 | + ] | |
| 131 | + in_domain = ( | |
| 132 | + True | |
| 133 | + if rule_match is not None | |
| 134 | + else is_in_domain(query, set(space.domain_vocab)) | |
| 135 | + ) | |
| 106 | 136 | latency["similarity"] = _elapsed_ms(t) |
| 107 | 137 | |
| 108 | 138 | # 4) Karar. |
| @@ -125,6 +155,9 @@ def process( | ||
| 125 | 155 | "trace_id": trace_id, |
| 126 | 156 | "query_masked": query_masked, |
| 127 | 157 | "role": role, |
| 158 | + "role_space_id": space.space_id, | |
| 159 | + "role_space_version": space.version, | |
| 160 | + "role_space_hash": space.content_hash, | |
| 128 | 161 | "authenticated": authenticated, |
| 129 | 162 | "normalized": normalized, |
| 130 | 163 | "roots": query_roots, |
| @@ -136,7 +169,10 @@ def process( | ||
| 136 | 169 | "similarity": { |
| 137 | 170 | "evaluated": ranked is not None, |
| 138 | 171 | "in_domain": in_domain, |
| 139 | - "top_k": [{"intent": s.intent, "score": round(s.score, 4)} for s in decision.top_k], | |
| 172 | + "top_k": [ | |
| 173 | + {"intent": s.intent, "score": round(s.score, 4), "space_id": s.space_id} | |
| 174 | + for s in decision.top_k | |
| 175 | + ], | |
| 140 | 176 | "margin": decision.margin, |
| 141 | 177 | }, |
| 142 | 178 | "decision": { |
| @@ -148,6 +184,10 @@ def process( | ||
| 148 | 184 | "role_redirect": decision.role_redirect, |
| 149 | 185 | "auth_action": decision.auth_action, |
| 150 | 186 | "required_role": decision.required_role, |
| 187 | + "view_id": decision.view_id, | |
| 188 | + "outcome": decision.outcome, | |
| 189 | + "scope": decision.scope, | |
| 190 | + "reason_code": decision.reason_code, | |
| 151 | 191 | }, |
| 152 | 192 | "response_id": response.response_id, |
| 153 | 193 | "latency_ms": latency, |
src/responder.pymodified+27 -11
| @@ -2,9 +2,8 @@ | ||
| 2 | 2 | |
| 3 | 3 | İlkeler (rehber §0): |
| 4 | 4 | - Gerçek etiket/yol içeren `response_template` kullanılır (katalogda hazır). |
| 5 | -- Rol-farkında: seçilen intent oturum/rol gerektiriyor ve kullanıcı yetersizse, | |
| 6 | - cevabın başına kibar bir uyarı eklenir (ama adımlar yine gösterilir; kullanıcı | |
| 7 | - ne gerektiğini görsün). | |
| 5 | +- Rol-farkında: cevap gövdesi yalnızca güvenilir oturum rolünün derlenmiş | |
| 6 | + görünümünden gelir. Retlerde işlem adımı ve rota asla gösterilmez. | |
| 8 | 7 | - FALLBACK: anlaşılmayan/kapsam dışı sorularda netleştirme metni. |
| 9 | 8 | - `response_id` kararlıdır (testler metne değil id'ye bakar). |
| 10 | 9 | - Varyantlar (opsiyonel `response_variants`): sosyal intent'lerde robotik tekrarı |
| @@ -21,12 +20,14 @@ from typing import Final | ||
| 21 | 20 | |
| 22 | 21 | from .catalog import DEFAULT_GREETING_OPENER, FALLBACK, GREETING_OPENERS, get_intent |
| 23 | 22 | from .normalize import fold_accents, normalize |
| 23 | +from .access import AccessOutcome | |
| 24 | 24 | from .decision import ( |
| 25 | 25 | LOGIN_REQUIRED, |
| 26 | 26 | ROLE_INSUFFICIENT, |
| 27 | 27 | Decision, |
| 28 | 28 | decide, |
| 29 | 29 | ) |
| 30 | +from .role_spaces import get_role_space | |
| 30 | 31 | |
| 31 | 32 | |
| 32 | 33 | # Rollerin insan-okunur (arayüzdeki) adları. |
| @@ -111,18 +112,33 @@ def render(decision: Decision, query: str | None = None) -> Response: | ||
| 111 | 112 | fallback=True, |
| 112 | 113 | ) |
| 113 | 114 | |
| 114 | - body = _select_body(info, query) | |
| 115 | + view = get_role_space(decision.role).view_for(decision.intent) | |
| 116 | + if decision.view_id and view is not None: | |
| 117 | + if ( | |
| 118 | + view.outcome is AccessOutcome.ALLOW | |
| 119 | + and view.response_template == info["response_template"] | |
| 120 | + ): | |
| 121 | + # Standart ALLOW: aynalama/varyant sunum katmanı geri devrede | |
| 122 | + # ('günaydın' -> 'Günaydın! ☀️', sosyal varyantlar). | |
| 123 | + body = _select_body(info, query) | |
| 124 | + else: | |
| 125 | + # Ret metni ya da role özel geçersiz kılma (kişisel karne notu gibi): | |
| 126 | + # olduğu gibi kullanılır; ret gövdesine katalog adımları eklenmez. | |
| 127 | + body = view.response_template | |
| 128 | + else: | |
| 129 | + body = _select_body(info, query) | |
| 115 | 130 | |
| 116 | - if decision.auth_action == LOGIN_REQUIRED: | |
| 131 | + # Aşağıdaki dallar yalnız view_id'siz eski çağrı yolu içindir (üretimde her zaman | |
| 132 | + # view_id vardır -> ret metni role-space'ten gelir). Ret hiçbir yolda adım sızdırmaz. | |
| 133 | + if decision.auth_action == LOGIN_REQUIRED and not decision.view_id: | |
| 117 | 134 | text = ( |
| 118 | - "Bunun için önce giriş yapmalısın (`/login`). Giriş yaptıktan sonra:\n" | |
| 119 | - + body | |
| 135 | + "Bu konu için önce giriş yapman gerekiyor. `/login` sayfasından " | |
| 136 | + "güvenli biçimde giriş yapabilirsin." | |
| 120 | 137 | ) |
| 121 | - elif decision.auth_action == ROLE_INSUFFICIENT: | |
| 122 | - needed = role_display(decision.required_role or "") | |
| 138 | + elif decision.auth_action == ROLE_INSUFFICIENT and not decision.view_id: | |
| 123 | 139 | text = ( |
| 124 | - f"Bu işlem için en az **{needed}** yetkisi gerekir; mevcut rolün bunu " | |
| 125 | - f"yapmaya yetmiyor. Yine de adımlar şöyle:\n" + body | |
| 140 | + "Bu işlem senin rolünde yapılamıyor. Yetkisiz işlem adımları ve " | |
| 141 | + "yönlendirme paylaşılmadı." | |
| 126 | 142 | ) |
| 127 | 143 | else: |
| 128 | 144 | text = body |
src/role_spaces.pyadded+292 -0
| @@ -0,0 +1,292 @@ | ||
| 1 | +"""Compile independent, closed retrieval spaces for every Çelebi role. | |
| 2 | + | |
| 3 | +The action vocabulary mirrors the backend-owned role-space V2 contract. The | |
| 4 | +bridge still treats the policy embedded in each V2 request as authoritative and | |
| 5 | +echoes that request's version/hash; this local copy makes direct Engine/CLI use | |
| 6 | +safe and deterministic instead of falling back to a privilege ladder. | |
| 7 | +""" | |
| 8 | + | |
| 9 | +from __future__ import annotations | |
| 10 | + | |
| 11 | +import hashlib | |
| 12 | +import json | |
| 13 | +from functools import lru_cache | |
| 14 | +from typing import Final | |
| 15 | + | |
| 16 | +from .access import ( | |
| 17 | + AccessOutcome, | |
| 18 | + AccessScope, | |
| 19 | + CompiledRoleSpace, | |
| 20 | + ReasonCode, | |
| 21 | + RoleIntentView, | |
| 22 | +) | |
| 23 | +from .catalog import INTENTS, ROLE_HIERARCHY | |
| 24 | +from .domain import build_domain_vocab | |
| 25 | +from .rules import RuleMatcher | |
| 26 | +from .similarity import SimilarityMatcher | |
| 27 | + | |
| 28 | + | |
| 29 | +ROLE_SPACE_VERSION: Final[str] = "2026-08-12.1" | |
| 30 | +AUTHENTICATED_ROLES: Final[tuple[str, ...]] = ( | |
| 31 | + "veli", "ogrenci", "ogretmen", "yonetici", "admin" | |
| 32 | +) | |
| 33 | + | |
| 34 | + | |
| 35 | +def _matrix(parent, student, teacher, manager, admin): | |
| 36 | + return dict(zip(AUTHENTICATED_ROLES, (parent, student, teacher, manager, admin))) | |
| 37 | + | |
| 38 | + | |
| 39 | +A = AccessOutcome.ALLOW | |
| 40 | +D = AccessOutcome.DENY | |
| 41 | +G = AccessScope.GENERAL | |
| 42 | +O = AccessScope.OWN | |
| 43 | +E = AccessScope.ENROLLED_COURSE | |
| 44 | +M = AccessScope.MANAGED_COURSE | |
| 45 | +S = AccessScope.SCHOOL | |
| 46 | +V = 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 | + "account.self": _matrix((A, O, "profile"), (A, O, "profile"), (A, O, "profile"), (A, O, "profile"), (A, O, "profile")), | |
| 56 | + "messages.use": _matrix((A, O, "messages"), (A, O, "messages"), (A, O, "messages"), (A, O, "messages"), (A, O, "messages")), | |
| 57 | + "notes.use": _matrix((A, O, "notes"), (A, O, "notes"), (A, O, "notes"), (A, O, "notes"), (A, O, "notes")), | |
| 58 | + # Ders görüntüleme: Veli erişemez (kayıt/yönetim yok); öğrenci kayıtlı derslerini, | |
| 59 | + # öğretmen yönettiklerini görür — ikisi de ALLOW (kapsam nottur). | |
| 60 | + "courses.view": _matrix((D, None, None), (A, E, "courses"), (A, M, "courses"), (A, S, "courses"), (A, S, "courses")), | |
| 61 | + "courses.create": _matrix((D, None, None), (D, None, None), (A, O, "courses"), (A, S, "courses"), (A, S, "courses")), | |
| 62 | + "courses.manage": _matrix((D, None, None), (D, None, None), (A, M, "courses"), (A, S, "courses"), (A, S, "courses")), | |
| 63 | + "courses.enroll_student": _matrix((D, None, None), (D, None, None), (A, M, "courses"), (A, S, "courses"), (A, S, "courses")), | |
| 64 | + # Sınava girme yalnız Öğrenci (backend: tam olarak Student + enrolled). Personel giremez. | |
| 65 | + "exams.take": _matrix((D, None, None), (A, E, "exams"), (D, None, None), (D, None, None), (D, None, None)), | |
| 66 | + "exams.manage": _matrix((D, None, None), (D, None, None), (A, M, "exams"), (A, S, "exams"), (A, S, "exams")), | |
| 67 | + "events.create": _matrix((D, None, None), (D, None, None), (A, O, "events"), (A, S, "events"), (A, S, "events")), | |
| 68 | + # Kendi etkinlik yoklamasını herkes işaretler (öğrenci+); Veli salt-okunur gözlemci. | |
| 69 | + "events.mark_attendance": _matrix((D, None, None), (A, O, "events"), (A, V, "events"), (A, V, "events"), (A, V, "events")), | |
| 70 | + "reports.read_own": _matrix((A, O, "reports_self"), (A, O, "reports_self"), (A, O, "reports_self"), (A, O, "reports_self"), (A, O, "reports_self")), | |
| 71 | + # Öğrenci not/yoklama arama = Öğretmen yönetim sayfası (Öğretmen+). Veli bu sayfayı | |
| 72 | + # kullanmaz (çocuğunun verisini ayrı akıştan görür) -> DENY. | |
| 73 | + "reports.observe_student": _matrix((D, None, None), (D, None, None), (A, M, "student_marks"), (A, S, "student_marks"), (A, S, "student_marks")), | |
| 74 | + # Pomodoro backend'de her doğrulanmış kullanıcıya açık (CurrentUser) -> hepsi ALLOW. | |
| 75 | + "pomodoro.start": _matrix((A, O, "pomodoro"), (A, O, "pomodoro"), (A, O, "pomodoro"), (A, O, "pomodoro"), (A, O, "pomodoro")), | |
| 76 | + "pomodoro.observe_student": _matrix((D, None, None), (D, None, None), (A, S, "student_pomodoro"), (A, S, "student_pomodoro"), (A, S, "student_pomodoro")), | |
| 77 | + "work.self": _matrix((D, None, None), (D, None, None), (A, O, "work"), (A, O, "work"), (A, O, "work")), | |
| 78 | + "work.manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "staff_work"), (A, S, "staff_work")), | |
| 79 | + "school.settings_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "school_settings"), (A, S, "school_settings")), | |
| 80 | + "school.terms_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "school_terms"), (A, S, "school_terms")), | |
| 81 | + "users.roles_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (D, None, None), (A, S, "admin_users")), | |
| 82 | +} | |
| 83 | + | |
| 84 | +_ACTION_BY_INTENT: Final[dict[str, str]] = { | |
| 85 | + "greeting": "platform.help", | |
| 86 | + "smalltalk": "platform.help", | |
| 87 | + "thanks": "platform.help", | |
| 88 | + "farewell": "platform.help", | |
| 89 | + "bot_identity": "platform.help", | |
| 90 | + "platform_info": "platform.help", | |
| 91 | + "help_capabilities": "platform.help", | |
| 92 | + "guide_info": "platform.help", | |
| 93 | + "login_how": "platform.help", | |
| 94 | + "register_how": "platform.help", | |
| 95 | + "logout_how": "account.self", | |
| 96 | + "session_info": "account.self", | |
| 97 | + "account_access_problem": "platform.help", | |
| 98 | + "profile_edit": "account.self", | |
| 99 | + "language_theme": "account.self", | |
| 100 | + "roles_permissions": "platform.help", | |
| 101 | + "access_denied_help": "platform.help", | |
| 102 | + "navigation_help": "platform.help", | |
| 103 | + "course_view": "courses.view", | |
| 104 | + "course_create": "courses.create", | |
| 105 | + "course_enroll_student": "courses.enroll_student", | |
| 106 | + "course_remove_student": "courses.manage", | |
| 107 | + "lesson_session_add": "courses.manage", | |
| 108 | + "roll_call": "courses.manage", | |
| 109 | + "exam_modes_info": "platform.help", | |
| 110 | + "exam_create": "exams.manage", | |
| 111 | + "exam_add_question": "exams.manage", | |
| 112 | + "exam_enter_room": "exams.take", | |
| 113 | + "exam_save_answer": "exams.take", | |
| 114 | + "exam_finish_result": "exams.take", | |
| 115 | + "exam_rejoin_retake": "exams.take", | |
| 116 | + "exam_grade_student": "exams.manage", | |
| 117 | + "exam_live_monitor": "exams.manage", | |
| 118 | + "report_card_view": "reports.read_own", | |
| 119 | + "weighted_average_info": "platform.help", | |
| 120 | + "student_marks_lookup": "reports.observe_student", | |
| 121 | + "attendance_view": "reports.read_own", | |
| 122 | + "attendance_rate_info": "platform.help", | |
| 123 | + "event_attendance_mark": "events.mark_attendance", | |
| 124 | + "student_attendance_lookup": "reports.observe_student", | |
| 125 | + "event_create": "events.create", | |
| 126 | + "note_create": "notes.use", | |
| 127 | + "work_checkin_out": "work.self", | |
| 128 | + "staff_work_manage": "work.manage", | |
| 129 | + "term_manage": "school.terms_manage", | |
| 130 | + "school_settings": "school.settings_manage", | |
| 131 | + "user_role_change": "users.roles_manage", | |
| 132 | + "privacy_security": "platform.help", | |
| 133 | + "pomodoro_use": "pomodoro.start", | |
| 134 | + "student_pomodoro_lookup": "pomodoro.observe_student", | |
| 135 | + "messages_use": "messages.use", | |
| 136 | + "study_club_info": "platform.help", | |
| 137 | + "parent_info": "platform.help", | |
| 138 | +} | |
| 139 | + | |
| 140 | +_OWN_REPORT_RESPONSES: Final[dict[str, str]] = { | |
| 141 | + "veli": ( | |
| 142 | + "Veli hesabının kendi öğrenci karnesi veya yoklama kaydı yoktur. Bağlı bir " | |
| 143 | + "çocuğun kaydını soruyorsan bunu açıkça belirt; erişim yalnız doğrulanmış " | |
| 144 | + "veli–öğrenci bağlantısıyla mümkündür." | |
| 145 | + ), | |
| 146 | + "ogretmen": ( | |
| 147 | + "Öğretmen hesabının kendi öğrenci karnesi/yoklama raporu yerine, yalnız " | |
| 148 | + "yönettiğin derslerdeki öğrencilerin raporlarını görüntüleme kapsamı vardır. " | |
| 149 | + "Hangi öğrenciyi ve dersi kastettiğini belirtmelisin." | |
| 150 | + ), | |
| 151 | + "yonetici": ( | |
| 152 | + "Yönetici hesabında kişisel öğrenci karnesi yerine okul kapsamındaki öğrenci " | |
| 153 | + "raporları yönetim ekranlarından görüntülenir. Hangi öğrenciyi kastettiğini belirt." | |
| 154 | + ), | |
| 155 | + "admin": ( | |
| 156 | + "ADMIN hesabında kişisel öğrenci karnesi yerine okul kapsamındaki öğrenci " | |
| 157 | + "raporları görüntülenir. Hangi öğrenciyi kastettiğini belirt." | |
| 158 | + ), | |
| 159 | +} | |
| 160 | + | |
| 161 | +def action_id_for_intent(intent: str) -> str: | |
| 162 | + return _ACTION_BY_INTENT[intent] | |
| 163 | + | |
| 164 | + | |
| 165 | +def _local_rule(item: dict, role: str): | |
| 166 | + action_id = action_id_for_intent(item["intent"]) | |
| 167 | + if role == "ziyaretci": | |
| 168 | + if item["auth_required"]: | |
| 169 | + return action_id, D, None, None | |
| 170 | + return action_id, A, G, None | |
| 171 | + outcome, scope, route_key = _ACTION_RULES[action_id][role] | |
| 172 | + return action_id, outcome, scope, route_key | |
| 173 | + | |
| 174 | + | |
| 175 | +def _deny_text(reason: ReasonCode) -> str: | |
| 176 | + """Ret metni. Ayrıcalıklı adım, rota veya gerekli-rol adı ASLA sızmaz. | |
| 177 | + | |
| 178 | + Giriş gereken durumda (ziyaretçi) yalnız kamuya açık `/login` yolu verilir — | |
| 179 | + bu bir sızıntı değil, herkesin erişebildiği giriş sayfasıdır. | |
| 180 | + """ | |
| 181 | + | |
| 182 | + if reason is ReasonCode.AUTHENTICATION_REQUIRED: | |
| 183 | + return ( | |
| 184 | + "Bu konu için önce giriş yapman gerekiyor. `/login` sayfasından " | |
| 185 | + "güvenli biçimde giriş yapabilirsin." | |
| 186 | + ) | |
| 187 | + return ( | |
| 188 | + "Bu işlem senin rolünde yapılamıyor. Yetkisiz işlem adımları ve " | |
| 189 | + "yönlendirme paylaşılmadı." | |
| 190 | + ) | |
| 191 | + | |
| 192 | + | |
| 193 | +def _view(item: dict, role: str) -> RoleIntentView: | |
| 194 | + action_id, outcome, scope, route_key = _local_rule(item, role) | |
| 195 | + if outcome is D: | |
| 196 | + reason = ( | |
| 197 | + ReasonCode.AUTHENTICATION_REQUIRED | |
| 198 | + if role == "ziyaretci" and item["auth_required"] | |
| 199 | + else ReasonCode.ROLE_NOT_PERMITTED | |
| 200 | + ) | |
| 201 | + body = _deny_text(reason) | |
| 202 | + scope = None | |
| 203 | + route_key = None | |
| 204 | + else: # ALLOW | |
| 205 | + reason = ReasonCode.ALLOWED | |
| 206 | + body = item["response_template"] | |
| 207 | + # Karne/yoklama sayfası öğrenciye özeldir; üst roller için kişisel karne | |
| 208 | + # yerine kapsam notu döndürülür (adım değil, bilgi). | |
| 209 | + if item["intent"] in {"report_card_view", "attendance_view"} and role != "ogrenci": | |
| 210 | + body = _OWN_REPORT_RESPONSES.get(role, body) | |
| 211 | + | |
| 212 | + return RoleIntentView( | |
| 213 | + role=role, | |
| 214 | + intent=item["intent"], | |
| 215 | + action_id=action_id, | |
| 216 | + outcome=outcome, | |
| 217 | + scope=scope, | |
| 218 | + reason_code=reason, | |
| 219 | + response_id=item["response_id"], | |
| 220 | + response_template=body, | |
| 221 | + examples=tuple(item["example_questions"]), | |
| 222 | + clarification=None, | |
| 223 | + # Sözleşme metadata'sı (frontend butonu pasifleştirmek için kullanabilir); | |
| 224 | + # kullanıcıya dönen METİN ayrıcalıklı rol adını/adımı ASLA içermez. | |
| 225 | + required_role=item["min_role"] if outcome is D else None, | |
| 226 | + route_key=route_key if outcome is A else None, | |
| 227 | + route_label=None, | |
| 228 | + ) | |
| 229 | + | |
| 230 | + | |
| 231 | +def _hash_views(role: str, views: dict[str, RoleIntentView]) -> str: | |
| 232 | + manifest = [ | |
| 233 | + { | |
| 234 | + "view": view.view_id, | |
| 235 | + "action": view.action_id, | |
| 236 | + "outcome": view.outcome.value, | |
| 237 | + "scope": view.scope.value if view.scope else None, | |
| 238 | + "route": view.route_key, | |
| 239 | + } | |
| 240 | + for view in views.values() | |
| 241 | + ] | |
| 242 | + raw = json.dumps( | |
| 243 | + {"version": ROLE_SPACE_VERSION, "role": role, "views": manifest}, | |
| 244 | + ensure_ascii=False, | |
| 245 | + sort_keys=True, | |
| 246 | + separators=(",", ":"), | |
| 247 | + ).encode("utf-8") | |
| 248 | + return hashlib.sha256(raw).hexdigest() | |
| 249 | + | |
| 250 | + | |
| 251 | +@lru_cache(maxsize=len(ROLE_HIERARCHY)) | |
| 252 | +def get_role_space(role: str) -> CompiledRoleSpace: | |
| 253 | + if role not in ROLE_HIERARCHY: | |
| 254 | + raise KeyError(f"bilinmeyen rol uzayı: {role!r}") | |
| 255 | + views = {item["intent"]: _view(item, role) for item in INTENTS} | |
| 256 | + content_hash = _hash_views(role, views) | |
| 257 | + space_id = f"{ROLE_SPACE_VERSION}:{role}:{content_hash[:12]}" | |
| 258 | + examples = [ | |
| 259 | + (view.intent, question) | |
| 260 | + for view in views.values() | |
| 261 | + for question in view.examples | |
| 262 | + ] | |
| 263 | + return CompiledRoleSpace( | |
| 264 | + role=role, | |
| 265 | + version=ROLE_SPACE_VERSION, | |
| 266 | + content_hash=content_hash, | |
| 267 | + views=CompiledRoleSpace.immutable_views(views), | |
| 268 | + rule_matcher=RuleMatcher(set(views), space_id=space_id), | |
| 269 | + similarity_matcher=SimilarityMatcher(examples, space_id=space_id), | |
| 270 | + domain_vocab=frozenset(build_domain_vocab(question for _, question in examples)), | |
| 271 | + ) | |
| 272 | + | |
| 273 | + | |
| 274 | +def validate_role_spaces() -> None: | |
| 275 | + expected = {item["intent"] for item in INTENTS} | |
| 276 | + if set(_ACTION_BY_INTENT) != expected: | |
| 277 | + missing = expected - set(_ACTION_BY_INTENT) | |
| 278 | + extra = set(_ACTION_BY_INTENT) - expected | |
| 279 | + raise ValueError(f"intent/action eşlemesi eksik={missing}, fazla={extra}") | |
| 280 | + ids: set[str] = set() | |
| 281 | + for role in ROLE_HIERARCHY: | |
| 282 | + space = get_role_space(role) | |
| 283 | + if set(space.views) != expected: | |
| 284 | + raise ValueError(f"{role}: eksik/fazla intent görünümü") | |
| 285 | + if space.space_id in ids: | |
| 286 | + raise ValueError(f"{role}: rol uzayı kimliği benzersiz değil") | |
| 287 | + ids.add(space.space_id) | |
| 288 | + if any(view.role != role for view in space.views.values()): | |
| 289 | + raise ValueError(f"{role}: başka role ait görünüm sızdı") | |
| 290 | + | |
| 291 | + | |
| 292 | +validate_role_spaces() |
src/rules.pymodified+59 -36
| @@ -277,6 +277,7 @@ class RuleMatch: | ||
| 277 | 277 | score: int |
| 278 | 278 | matched: tuple[str, ...] |
| 279 | 279 | reason: str |
| 280 | + space_id: str | None = None | |
| 280 | 281 | |
| 281 | 282 | |
| 282 | 283 | def _present(keyword: str, tokens: list[str]) -> bool: |
| @@ -295,41 +296,63 @@ def _group_matches(group: _Group, tokens: list[str]) -> bool: | ||
| 295 | 296 | return True |
| 296 | 297 | |
| 297 | 298 | |
| 298 | -def match(query: str) -> RuleMatch | None: | |
| 299 | - """Soruyu kural katmanından geçirir. | |
| 299 | +class RuleMatcher: | |
| 300 | + """A rule index compiled for one closed intent space.""" | |
| 301 | + | |
| 302 | + def __init__( | |
| 303 | + self, | |
| 304 | + intent_names: set[str] | frozenset[str] | None = None, | |
| 305 | + *, | |
| 306 | + space_id: str | None = None, | |
| 307 | + ) -> None: | |
| 308 | + allowed = None if intent_names is None else frozenset(intent_names) | |
| 309 | + self._rules = tuple( | |
| 310 | + rule for rule in _RULES if allowed is None or rule.intent in allowed | |
| 311 | + ) | |
| 312 | + self.space_id = space_id | |
| 313 | + | |
| 314 | + def match(self, query: str) -> RuleMatch | None: | |
| 315 | + """Soruyu bu derlenmiş kural uzayından geçirir. | |
| 300 | 316 | |
| 301 | - Returns: | |
| 302 | 317 | Tek bir intent en yüksek özgüllükle eşleşirse RuleMatch; hiçbir kural |
| 303 | - eşleşmezse veya birden çok intent aynı en yüksek skorda eşleşirse (belirsiz) | |
| 304 | - None. | |
| 305 | - """ | |
| 306 | - | |
| 307 | - tokens = folded_tokens(query) | |
| 308 | - if not tokens: | |
| 309 | - return None | |
| 310 | - | |
| 311 | - best_by_intent: dict[str, tuple[int, tuple[str, ...]]] = {} | |
| 312 | - for rule in _RULES: | |
| 313 | - for group in rule.groups: | |
| 314 | - if _group_matches(group, tokens): | |
| 315 | - score = len(group.all_kw) | |
| 316 | - prev = best_by_intent.get(rule.intent) | |
| 317 | - if prev is None or score > prev[0]: | |
| 318 | - best_by_intent[rule.intent] = (score, group.all_kw) | |
| 319 | - | |
| 320 | - if not best_by_intent: | |
| 321 | - return None | |
| 322 | - | |
| 323 | - ranked = sorted(best_by_intent.items(), key=lambda kv: kv[1][0], reverse=True) | |
| 324 | - top_intent, (top_score, matched) = ranked[0] | |
| 325 | - | |
| 326 | - # Belirsizlik: aynı en yüksek skorda birden çok intent -> karar verme. | |
| 327 | - if len(ranked) > 1 and ranked[1][1][0] == top_score: | |
| 328 | - return None | |
| 329 | - | |
| 330 | - return RuleMatch( | |
| 331 | - intent=top_intent, | |
| 332 | - score=top_score, | |
| 333 | - matched=matched, | |
| 334 | - reason=f"kural: {top_intent} <- {list(matched)}", | |
| 335 | - ) | |
| 318 | + eşleşmezse veya eşitlik varsa None döner. | |
| 319 | + """ | |
| 320 | + | |
| 321 | + tokens = folded_tokens(query) | |
| 322 | + if not tokens: | |
| 323 | + return None | |
| 324 | + | |
| 325 | + best_by_intent: dict[str, tuple[int, tuple[str, ...]]] = {} | |
| 326 | + for rule in self._rules: | |
| 327 | + for group in rule.groups: | |
| 328 | + if _group_matches(group, tokens): | |
| 329 | + score = len(group.all_kw) | |
| 330 | + prev = best_by_intent.get(rule.intent) | |
| 331 | + if prev is None or score > prev[0]: | |
| 332 | + best_by_intent[rule.intent] = (score, group.all_kw) | |
| 333 | + | |
| 334 | + if not best_by_intent: | |
| 335 | + return None | |
| 336 | + | |
| 337 | + ranked = sorted(best_by_intent.items(), key=lambda kv: kv[1][0], reverse=True) | |
| 338 | + top_intent, (top_score, matched) = ranked[0] | |
| 339 | + | |
| 340 | + if len(ranked) > 1 and ranked[1][1][0] == top_score: | |
| 341 | + return None | |
| 342 | + | |
| 343 | + return RuleMatch( | |
| 344 | + intent=top_intent, | |
| 345 | + score=top_score, | |
| 346 | + matched=matched, | |
| 347 | + reason=f"kural: {top_intent} <- {list(matched)}", | |
| 348 | + space_id=self.space_id, | |
| 349 | + ) | |
| 350 | + | |
| 351 | + | |
| 352 | +_DEFAULT_RULE_MATCHER: Final[RuleMatcher] = RuleMatcher() | |
| 353 | + | |
| 354 | + | |
| 355 | +def match(query: str) -> RuleMatch | None: | |
| 356 | + """Geriye uyumlu global kural API'si.""" | |
| 357 | + | |
| 358 | + return _DEFAULT_RULE_MATCHER.match(query) |
src/similarity.pymodified+7 -1
| @@ -62,6 +62,9 @@ def char_ngrams(text: str, ns: Iterable[int] = DEFAULT_NGRAMS) -> Counter[str]: | ||
| 62 | 62 | class ScoredIntent: |
| 63 | 63 | intent: str |
| 64 | 64 | score: float |
| 65 | + # The compiled role-space that produced this candidate. ``None`` is kept | |
| 66 | + # for callers constructing legacy test doubles by hand. | |
| 67 | + space_id: str | None = None | |
| 65 | 68 | |
| 66 | 69 | |
| 67 | 70 | @runtime_checkable |
| @@ -82,11 +85,14 @@ class SimilarityMatcher: | ||
| 82 | 85 | examples: list[tuple[str, str]], |
| 83 | 86 | ns: Iterable[int] = DEFAULT_NGRAMS, |
| 84 | 87 | word_weight: int = DEFAULT_WORD_WEIGHT, |
| 88 | + *, | |
| 89 | + space_id: str | None = None, | |
| 85 | 90 | ) -> None: |
| 86 | 91 | """examples: (intent, question) çiftleri.""" |
| 87 | 92 | |
| 88 | 93 | self._ns = tuple(ns) |
| 89 | 94 | self._word_weight = word_weight |
| 95 | + self._space_id = space_id | |
| 90 | 96 | self._intents: list[str] = [] |
| 91 | 97 | self._doc_tfs: list[Counter[str]] = [] |
| 92 | 98 | |
| @@ -175,7 +181,7 @@ class SimilarityMatcher: | ||
| 175 | 181 | best[intent] = score |
| 176 | 182 | |
| 177 | 183 | return [ |
| 178 | - ScoredIntent(intent, score) | |
| 184 | + ScoredIntent(intent, score, self._space_id) | |
| 179 | 185 | for intent, score in sorted(best.items(), key=lambda kv: kv[1], reverse=True) |
| 180 | 186 | ] |
| 181 | 187 |
tests/e2e/test_behavior_matrix.pymodified+19 -9
| @@ -140,8 +140,9 @@ GATING_MATRIX: list[tuple[str, str, str | None, bool | None]] = [ | ||
| 140 | 140 | ("okul ayarlarını değiştirmek istiyorum", "ogretmen", "role_insufficient", False), |
| 141 | 141 | ("okul ayarlarını değiştirmek istiyorum", "yonetici", None, True), |
| 142 | 142 | # Veli: salt-okunur gözlemci — öğrenci işlemleri yapamaz, Mesajlar'a erişir. |
| 143 | - ("sınav odasına nasıl girerim", "veli", "role_insufficient", False), | |
| 144 | - ("pomodoro oturumu nasıl açılır", "veli", "role_insufficient", False), | |
| 143 | + ("sınav odasına nasıl girerim", "veli", "role_insufficient", None), | |
| 144 | + # Pomodoro backend'de her doğrulanmış kullanıcıya açık -> veli de yapabilir. | |
| 145 | + ("pomodoro oturumu nasıl açılır", "veli", None, True), | |
| 145 | 146 | ("mesajlarım nerede", "veli", None, True), |
| 146 | 147 | ] |
| 147 | 148 | |
| @@ -154,14 +155,23 @@ class RoleGatingMatrixTests(unittest.TestCase): | ||
| 154 | 155 | with self.subTest(query=query, role=role): |
| 155 | 156 | resp = ask(query, role) |
| 156 | 157 | self.assertEqual(resp["auth_action"], auth_action) |
| 157 | - if nav_available is not None and resp["navigation"] is not None: | |
| 158 | - self.assertEqual(resp["navigation"]["available"], nav_available) | |
| 159 | - | |
| 160 | - def test_role_insufficient_response_still_shows_steps(self) -> None: | |
| 161 | - # Tasarım kararı: yetki yetmese de adımlar gösterilir + kibar uyarı eklenir. | |
| 158 | + if auth_action is None: | |
| 159 | + # İzinli: gerçek sayfaya aktif yönlendirme. | |
| 160 | + self.assertIsNotNone(resp["navigation"]) | |
| 161 | + self.assertTrue(resp["navigation"]["available"]) | |
| 162 | + else: | |
| 163 | + # Reddedildi: no-leak -> rota sızdırılmaz (None). | |
| 164 | + self.assertIsNone(resp["navigation"]) | |
| 165 | + | |
| 166 | + def test_role_insufficient_hides_steps_and_route(self) -> None: | |
| 167 | + # No-leak kararı: yetki yetmiyorsa adımlar, rota ve ayrıcalıklı rol adı | |
| 168 | + # GÖSTERİLMEZ; yalnız kibar bir ret döner (öğrenci -> öğretmen adımı sızmaz). | |
| 162 | 169 | resp = ask("sınav oluşturmak istiyorum", "ogrenci") |
| 163 | - self.assertIn("Öğretmen", resp["text"]) | |
| 164 | - self.assertEqual(resp["response_id"], "exam_create_instructions") | |
| 170 | + self.assertEqual(resp["auth_action"], "role_insufficient") | |
| 171 | + self.assertIsNone(resp["navigation"]) | |
| 172 | + self.assertNotIn("Sınav oluştur", resp["text"]) # buton/adım imzası | |
| 173 | + self.assertNotIn("Ders seç", resp["text"]) | |
| 174 | + self.assertNotIn("Öğretmen", resp["text"]) # ayrıcalıklı rol adı | |
| 165 | 175 | |
| 166 | 176 | |
| 167 | 177 | # ============================================================================= |
tests/e2e/test_conversation.pymodified+3 -1
| @@ -1304,7 +1304,9 @@ class RoleScenarios(unittest.TestCase): | ||
| 1304 | 1304 | r = answer("yeni ders oluştur", role="ogrenci", authenticated=True) |
| 1305 | 1305 | self.assertEqual(r.response_id, "course_create_instructions") |
| 1306 | 1306 | self.assertEqual(r.auth_action, "role_insufficient") |
| 1307 | - self.assertIn("Öğretmen", r.text) | |
| 1307 | + # No-leak: adımlar ve ayrıcalıklı rol adı cevap metninde GÖSTERİLMEZ. | |
| 1308 | + self.assertNotIn("Öğretmen", r.text) | |
| 1309 | + self.assertNotIn("Yeni ders", r.text) | |
| 1308 | 1310 | |
| 1309 | 1311 | def test_teacher_can_create_course(self) -> None: |
| 1310 | 1312 | r = answer("yeni ders oluştur", role="ogretmen", authenticated=True) |
tests/e2e/test_role_isolation.pyadded+106 -0
| @@ -0,0 +1,106 @@ | ||
| 1 | +"""Rol izolasyonu sözleşmesi: her rolün AYRI cevap uzayı. | |
| 2 | + | |
| 3 | +Bu dosya kullanıcının çekirdek şartını sabitler: | |
| 4 | + 1) Nerede ne cevap veriliyor — izinli rol adımları görür. | |
| 5 | + 2) Bir rolün cevabı diğerine SIZMAZ — düşük rol, ayrıcalıklı bir işlemi | |
| 6 | + sorunca adım/rota/ayrıcalıklı-rol-adı ASLA görmez (yalnız kibar ret). | |
| 7 | + 3) Bilmiyorsa — kapsam dışı/belirsiz sorguda "anlayamadım, bunu mu demek | |
| 8 | + istedin?" + aynı rol uzayından öneriler döner. | |
| 9 | + | |
| 10 | +Model ikili: ALLOW (adım + yönlendirme) / DENY (kibar ret, sızıntı yok). | |
| 11 | +Kapsam (kendi/yönetilen/bağlı) cevabın içinde nottur, ayrı bir outcome değildir. | |
| 12 | +""" | |
| 13 | + | |
| 14 | +import unittest | |
| 15 | + | |
| 16 | +from src.engine import Engine | |
| 17 | + | |
| 18 | + | |
| 19 | +ENGINE = Engine() | |
| 20 | + | |
| 21 | + | |
| 22 | +def ask(query: str, role: str) -> dict: | |
| 23 | + return ENGINE.handle( | |
| 24 | + {"query": query, "session": {"role": role, "authenticated": role != "ziyaretci"}} | |
| 25 | + ) | |
| 26 | + | |
| 27 | + | |
| 28 | +# (sorgu, o işlemi YAPAMAYAN roller, YAPABİLEN bir rol) | |
| 29 | +CROSS_ROLE: list[tuple[str, list[str], str]] = [ | |
| 30 | + ("sınav oluşturmak istiyorum", ["ogrenci", "veli"], "ogretmen"), | |
| 31 | + ("kullanıcı rolünü değiştirmek istiyorum", ["ogrenci", "ogretmen", "yonetici"], "admin"), | |
| 32 | + ("okul ayarlarını değiştirmek istiyorum", ["ogrenci", "ogretmen"], "yonetici"), | |
| 33 | + ("personel mesailerini görmek istiyorum", ["ogrenci", "ogretmen"], "yonetici"), | |
| 34 | + ("bir öğrencinin karnesine bakmak istiyorum", ["ogrenci"], "ogretmen"), | |
| 35 | +] | |
| 36 | + | |
| 37 | +# Cevap gövdesinde ASLA görünmemesi gereken, o işlemin adımlarına/rotasına özgü | |
| 38 | +# imza ifadeler (sızıntı dedektörü). | |
| 39 | +STEP_SIGNATURES: dict[str, list[str]] = { | |
| 40 | + "sınav oluşturmak istiyorum": ["Sınav oluştur", "Ders seç", "/exams"], | |
| 41 | + "kullanıcı rolünü değiştirmek istiyorum": ["/admin/users", "rol menüsünden"], | |
| 42 | + "okul ayarlarını değiştirmek istiyorum": ["/management/settings", "Not bantları"], | |
| 43 | + "personel mesailerini görmek istiyorum": ["/management/staff-work", "Düzenle"], | |
| 44 | + "bir öğrencinin karnesine bakmak istiyorum": ["/management/student-marks"], | |
| 45 | +} | |
| 46 | + | |
| 47 | + | |
| 48 | +class CrossRoleIsolationTests(unittest.TestCase): | |
| 49 | + """Yasak rol: adım/rota/ayrıcalıklı-rol-adı sızmaz; izinli rol: gerçek adım+rota.""" | |
| 50 | + | |
| 51 | + def test_denied_role_gets_no_steps_or_route(self) -> None: | |
| 52 | + for query, forbidden_roles, _allowed in CROSS_ROLE: | |
| 53 | + for role in forbidden_roles: | |
| 54 | + with self.subTest(query=query, role=role): | |
| 55 | + resp = ask(query, role) | |
| 56 | + self.assertIsNotNone(resp["auth_action"]) # reddedildi | |
| 57 | + self.assertIsNone(resp["navigation"]) # rota sızmadı | |
| 58 | + for sig in STEP_SIGNATURES[query]: | |
| 59 | + self.assertNotIn(sig, resp["text"]) # adım/rota sızmadı | |
| 60 | + | |
| 61 | + def test_allowed_role_gets_steps_and_route(self) -> None: | |
| 62 | + for query, _forbidden, allowed in CROSS_ROLE: | |
| 63 | + with self.subTest(query=query, role=allowed): | |
| 64 | + resp = ask(query, allowed) | |
| 65 | + self.assertIsNone(resp["auth_action"]) # izinli | |
| 66 | + self.assertIsNotNone(resp["navigation"]) # yönlendirme var | |
| 67 | + | |
| 68 | + | |
| 69 | +# Ortak sorular: her rol uzayında bulunmalı (fallback değil, izinli). | |
| 70 | +COMMON_QUERIES = ["merhaba", "teşekkürler", "roller ve yetkiler nedir", "mesajlarım nerede"] | |
| 71 | + | |
| 72 | + | |
| 73 | +class CommonSpaceTests(unittest.TestCase): | |
| 74 | + """Ortak sorular her rol uzayında yanıtlanır (kopya-paste değil, derlenmiş).""" | |
| 75 | + | |
| 76 | + def test_common_questions_answered_in_every_role_space(self) -> None: | |
| 77 | + for role in ("veli", "ogrenci", "ogretmen", "yonetici", "admin"): | |
| 78 | + for query in COMMON_QUERIES: | |
| 79 | + with self.subTest(role=role, query=query): | |
| 80 | + resp = ask(query, role) | |
| 81 | + self.assertFalse(resp["fallback"]) | |
| 82 | + self.assertIsNone(resp["auth_action"]) | |
| 83 | + | |
| 84 | + | |
| 85 | +class OutOfScopeSuggestionTests(unittest.TestCase): | |
| 86 | + """Bilmiyorsa: 'anlayamadım, bunu mu?' + aynı uzaydan aday öneriler.""" | |
| 87 | + | |
| 88 | + def test_ambiguous_offers_clarification_with_candidates(self) -> None: | |
| 89 | + resp = ask("bir yerde hata verdi yardım et", "ogrenci") | |
| 90 | + self.assertEqual(resp["response_id"], "clarification_prompt") | |
| 91 | + self.assertIn("anlayamadım", resp["text"]) | |
| 92 | + clar = resp["clarification"] | |
| 93 | + self.assertIsNotNone(clar) | |
| 94 | + self.assertEqual(len(clar["candidates"]), 2) | |
| 95 | + for cand in clar["candidates"]: | |
| 96 | + self.assertTrue(cand["intent"]) | |
| 97 | + | |
| 98 | + def test_out_of_domain_falls_back_without_inventing(self) -> None: | |
| 99 | + for query in ["bugün hava nasıl", "dolar kaç lira"]: | |
| 100 | + with self.subTest(query=query): | |
| 101 | + resp = ask(query, "ogrenci") | |
| 102 | + self.assertTrue(resp["fallback"]) | |
| 103 | + | |
| 104 | + | |
| 105 | +if __name__ == "__main__": | |
| 106 | + unittest.main() |
tests/integration/test_engine.pymodified+6 -7
| @@ -67,12 +67,12 @@ class ContractTests(unittest.TestCase): | ||
| 67 | 67 | self.assertEqual(resp["navigation"]["route"], "/marks") |
| 68 | 68 | self.assertTrue(resp["navigation"]["available"]) |
| 69 | 69 | |
| 70 | - def test_navigation_unavailable_when_role_insufficient(self) -> None: | |
| 71 | - # Öğrenci sınav oluşturamaz -> route yine döner ama available=False. | |
| 70 | + def test_navigation_hidden_when_role_insufficient(self) -> None: | |
| 71 | + # No-leak: öğrenci sınav oluşturamaz -> ret; rota/route SIZDIRILMAZ (None). | |
| 72 | 72 | resp = self.engine.handle({"query": "sınav nasıl oluşturulur", |
| 73 | 73 | "session": {"role": "ogrenci", "authenticated": True}}) |
| 74 | - self.assertEqual(resp["navigation"]["route"], "/exams") | |
| 75 | - self.assertFalse(resp["navigation"]["available"]) | |
| 74 | + self.assertEqual(resp["auth_action"], "role_insufficient") | |
| 75 | + self.assertIsNone(resp["navigation"]) | |
| 76 | 76 | |
| 77 | 77 | def test_no_navigation_for_info_intent(self) -> None: |
| 78 | 78 | # Selamlama gibi sayfası olmayan intent -> navigation None. |
| @@ -170,12 +170,11 @@ class MultiIntentTests(unittest.TestCase): | ||
| 170 | 170 | self.assertIn("3)", resp["text"]) |
| 171 | 171 | |
| 172 | 172 | def test_each_answer_has_own_navigation_and_auth(self) -> None: |
| 173 | - # Öğrencide her parçanın kendi yetki durumu değerlendirilir. | |
| 173 | + # Öğrencide her parçanın kendi yetki durumu; ret'te rota SIZDIRILMAZ. | |
| 174 | 174 | resp = self._ask("sınav oluştur ve yoklama al", role="ogrenci") |
| 175 | 175 | for ans in resp["answers"]: |
| 176 | 176 | self.assertEqual(ans["auth_action"], "role_insufficient") |
| 177 | - self.assertIsNotNone(ans["navigation"]) | |
| 178 | - self.assertFalse(ans["navigation"]["available"]) | |
| 177 | + self.assertIsNone(ans["navigation"]) | |
| 179 | 178 | |
| 180 | 179 | def test_natural_ve_is_not_split(self) -> None: |
| 181 | 180 | # 'roller ve yetkiler nedir' TEK sorudur; parçalar kurala çarpmaz -> bölünmez. |
tests/unit/test_bridge.pymodified+3 -2
| @@ -62,9 +62,10 @@ class BridgeRoleContractTests(unittest.TestCase): | ||
| 62 | 62 | ) |
| 63 | 63 | |
| 64 | 64 | self.assertEqual(student["auth_action"], "role_insufficient") |
| 65 | - self.assertEqual(student["required_role"], "ogretmen") | |
| 66 | - self.assertFalse(student["navigation"]["available"]) | |
| 65 | + self.assertEqual(student["required_role"], "ogretmen") # sözleşme metadata'sı | |
| 66 | + self.assertIsNone(student["navigation"]) # no-leak: rota sızmaz | |
| 67 | 67 | self.assertIsNone(admin["auth_action"]) |
| 68 | + self.assertIsNotNone(admin["navigation"]) | |
| 68 | 69 | self.assertTrue(admin["navigation"]["available"]) |
| 69 | 70 | |
| 70 | 71 |
tests/unit/test_cli.pymodified+4 -2
| @@ -50,10 +50,12 @@ class HandleLineTests(unittest.TestCase): | ||
| 50 | 50 | def test_role_command_gating_effect(self) -> None: |
| 51 | 51 | self.session.handle_line("/rol ogrenci") |
| 52 | 52 | text, _ = self.session.handle_line("yeni ders oluştur") |
| 53 | - self.assertIn("Öğretmen", text) # rol yetersiz uyarısı | |
| 53 | + # No-leak: öğrenciye adım/ayrıcalıklı rol adı gösterilmez, kibar ret döner. | |
| 54 | + self.assertNotIn("Öğretmen", text) | |
| 55 | + self.assertNotIn("Yeni ders", text) | |
| 54 | 56 | self.session.handle_line("/rol ogretmen") |
| 55 | 57 | text2, _ = self.session.handle_line("yeni ders oluştur") |
| 56 | - self.assertNotIn("yetmiyor", text2) # artık izin var | |
| 58 | + self.assertIn("Yeni ders", text2) # öğretmende gerçek adımlar döner | |
| 57 | 59 | |
| 58 | 60 | def test_roles_command(self) -> None: |
| 59 | 61 | text, _ = self.session.handle_line("/roller") |
tests/unit/test_responder.pymodified+5 -3
| @@ -41,13 +41,15 @@ class RenderTests(unittest.TestCase): | ||
| 41 | 41 | r = render(_decision("report_card_view", auth_action=LOGIN_REQUIRED, required_role="ogrenci")) |
| 42 | 42 | self.assertEqual(r.response_id, "report_card_info") |
| 43 | 43 | self.assertIn("/login", r.text) |
| 44 | - # Gövde de korunmalı. | |
| 45 | - self.assertIn("Karnem", r.text) | |
| 44 | + # No-leak: giriş istenir; adımlar (Karnem içeriği) GÖSTERİLMEZ. | |
| 45 | + self.assertNotIn("Karnem", r.text) | |
| 46 | 46 | |
| 47 | 47 | def test_role_insufficient_prefix(self) -> None: |
| 48 | 48 | r = render(_decision("course_create", auth_action=ROLE_INSUFFICIENT, required_role="ogretmen")) |
| 49 | - self.assertIn("Öğretmen", r.text) | |
| 50 | 49 | self.assertEqual(r.response_id, "course_create_instructions") |
| 50 | + # No-leak: adımlar ve ayrıcalıklı rol adı GÖSTERİLMEZ. | |
| 51 | + self.assertNotIn("Öğretmen", r.text) | |
| 52 | + self.assertNotIn("Yeni ders", r.text) | |
| 51 | 53 | |
| 52 | 54 | def test_response_id_stable_under_gating(self) -> None: |
| 53 | 55 | plain = render(_decision("course_create")) |