"""Post-stream output scanner. Two checks: - PII regex (email, phone, suspect names) — third line of defense for FERPA - Answer-leak overlap — verbatim chunks >= threshold against retrieved question/slide_answer bodies, blocking regurgitation of answer keys """ from __future__ import annotations import os import re from dataclasses import dataclass, field from scripts.lib.catalog_loader import Catalog from scripts.lib.ranker import RetrievalResult _RE_EMAIL = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b") _RE_PHONE = re.compile(r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b") # Only slide_answer bodies are checked for verbatim overlap. Question bodies # are quoteable: students see questions on assignments anyway, and posing the # question is part of the Socratic walk-through. pack_loader._ASSESSMENT_KINDS # still includes "question" so the assessment-aware Socratic block in the # system prompt fires when a question is retrieved; only this mechanical # verbatim check is narrowed. _ASSESSMENT_KINDS = {"slide_answer"} _DEFAULT_OVERLAP_THRESHOLD = 30 @dataclass class ScanResult: pii_violations: list[str] = field(default_factory=list) answer_leak_chunks: list[str] = field(default_factory=list) def _overlap_threshold() -> int: raw = os.environ.get("ME_HUB_ANSWER_LEAK_MIN_CHARS") if raw is None: return _DEFAULT_OVERLAP_THRESHOLD try: return max(1, int(raw)) except ValueError: return _DEFAULT_OVERLAP_THRESHOLD def _find_verbatim_chunks(response: str, body: str, min_chars: int) -> list[str]: """Return verbatim substrings of `body` that appear in `response`, length >= min_chars.""" if not body or not response: return [] chunks: list[str] = [] body_len = len(body) if body_len < min_chars: return [] seen_starts: set[int] = set() for i in range(body_len - min_chars + 1): if i in seen_starts: continue # Try to extend the window as long as response still contains it end = i + min_chars while end <= body_len and body[i:end] in response: end += 1 end -= 1 # rewind to last successful match if end - i >= min_chars: chunk = body[i:end] chunks.append(chunk) # Skip starts within the matched range to avoid duplicates for j in range(i, end): seen_starts.add(j) return chunks def scan( response: str, retrieved: list[RetrievalResult], catalog: Catalog, *, suspect_names: set[str] | None = None, ) -> ScanResult: """Post-stream scan: PII regex + answer-leak overlap.""" pii: list[str] = [] pii.extend(_RE_EMAIL.findall(response)) pii.extend(_RE_PHONE.findall(response)) if suspect_names: name_rx = re.compile( r"\b(" + "|".join(re.escape(n) for n in suspect_names) + r")\b", flags=re.IGNORECASE, ) pii.extend(name_rx.findall(response)) threshold = _overlap_threshold() leak_chunks: list[str] = [] by_doc_id = {r["doc_id"]: r for r in catalog.records} for rr in retrieved: rec = by_doc_id.get(rr.doc_id, {}) if rec.get("kind") not in _ASSESSMENT_KINDS: continue body = rec.get("concept_profile", "") or "" leak_chunks.extend(_find_verbatim_chunks(response, body, threshold)) return ScanResult(pii_violations=pii, answer_leak_chunks=leak_chunks)