V2 kapalı per-rol uzay altyapısı (foundation/WIP)
Browse files at this commit44249ab7ca36dfd3ff8a161cb94ed8ad002f9646Parent: b6ccb68- feat
- V2 kapalı per-rol uzay altyapısı (foundation/WIP)
9 changed files +698 -135
- src/access.py +92 -0
- src/decision.py +51 -47
- src/domain.py +16 -6
- src/engine.py +115 -29
- src/observability.py +44 -4
- src/responder.py +15 -12
- src/role_spaces.py +299 -0
- src/rules.py +59 -36
- src/similarity.py +7 -1
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/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+115 -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,100 @@ 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: | |
| 188 | + return None | |
| 189 | + view = get_role_space(role).view_for(intent) | |
| 190 | + if view is None or view.outcome is not AccessOutcome.ALLOW or view.route_key is None: | |
| 181 | 191 | return None |
| 182 | 192 | route = route_for(intent) |
| 183 | 193 | if route is None: |
| 184 | 194 | return None |
| 185 | 195 | path, label = route |
| 186 | - return {"route": path, "label": label, "available": auth_action is None} | |
| 196 | + return {"route": path, "label": label, "available": True} | |
| 197 | + | |
| 198 | + | |
| 199 | +_WIRE_ROLES: dict[str, str] = { | |
| 200 | + "ziyaretci": "visitor", | |
| 201 | + "veli": "parent", | |
| 202 | + "ogrenci": "student", | |
| 203 | + "ogretmen": "teacher", | |
| 204 | + "yonetici": "manager", | |
| 205 | + "admin": "admin", | |
| 206 | +} | |
| 207 | + | |
| 208 | + | |
| 209 | +def assistant_meta_from_result(result: dict[str, Any], role: str) -> dict[str, Any]: | |
| 210 | + """Build the role-space V2 metadata from one engine result. | |
| 211 | + | |
| 212 | + The legacy engine response remains intact; bridge V2 puts this metadata next | |
| 213 | + to ``text`` on the wire. | |
| 214 | + """ | |
| 215 | + | |
| 216 | + space = get_role_space(role) | |
| 217 | + intent = result.get("intent") | |
| 218 | + view = space.view_for(intent) if isinstance(intent, str) else None | |
| 219 | + response_id = result.get("response_id") | |
| 220 | + if response_id == "clarification_prompt": | |
| 221 | + outcome = "clarify" | |
| 222 | + reason_code = "ambiguous_query" | |
| 223 | + elif bool(result.get("fallback")): | |
| 224 | + outcome = "fallback" | |
| 225 | + reason_code = "out_of_scope" | |
| 226 | + elif result.get("auth_action") is not None: | |
| 227 | + outcome = "deny" | |
| 228 | + reason_code = view.reason_code.value if view else "role_not_permitted" | |
| 229 | + elif isinstance(response_id, str) and response_id.startswith("safety_"): | |
| 230 | + outcome = "deny" | |
| 231 | + safety = result.get("safety") or {} | |
| 232 | + reason_code = "safety_" + str(safety.get("category", "blocked")).lower() | |
| 233 | + else: | |
| 234 | + outcome = "allow" | |
| 235 | + reason_code = view.reason_code.value if view else "allowed" | |
| 236 | + | |
| 237 | + navigation = None | |
| 238 | + if outcome == "allow" and view is not None and view.route_key is not None: | |
| 239 | + navigation = {"route_key": view.route_key} | |
| 240 | + if view.route_label: | |
| 241 | + navigation["label"] = view.route_label | |
| 242 | + | |
| 243 | + clarification = None | |
| 244 | + existing_clarification = result.get("clarification") | |
| 245 | + if outcome == "clarify" and isinstance(existing_clarification, dict): | |
| 246 | + options = [ | |
| 247 | + str(candidate.get("intent")) | |
| 248 | + for candidate in existing_clarification.get("candidates", []) | |
| 249 | + if isinstance(candidate, dict) and candidate.get("intent") | |
| 250 | + ] | |
| 251 | + clarification = {"prompt": CLARIFICATION_PROMPT_TEXT, "options": options} | |
| 252 | + | |
| 253 | + return { | |
| 254 | + "contract_version": 2, | |
| 255 | + "served_role": _WIRE_ROLES[role], | |
| 256 | + "role_space_version": space.version, | |
| 257 | + "role_space_hash": space.content_hash, | |
| 258 | + "outcome": outcome, | |
| 259 | + "action_id": intent, | |
| 260 | + "reason_code": reason_code, | |
| 261 | + "navigation": navigation, | |
| 262 | + "clarification": clarification, | |
| 263 | + "suggestions": list(result.get("suggestions") or []), | |
| 264 | + } | |
| 265 | + | |
| 266 | + | |
| 267 | +def _attach_assistant_meta(result: dict[str, Any], role: str) -> dict[str, Any]: | |
| 268 | + result["assistant_meta"] = assistant_meta_from_result(result, role) | |
| 269 | + return result | |
| 187 | 270 | |
| 188 | 271 | |
| 189 | 272 | def _build_clarification(trace: dict[str, Any], *, force: bool = False) -> dict[str, Any] | None: |
| @@ -323,7 +406,9 @@ class Engine: | ||
| 323 | 406 | log_sink: LogSink | None = None, |
| 324 | 407 | rate_limiter: "safety_mod.RateLimiter | None" = None, |
| 325 | 408 | ) -> None: |
| 326 | - self._matcher = matcher or get_default_matcher() | |
| 409 | + # ``None`` means role-local default. A custom matcher is retained for | |
| 410 | + # tests/opt-in embedding and projected into the selected space later. | |
| 411 | + self._matcher = matcher | |
| 327 | 412 | self._log_sink = log_sink |
| 328 | 413 | self._rate_limiter = rate_limiter |
| 329 | 414 | |
| @@ -368,7 +453,7 @@ class Engine: | ||
| 368 | 453 | "authenticated": authenticated, "short_circuit": "empty_query", |
| 369 | 454 | "response_id": FALLBACK["response_id"], |
| 370 | 455 | }) |
| 371 | - return empty | |
| 456 | + return _attach_assistant_meta(empty, role) | |
| 372 | 457 | |
| 373 | 458 | # 0) Rate-limit / spam (opsiyonel; user_id gerekir). |
| 374 | 459 | if self._rate_limiter is not None and user_id: |
| @@ -376,7 +461,7 @@ class Engine: | ||
| 376 | 461 | if limited is not None: |
| 377 | 462 | if self._log_sink is not None: |
| 378 | 463 | self._log_sink(_safety_trace(trace_id, query, role, authenticated, limited)) |
| 379 | - return { | |
| 464 | + return _attach_assistant_meta({ | |
| 380 | 465 | "trace_id": trace_id, |
| 381 | 466 | "response_id": "safety_" + limited.category.lower(), |
| 382 | 467 | "text": limited.user_message, |
| @@ -390,7 +475,7 @@ class Engine: | ||
| 390 | 475 | "answers": None, |
| 391 | 476 | "suggestions": suggestions, |
| 392 | 477 | "safety": _safety_info(limited), |
| 393 | - } | |
| 478 | + }, role) | |
| 394 | 479 | |
| 395 | 480 | # 1) İçerik-güvenliği giriş kapısı. |
| 396 | 481 | safety = safety_mod.evaluate_input(query, role=role, authenticated=authenticated) |
| @@ -399,7 +484,7 @@ class Engine: | ||
| 399 | 484 | if safety.decision in safety_mod.BLOCKING_DECISIONS: |
| 400 | 485 | if self._log_sink is not None: |
| 401 | 486 | self._log_sink(_safety_trace(trace_id, query, role, authenticated, safety)) |
| 402 | - return { | |
| 487 | + return _attach_assistant_meta({ | |
| 403 | 488 | "trace_id": trace_id, |
| 404 | 489 | "response_id": "safety_" + safety.category.lower(), |
| 405 | 490 | "text": safety.user_message, |
| @@ -413,23 +498,25 @@ class Engine: | ||
| 413 | 498 | "answers": None, |
| 414 | 499 | "suggestions": suggestions, |
| 415 | 500 | "safety": safety_info, |
| 416 | - } | |
| 501 | + }, role) | |
| 417 | 502 | |
| 418 | 503 | # 1.5) Rol beyanı ("Öğrenci", "ben öğretmenim") -> role özel yetenek özeti. |
| 419 | 504 | # Bot 'rolünü söyle' dediğinde verilen tek kelimelik cevabı anlamlandırır; |
| 420 | 505 | # aksi hâlde 'Öğrenci' yanlışlıkla 'öğrenci kaydet' intent'ine benzerdi. |
| 421 | 506 | declared = _declared_role(query) |
| 422 | - caps = capabilities_for(declared) if declared else None | |
| 507 | + served_declaration = role if (authenticated and declared) else declared | |
| 508 | + caps = capabilities_for(served_declaration) if served_declaration else None | |
| 423 | 509 | if caps: |
| 424 | 510 | if self._log_sink is not None: |
| 425 | 511 | self._log_sink({ |
| 426 | 512 | "trace_id": trace_id, "query_masked": safety_mod.mask_pii(query)[0], "role": role, |
| 427 | 513 | "authenticated": authenticated, "short_circuit": "role_declaration", |
| 428 | - "declared_role": declared, "response_id": "role_capabilities_" + declared, | |
| 514 | + "declared_role": declared, "served_role": served_declaration, | |
| 515 | + "response_id": "role_capabilities_" + served_declaration, | |
| 429 | 516 | }) |
| 430 | - return { | |
| 517 | + return _attach_assistant_meta({ | |
| 431 | 518 | "trace_id": trace_id, |
| 432 | - "response_id": "role_capabilities_" + declared, | |
| 519 | + "response_id": "role_capabilities_" + served_declaration, | |
| 433 | 520 | "text": caps, |
| 434 | 521 | "intent": None, |
| 435 | 522 | "confidence": 1.0, |
| @@ -441,7 +528,7 @@ class Engine: | ||
| 441 | 528 | "answers": None, |
| 442 | 529 | "suggestions": suggestions, |
| 443 | 530 | "safety": safety_info, |
| 444 | - } | |
| 531 | + }, role) | |
| 445 | 532 | |
| 446 | 533 | # PII maskeleme: maskelenmiş sorguyu boru hattına ver. |
| 447 | 534 | effective_query = query |
| @@ -449,7 +536,7 @@ class Engine: | ||
| 449 | 536 | effective_query = safety.masked_message |
| 450 | 537 | |
| 451 | 538 | # 1.6) Çoklu istek ('X ve Y'): her bağımsız parça ayrı yanıtlanır. |
| 452 | - segments = _multi_intent_segments(effective_query) | |
| 539 | + segments = _multi_intent_segments(effective_query, role) | |
| 453 | 540 | if segments is not None: |
| 454 | 541 | answers: list[dict[str, Any]] = [] |
| 455 | 542 | parts: list[str] = [] |
| @@ -463,7 +550,9 @@ class Engine: | ||
| 463 | 550 | "response_id": seg_response.response_id, |
| 464 | 551 | "text": seg_response.text, |
| 465 | 552 | "auth_action": seg_response.auth_action, |
| 466 | - "navigation": _build_navigation(seg_response.intent, seg_response.auth_action), | |
| 553 | + "navigation": _build_navigation( | |
| 554 | + seg_response.intent, seg_response.auth_action, role | |
| 555 | + ), | |
| 467 | 556 | }) |
| 468 | 557 | info = get_intent(seg_response.intent) if seg_response.intent else None |
| 469 | 558 | title = (info["description"].rstrip(".") if info else segment) |
| @@ -485,7 +574,7 @@ class Engine: | ||
| 485 | 574 | "response_id": first["response_id"], |
| 486 | 575 | "safety": safety_info, |
| 487 | 576 | }) |
| 488 | - return { | |
| 577 | + result = { | |
| 489 | 578 | "trace_id": trace_id, |
| 490 | 579 | "response_id": first["response_id"], |
| 491 | 580 | "text": _with_brand_note(text, query), |
| @@ -500,6 +589,7 @@ class Engine: | ||
| 500 | 589 | "suggestions": suggestions, |
| 501 | 590 | "safety": safety_info, |
| 502 | 591 | } |
| 592 | + return _attach_assistant_meta(result, role) | |
| 503 | 593 | |
| 504 | 594 | # 2) Boru hattı. |
| 505 | 595 | response, trace = process( |
| @@ -570,7 +660,7 @@ class Engine: | ||
| 570 | 660 | text = safety.user_message + "\n" + text |
| 571 | 661 | if self._log_sink is not None: |
| 572 | 662 | self._log_sink(trace) |
| 573 | - return { | |
| 663 | + result = { | |
| 574 | 664 | "trace_id": trace["trace_id"], |
| 575 | 665 | "response_id": "clarification_prompt", |
| 576 | 666 | "text": text, |
| @@ -585,6 +675,7 @@ class Engine: | ||
| 585 | 675 | "suggestions": suggestions, |
| 586 | 676 | "safety": safety_info, |
| 587 | 677 | } |
| 678 | + return _attach_assistant_meta(result, role) | |
| 588 | 679 | |
| 589 | 680 | text = response.text |
| 590 | 681 | # "Neler yapabilirim?" -> oturum rolü belliyse jenerik "rolünü söyle" yerine |
| @@ -593,12 +684,6 @@ class Engine: | ||
| 593 | 684 | role_caps = capabilities_for(role) |
| 594 | 685 | if role_caps: |
| 595 | 686 | 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 | 687 | if safety.decision == safety_mod.ALLOW_WITH_WARNING and safety.user_message: |
| 603 | 688 | text = safety.user_message + "\n" + text |
| 604 | 689 | |
| @@ -613,7 +698,7 @@ class Engine: | ||
| 613 | 698 | if self._log_sink is not None: |
| 614 | 699 | self._log_sink(trace) |
| 615 | 700 | |
| 616 | - return { | |
| 701 | + result = { | |
| 617 | 702 | "trace_id": trace["trace_id"], |
| 618 | 703 | "response_id": response.response_id, |
| 619 | 704 | "text": _with_brand_note(text, query), |
| @@ -622,12 +707,13 @@ class Engine: | ||
| 622 | 707 | "fallback": response.fallback, |
| 623 | 708 | "auth_action": response.auth_action, |
| 624 | 709 | "required_role": trace["decision"]["required_role"], |
| 625 | - "navigation": _build_navigation(response.intent, response.auth_action), | |
| 710 | + "navigation": _build_navigation(response.intent, response.auth_action, role), | |
| 626 | 711 | "clarification": _build_clarification(trace), |
| 627 | 712 | "answers": None, |
| 628 | 713 | "suggestions": suggestions, |
| 629 | 714 | "safety": safety_info, |
| 630 | 715 | } |
| 716 | + return _attach_assistant_meta(result, role) | |
| 631 | 717 | |
| 632 | 718 | |
| 633 | 719 | # 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+15 -12
| @@ -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ı |
| @@ -27,6 +26,7 @@ from .decision import ( | ||
| 27 | 26 | Decision, |
| 28 | 27 | decide, |
| 29 | 28 | ) |
| 29 | +from .role_spaces import get_role_space | |
| 30 | 30 | |
| 31 | 31 | |
| 32 | 32 | # Rollerin insan-okunur (arayüzdeki) adları. |
| @@ -111,18 +111,21 @@ def render(decision: Decision, query: str | None = None) -> Response: | ||
| 111 | 111 | fallback=True, |
| 112 | 112 | ) |
| 113 | 113 | |
| 114 | - body = _select_body(info, query) | |
| 114 | + view = get_role_space(decision.role).view_for(decision.intent) | |
| 115 | + if decision.view_id and view is not None: | |
| 116 | + # The view body is already either role-local guidance or a fail-closed | |
| 117 | + # denial. Do not append the global catalog body to a denial. | |
| 118 | + body = view.response_template | |
| 119 | + else: | |
| 120 | + body = _select_body(info, query) | |
| 115 | 121 | |
| 116 | - if decision.auth_action == LOGIN_REQUIRED: | |
| 117 | - text = ( | |
| 118 | - "Bunun için önce giriş yapmalısın (`/login`). Giriş yaptıktan sonra:\n" | |
| 119 | - + body | |
| 120 | - ) | |
| 121 | - elif decision.auth_action == ROLE_INSUFFICIENT: | |
| 122 | + if decision.auth_action == LOGIN_REQUIRED and not decision.view_id: | |
| 123 | + text = "Bu konu oturum bilgisi gerektiriyor. Önce güvenli biçimde giriş yapmalısın." | |
| 124 | + elif decision.auth_action == ROLE_INSUFFICIENT and not decision.view_id: | |
| 122 | 125 | needed = role_display(decision.required_role or "") |
| 123 | 126 | 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 | |
| 127 | + f"Bu işlem için **{needed}** yetkisi gerekir. Yetkisiz işlem adımları " | |
| 128 | + "ve yönlendirme paylaşılmadı." | |
| 126 | 129 | ) |
| 127 | 130 | else: |
| 128 | 131 | text = body |
src/role_spaces.pyadded+299 -0
| @@ -0,0 +1,299 @@ | ||
| 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 | +C = AccessOutcome.CLARIFY | |
| 42 | +G = AccessScope.GENERAL | |
| 43 | +O = AccessScope.OWN | |
| 44 | +L = AccessScope.LINKED_CHILD | |
| 45 | +E = AccessScope.ENROLLED_COURSE | |
| 46 | +M = AccessScope.MANAGED_COURSE | |
| 47 | +S = AccessScope.SCHOOL | |
| 48 | +V = AccessScope.EVENT_AUDIENCE | |
| 49 | + | |
| 50 | +# (outcome, scope, navigation_key). These are the actions used by the current | |
| 51 | +# catalog, copied from the backend policy rather than inferred from role rank. | |
| 52 | +_ACTION_RULES: Final[dict[str, dict[str, tuple[AccessOutcome, AccessScope | None, str | None]]]] = { | |
| 53 | + "platform.help": _matrix((A, G, "guide"), (A, G, "guide"), (A, G, "guide"), (A, G, "guide"), (A, G, "guide")), | |
| 54 | + "account.self": _matrix((A, O, "profile"), (A, O, "profile"), (A, O, "profile"), (A, O, "profile"), (A, O, "profile")), | |
| 55 | + "messages.use": _matrix((A, O, "messages"), (A, O, "messages"), (A, O, "messages"), (A, O, "messages"), (A, O, "messages")), | |
| 56 | + "notes.use": _matrix((A, O, "notes"), (A, O, "notes"), (A, O, "notes"), (A, O, "notes"), (A, O, "notes")), | |
| 57 | + "courses.view": _matrix((D, None, None), (C, E, "courses"), (C, M, "courses"), (A, S, "courses"), (A, S, "courses")), | |
| 58 | + "courses.create": _matrix((D, None, None), (D, None, None), (A, O, "courses"), (A, S, "courses"), (A, S, "courses")), | |
| 59 | + "courses.manage": _matrix((D, None, None), (D, None, None), (C, M, "courses"), (A, S, "courses"), (A, S, "courses")), | |
| 60 | + "courses.enroll_student": _matrix((D, None, None), (D, None, None), (C, M, "courses"), (A, S, "courses"), (A, S, "courses")), | |
| 61 | + "exams.take": _matrix((D, None, None), (C, E, "exams"), (D, None, None), (D, None, None), (D, None, None)), | |
| 62 | + "exams.manage": _matrix((D, None, None), (D, None, None), (C, M, "exams"), (A, S, "exams"), (A, S, "exams")), | |
| 63 | + "events.create": _matrix((D, None, None), (D, None, None), (A, O, "events"), (A, S, "events"), (A, S, "events")), | |
| 64 | + "events.mark_attendance": _matrix((D, None, None), (D, None, None), (C, V, "events"), (C, V, "events"), (C, V, "events")), | |
| 65 | + "reports.read_own": _matrix((A, O, "reports_self"), (A, O, "reports_self"), (A, O, "reports_self"), (A, O, "reports_self"), (A, O, "reports_self")), | |
| 66 | + "reports.observe_student": _matrix((C, L, None), (D, None, None), (C, M, None), (A, S, None), (A, S, None)), | |
| 67 | + "pomodoro.start": _matrix((D, None, None), (A, O, "pomodoro"), (D, None, None), (D, None, None), (D, None, None)), | |
| 68 | + "pomodoro.observe_student": _matrix((C, L, None), (D, None, None), (A, S, None), (A, S, None), (A, S, None)), | |
| 69 | + "work.self": _matrix((D, None, None), (D, None, None), (A, O, "work"), (A, O, "work"), (A, O, "work")), | |
| 70 | + "work.manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "staff_work"), (A, S, "staff_work")), | |
| 71 | + "school.settings_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "school_settings"), (A, S, "school_settings")), | |
| 72 | + "school.terms_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (A, S, "school_terms"), (A, S, "school_terms")), | |
| 73 | + "users.roles_manage": _matrix((D, None, None), (D, None, None), (D, None, None), (D, None, None), (A, S, "admin_users")), | |
| 74 | +} | |
| 75 | + | |
| 76 | +_ACTION_BY_INTENT: Final[dict[str, str]] = { | |
| 77 | + "greeting": "platform.help", | |
| 78 | + "smalltalk": "platform.help", | |
| 79 | + "thanks": "platform.help", | |
| 80 | + "farewell": "platform.help", | |
| 81 | + "bot_identity": "platform.help", | |
| 82 | + "platform_info": "platform.help", | |
| 83 | + "help_capabilities": "platform.help", | |
| 84 | + "guide_info": "platform.help", | |
| 85 | + "login_how": "platform.help", | |
| 86 | + "register_how": "platform.help", | |
| 87 | + "logout_how": "account.self", | |
| 88 | + "session_info": "account.self", | |
| 89 | + "account_access_problem": "platform.help", | |
| 90 | + "profile_edit": "account.self", | |
| 91 | + "language_theme": "account.self", | |
| 92 | + "roles_permissions": "platform.help", | |
| 93 | + "access_denied_help": "platform.help", | |
| 94 | + "navigation_help": "platform.help", | |
| 95 | + "course_view": "courses.view", | |
| 96 | + "course_create": "courses.create", | |
| 97 | + "course_enroll_student": "courses.enroll_student", | |
| 98 | + "course_remove_student": "courses.manage", | |
| 99 | + "lesson_session_add": "courses.manage", | |
| 100 | + "roll_call": "courses.manage", | |
| 101 | + "exam_modes_info": "platform.help", | |
| 102 | + "exam_create": "exams.manage", | |
| 103 | + "exam_add_question": "exams.manage", | |
| 104 | + "exam_enter_room": "exams.take", | |
| 105 | + "exam_save_answer": "exams.take", | |
| 106 | + "exam_finish_result": "exams.take", | |
| 107 | + "exam_rejoin_retake": "exams.take", | |
| 108 | + "exam_grade_student": "exams.manage", | |
| 109 | + "exam_live_monitor": "exams.manage", | |
| 110 | + "report_card_view": "reports.read_own", | |
| 111 | + "weighted_average_info": "platform.help", | |
| 112 | + "student_marks_lookup": "reports.observe_student", | |
| 113 | + "attendance_view": "reports.read_own", | |
| 114 | + "attendance_rate_info": "platform.help", | |
| 115 | + "event_attendance_mark": "events.mark_attendance", | |
| 116 | + "student_attendance_lookup": "reports.observe_student", | |
| 117 | + "event_create": "events.create", | |
| 118 | + "note_create": "notes.use", | |
| 119 | + "work_checkin_out": "work.self", | |
| 120 | + "staff_work_manage": "work.manage", | |
| 121 | + "term_manage": "school.terms_manage", | |
| 122 | + "school_settings": "school.settings_manage", | |
| 123 | + "user_role_change": "users.roles_manage", | |
| 124 | + "privacy_security": "platform.help", | |
| 125 | + "pomodoro_use": "pomodoro.start", | |
| 126 | + "student_pomodoro_lookup": "pomodoro.observe_student", | |
| 127 | + "messages_use": "messages.use", | |
| 128 | + "study_club_info": "platform.help", | |
| 129 | + "parent_info": "platform.help", | |
| 130 | +} | |
| 131 | + | |
| 132 | +_OWN_REPORT_RESPONSES: Final[dict[str, str]] = { | |
| 133 | + "veli": ( | |
| 134 | + "Veli hesabının kendi öğrenci karnesi veya yoklama kaydı yoktur. Bağlı bir " | |
| 135 | + "çocuğun kaydını soruyorsan bunu açıkça belirt; erişim yalnız doğrulanmış " | |
| 136 | + "veli–öğrenci bağlantısıyla mümkündür." | |
| 137 | + ), | |
| 138 | + "ogretmen": ( | |
| 139 | + "Öğretmen hesabının kendi öğrenci karnesi/yoklama raporu yerine, yalnız " | |
| 140 | + "yönettiğin derslerdeki öğrencilerin raporlarını görüntüleme kapsamı vardır. " | |
| 141 | + "Hangi öğrenciyi ve dersi kastettiğini belirtmelisin." | |
| 142 | + ), | |
| 143 | + "yonetici": ( | |
| 144 | + "Yönetici hesabında kişisel öğrenci karnesi yerine okul kapsamındaki öğrenci " | |
| 145 | + "raporları yönetim ekranlarından görüntülenir. Hangi öğrenciyi kastettiğini belirt." | |
| 146 | + ), | |
| 147 | + "admin": ( | |
| 148 | + "ADMIN hesabında kişisel öğrenci karnesi yerine okul kapsamındaki öğrenci " | |
| 149 | + "raporları görüntülenir. Hangi öğrenciyi kastettiğini belirt." | |
| 150 | + ), | |
| 151 | +} | |
| 152 | + | |
| 153 | +_CONTEXT_TEXT: Final[dict[AccessScope, str]] = { | |
| 154 | + AccessScope.LINKED_CHILD: ( | |
| 155 | + "Bu bilgi yalnızca sana bağlı bir çocuk için görüntülenebilir. Bu mesajda " | |
| 156 | + "veli–öğrenci bağlantısını doğrulayamıyorum; hangi bağlı öğrenciyi kastettiğini belirt." | |
| 157 | + ), | |
| 158 | + AccessScope.ENROLLED_COURSE: ( | |
| 159 | + "Bu işlem yalnızca kayıtlı olduğun ders veya sınav bağlamında yapılabilir. " | |
| 160 | + "Kaydını bu mesajdan doğrulayamıyorum; ilgili ders/sınavı belirt." | |
| 161 | + ), | |
| 162 | + AccessScope.MANAGED_COURSE: ( | |
| 163 | + "Bu işlem yalnızca yönettiğin ders bağlamında yapılabilir. Ders sahipliğini " | |
| 164 | + "bu mesajdan doğrulayamıyorum; ilgili dersi belirt." | |
| 165 | + ), | |
| 166 | + AccessScope.OWNED_RESOURCE: "Bu işlem yalnızca sahibi olduğun kaynak için yapılabilir.", | |
| 167 | + AccessScope.PARTICIPANT: "Bu işlem yalnızca katılımcısı olduğun kaynak için yapılabilir.", | |
| 168 | + AccessScope.REQUESTER: "Bu işlem yalnızca talebin sahibi için yapılabilir.", | |
| 169 | + AccessScope.EVENT_AUDIENCE: ( | |
| 170 | + "Etkinlik yoklamasını Öğretmen, Yönetici veya ADMIN yalnızca etkinliğin " | |
| 171 | + "hedef kitlesindeki kullanıcı için kaydedebilir. Etkinlik ve hedef kullanıcı " | |
| 172 | + "bilgisi olmadan bu koşulu doğrulayamıyorum." | |
| 173 | + ), | |
| 174 | +} | |
| 175 | + | |
| 176 | + | |
| 177 | +def action_id_for_intent(intent: str) -> str: | |
| 178 | + return _ACTION_BY_INTENT[intent] | |
| 179 | + | |
| 180 | + | |
| 181 | +def _local_rule(item: dict, role: str): | |
| 182 | + action_id = action_id_for_intent(item["intent"]) | |
| 183 | + if role == "ziyaretci": | |
| 184 | + if item["auth_required"]: | |
| 185 | + return action_id, D, None, None | |
| 186 | + return action_id, A, G, None | |
| 187 | + outcome, scope, route_key = _ACTION_RULES[action_id][role] | |
| 188 | + return action_id, outcome, scope, route_key | |
| 189 | + | |
| 190 | + | |
| 191 | +def _deny_text(item: dict, role: str, reason: ReasonCode) -> str: | |
| 192 | + if reason is ReasonCode.AUTHENTICATION_REQUIRED: | |
| 193 | + return "Bu konu oturum bilgisi gerektiriyor. Önce güvenli biçimde giriş yapmalısın." | |
| 194 | + return ( | |
| 195 | + f"Bu işlem **{role}** rolüne açık değil. Yetkisiz işlem adımları veya " | |
| 196 | + "yönlendirme paylaşılmadı." | |
| 197 | + ) | |
| 198 | + | |
| 199 | + | |
| 200 | +def _view(item: dict, role: str) -> RoleIntentView: | |
| 201 | + action_id, outcome, scope, route_key = _local_rule(item, role) | |
| 202 | + if outcome is D: | |
| 203 | + reason = ( | |
| 204 | + ReasonCode.AUTHENTICATION_REQUIRED | |
| 205 | + if role == "ziyaretci" and item["auth_required"] | |
| 206 | + else ReasonCode.ROLE_NOT_PERMITTED | |
| 207 | + ) | |
| 208 | + body = _deny_text(item, role, reason) | |
| 209 | + elif outcome is C: | |
| 210 | + reason = ReasonCode.CONTEXT_REQUIRED | |
| 211 | + body = _CONTEXT_TEXT[scope] | |
| 212 | + route_key = None | |
| 213 | + else: | |
| 214 | + reason = ReasonCode.ALLOWED | |
| 215 | + body = item["response_template"] | |
| 216 | + | |
| 217 | + if item["intent"] in {"report_card_view", "attendance_view"} and role != "ogrenci": | |
| 218 | + body = _OWN_REPORT_RESPONSES.get(role, body) | |
| 219 | + | |
| 220 | + clarification = _CONTEXT_TEXT.get(scope) if outcome is C else None | |
| 221 | + return RoleIntentView( | |
| 222 | + role=role, | |
| 223 | + intent=item["intent"], | |
| 224 | + action_id=action_id, | |
| 225 | + outcome=outcome, | |
| 226 | + scope=scope, | |
| 227 | + reason_code=reason, | |
| 228 | + response_id=item["response_id"], | |
| 229 | + response_template=body, | |
| 230 | + examples=tuple(item["example_questions"]), | |
| 231 | + clarification=clarification, | |
| 232 | + required_role=None if outcome is not D else item["min_role"], | |
| 233 | + route_key=route_key if outcome is A else None, | |
| 234 | + route_label=None, | |
| 235 | + ) | |
| 236 | + | |
| 237 | + | |
| 238 | +def _hash_views(role: str, views: dict[str, RoleIntentView]) -> str: | |
| 239 | + manifest = [ | |
| 240 | + { | |
| 241 | + "view": view.view_id, | |
| 242 | + "action": view.action_id, | |
| 243 | + "outcome": view.outcome.value, | |
| 244 | + "scope": view.scope.value if view.scope else None, | |
| 245 | + "route": view.route_key, | |
| 246 | + } | |
| 247 | + for view in views.values() | |
| 248 | + ] | |
| 249 | + raw = json.dumps( | |
| 250 | + {"version": ROLE_SPACE_VERSION, "role": role, "views": manifest}, | |
| 251 | + ensure_ascii=False, | |
| 252 | + sort_keys=True, | |
| 253 | + separators=(",", ":"), | |
| 254 | + ).encode("utf-8") | |
| 255 | + return hashlib.sha256(raw).hexdigest() | |
| 256 | + | |
| 257 | + | |
| 258 | +@lru_cache(maxsize=len(ROLE_HIERARCHY)) | |
| 259 | +def get_role_space(role: str) -> CompiledRoleSpace: | |
| 260 | + if role not in ROLE_HIERARCHY: | |
| 261 | + raise KeyError(f"bilinmeyen rol uzayı: {role!r}") | |
| 262 | + views = {item["intent"]: _view(item, role) for item in INTENTS} | |
| 263 | + content_hash = _hash_views(role, views) | |
| 264 | + space_id = f"{ROLE_SPACE_VERSION}:{role}:{content_hash[:12]}" | |
| 265 | + examples = [ | |
| 266 | + (view.intent, question) | |
| 267 | + for view in views.values() | |
| 268 | + for question in view.examples | |
| 269 | + ] | |
| 270 | + return CompiledRoleSpace( | |
| 271 | + role=role, | |
| 272 | + version=ROLE_SPACE_VERSION, | |
| 273 | + content_hash=content_hash, | |
| 274 | + views=CompiledRoleSpace.immutable_views(views), | |
| 275 | + rule_matcher=RuleMatcher(set(views), space_id=space_id), | |
| 276 | + similarity_matcher=SimilarityMatcher(examples, space_id=space_id), | |
| 277 | + domain_vocab=frozenset(build_domain_vocab(question for _, question in examples)), | |
| 278 | + ) | |
| 279 | + | |
| 280 | + | |
| 281 | +def validate_role_spaces() -> None: | |
| 282 | + expected = {item["intent"] for item in INTENTS} | |
| 283 | + if set(_ACTION_BY_INTENT) != expected: | |
| 284 | + missing = expected - set(_ACTION_BY_INTENT) | |
| 285 | + extra = set(_ACTION_BY_INTENT) - expected | |
| 286 | + raise ValueError(f"intent/action eşlemesi eksik={missing}, fazla={extra}") | |
| 287 | + ids: set[str] = set() | |
| 288 | + for role in ROLE_HIERARCHY: | |
| 289 | + space = get_role_space(role) | |
| 290 | + if set(space.views) != expected: | |
| 291 | + raise ValueError(f"{role}: eksik/fazla intent görünümü") | |
| 292 | + if space.space_id in ids: | |
| 293 | + raise ValueError(f"{role}: rol uzayı kimliği benzersiz değil") | |
| 294 | + ids.add(space.space_id) | |
| 295 | + if any(view.role != role for view in space.views.values()): | |
| 296 | + raise ValueError(f"{role}: başka role ait görünüm sızdı") | |
| 297 | + | |
| 298 | + | |
| 299 | +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 |