"""Python orchestrator for the agentic brand review (NOT SDK handoffs). `run_audit(ctx, job_id)` drives the three agents: 1. Pre-scans every slide for the fixed must-flag terms (DRAFT, TW question, Page to be updated) using ``services.markers.find_text_markers_pure`` directly. Hits are persisted in ``marker_hits[slide_n]`` and passed into each Slide Reviewer call as part of ``SlideBriefing``. 2. Runs the Slide Reviewer Agent in parallel across all slides, capped at ``MAX_CONCURRENT_SLIDES`` (5) by ``asyncio.Semaphore``. 3. Runs the Deck Consistency Agent once. 4. Runs the Lead Auditor Agent once over the collected slide + deck findings; the agent returns a draft :class:`FinalAuditResult`. 5. Walks every must-flag hit and injects a deterministic ``safety_net`` finding for any hit the upstream agents did not surface. This is the demo's must-flag guarantee — it lives in Python, not the LLM. 6. Validates each finding's evidence and category at the boundary; tags ``finding_meta.must_flag = True`` on agent findings whose evidence overlaps a marker hit's context window. 7. Records per-slide errors in ``FinalAuditResult.errors``. If any slide had no successful agent output, the audit ends ``partial`` (the API layer reads ``errors``); the runner does NOT re-raise. A small retry helper wraps every ``Runner.run`` call: up to 4 attempts on ``RateLimitError``, ``APITimeoutError``, and ``APIStatusError(>=500)``; permanent 4xx (non-429) errors propagate. Public surface -------------- * :func:`run_audit` — top-level coroutine. The API layer awaits this from inside its job-processing background task. * :func:`_run_with_retry` — exposed for unit tests. * :class:`SlideBriefing`, :class:`ConsistencyBriefing`, :class:`MergeInput` — the per-call inputs the Agents SDK serialises into the agent prompt. """ from __future__ import annotations import asyncio import json import logging import os import random import re import time from dataclasses import asdict, dataclass, is_dataclass from pathlib import Path from typing import Any, Awaitable, Callable import openai from agents import Runner from agents.context import AuditContext from agents.consistency import deck_consistency from agents.lead_auditor import lead_auditor from agents.output_schemas import ( DeckFindings, FindingExtended, FindingMeta, FinalAuditResult, SeverityCounts, SlideEnvelopeExtended, SlideFindings, ) from agents.slide_bundle import ( build_rubric_full, build_slide_bundle, bundle_to_prompt_payload, ) from agents.slide_reviewer import ( SLIDE_REVIEWER_MODE_AGENTIC, SLIDE_REVIEWER_MODE_SINGLE_SHOT, get_slide_reviewer, get_slide_reviewer_mode, slide_reviewer, ) from services.confidentiality import ConfidentialityCheck, check_confidentiality_pure from services.event_log import append_event from services.markers import Hit, find_text_markers_pure from services.rate_limit import ( DECK_CONSISTENCY_EST_TOKENS, LEAD_AUDITOR_EST_TOKENS, SLIDE_REVIEW_EST_TOKENS, TokenRateLimiter, get_default_limiter, ) logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- MUST_FLAG_TERMS: list[str] = ["DRAFT", "TW question", "Page to be updated"] def _int_env(key: str, default: int) -> int: raw = os.environ.get(key, "") if not raw: return default try: return int(raw) except ValueError: logger.warning("Invalid %s=%r — falling back to %d", key, raw, default) return default # Concurrency cap is env-tunable. The rate limiter is the *primary* throttle — # this semaphore is a fail-safe in case the limiter mis-estimates and the # pipeline tries to fan out beyond the API's connection-level tolerance. _REQUESTED_CONCURRENT_SLIDES: int = _int_env("OPENAI_REVIEW_CONCURRENCY", 2) _HARD_MAX_CONCURRENT_SLIDES: int = _int_env("OPENAI_REVIEW_CONCURRENCY_HARD_CAP", 2) MAX_CONCURRENT_SLIDES: int = max( 1, min(_REQUESTED_CONCURRENT_SLIDES, _HARD_MAX_CONCURRENT_SLIDES) ) MAX_TURNS_SLIDE_REVIEWER: int = 15 # In single-shot mode the agent has no tools; one turn is exactly what we # want and the SDK will reject anything > 1 if a tool call is requested. MAX_TURNS_SLIDE_REVIEWER_SINGLE_SHOT: int = 1 MAX_TURNS_DECK_CONSISTENCY: int = 10 MAX_TURNS_LEAD_AUDITOR: int = 10 # Bumped from 4 → 5 attempts so transient bursts (which can run 3-4 deep # during the first minute of a large deck) get more slack before failing. MAX_RETRY_ATTEMPTS: int = 5 # Exponential backoff base delays (seconds): 2, 4, 8, 16, 30 (capped). # These run *before* attempts 2..6 — first attempt is always immediate. _BACKOFF_DELAYS: tuple[float, ...] = (2.0, 4.0, 8.0, 16.0, 30.0) _BACKOFF_MAX_SECONDS: float = 30.0 # OpenAI's RateLimitError message often embeds a "Please try again in 3.87s" # hint computed from headers. When present, honour it instead of guessing. _RETRY_AFTER_RE = re.compile( r"try again in ([\d.]+)\s*(ms|s)", re.IGNORECASE ) # --------------------------------------------------------------------------- # Per-call agent inputs # --------------------------------------------------------------------------- @dataclass class SlideBriefing: """Input passed to one Slide Reviewer Agent invocation.""" slide_number: int marker_hits: list[Hit] @dataclass class ConsistencyBriefing: """Input passed to the single Deck Consistency Agent invocation.""" slide_count: int @dataclass class MergeInput: """Input passed to the single Lead Auditor Agent invocation.""" job_id: str file_name: str slide_count: int slide_findings: list[SlideFindings] deck_findings: DeckFindings def _briefing_to_prompt(briefing: Any) -> str: """Serialise a dataclass briefing into a deterministic JSON prompt string. The Agents SDK accepts ``str | list[TResponseInputItem] | RunState``. We use a JSON string so the agent gets a single, predictable user message. """ if is_dataclass(briefing): payload = asdict(briefing) else: payload = briefing # already a dict / Pydantic-ish return json.dumps(payload, default=_json_default, ensure_ascii=False) def _json_default(obj: Any) -> Any: """JSON encoder fallback for Hit / Pydantic models.""" if hasattr(obj, "model_dump"): return obj.model_dump() if is_dataclass(obj): return asdict(obj) raise TypeError(f"Cannot serialise {type(obj).__name__}") # --------------------------------------------------------------------------- # Single-shot multimodal input construction # --------------------------------------------------------------------------- def _single_shot_input(bundle: Any) -> list[dict[str, Any]]: """Build the Agents-SDK ``input`` list for a single-shot review. Returns a list with exactly one ``user`` message whose content has two parts: 1. ``input_image`` — the rendered PNG as a base64 data URL (omitted when the bundle has no image — e.g. soffice was unavailable). 2. ``input_text`` — the JSON-serialised bundle payload (without the image bytes — those are the input_image part). The shape matches the OpenAI Responses API's ``ResponseInputMessageContentList`` and is what the Agents SDK forwards verbatim when ``input`` is a list of dicts. """ payload = bundle_to_prompt_payload(bundle) text_part: dict[str, Any] = { "type": "input_text", "text": json.dumps(payload, default=_json_default, ensure_ascii=False), } content: list[dict[str, Any]] = [] if bundle.image_b64: content.append( { "type": "input_image", "detail": "auto", "image_url": f"data:image/png;base64,{bundle.image_b64}", } ) content.append(text_part) return [{"role": "user", "content": content}] # --------------------------------------------------------------------------- # Retry helper # --------------------------------------------------------------------------- def _is_retriable(exc: BaseException) -> bool: """True if *exc* is a transient OpenAI error worth retrying. Includes ``APIConnectionError`` — the connection-reset pattern we saw in the 33-slide audit ("connection error") happens when the server kills a TCP socket mid-stream during heavy concurrency. """ if isinstance(exc, ( openai.RateLimitError, openai.APITimeoutError, openai.APIConnectionError, )): return True if isinstance(exc, openai.APIStatusError): status = getattr(exc, "status_code", None) if status is not None and status >= 500: return True return False def _retry_after_hint(exc: BaseException) -> float | None: """Extract a ``retry-after`` hint (seconds) from an OpenAI error. OpenAI 429s typically embed the wait into the message body. Falls back to the ``retry-after`` HTTP header when available. Returns ``None`` if no hint can be parsed. """ msg = str(exc) if exc else "" m = _RETRY_AFTER_RE.search(msg) if m: try: value = float(m.group(1)) return value / 1000 if m.group(2).lower() == "ms" else value except ValueError: pass # APIStatusError has a .response with headers in modern SDKs. response = getattr(exc, "response", None) if response is not None: try: header = response.headers.get("retry-after") except Exception: # noqa: BLE001 — defensive against odd mocks header = None if header: try: return float(header) except ValueError: pass return None async def _run_with_retry( coro_factory: Callable[[], Awaitable[Any]], *, label: str, max_attempts: int = MAX_RETRY_ATTEMPTS, sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, rng: Callable[[], float] = random.random, ) -> Any: """Run *coro_factory* with exponential backoff on retriable OpenAI errors. Retries on ``RateLimitError``, ``APITimeoutError``, ``APIConnectionError`` and ``APIStatusError`` with ``status_code >= 500``. All other errors propagate immediately. Backoff strategy: * If the error embeds a ``retry-after`` hint (parsed from message or header), use ``hint + jitter`` — capped at :data:`_BACKOFF_MAX_SECONDS`. * Otherwise, exponential backoff: 2s, 4s, 8s, 16s, 30s + jitter. * Up to :data:`MAX_RETRY_ATTEMPTS` attempts (default 5). The ``sleep`` and ``rng`` parameters are seams for unit tests so they can pass a ``no_sleep`` and a deterministic RNG. """ last_exc: BaseException | None = None for attempt in range(1, max_attempts + 1): try: return await coro_factory() except BaseException as exc: # noqa: BLE001 — narrow with _is_retriable last_exc = exc if not _is_retriable(exc) or attempt >= max_attempts: raise hint = _retry_after_hint(exc) if hint is not None: base = min(hint, _BACKOFF_MAX_SECONDS) else: base = _BACKOFF_DELAYS[min(attempt - 1, len(_BACKOFF_DELAYS) - 1)] jitter = rng() wait = min(base + jitter, _BACKOFF_MAX_SECONDS) logger.warning( "%s: retriable error (%s) on attempt %d/%d — sleeping %.2fs%s", label, type(exc).__name__, attempt, max_attempts, wait, " (hint)" if hint is not None else "", ) await sleep(wait) # Defensive: should be unreachable. assert last_exc is not None raise last_exc # --------------------------------------------------------------------------- # Public orchestrator # --------------------------------------------------------------------------- def _model_for(agent: Any, default_env: str, fallback: str = "gpt-4o") -> str: """Return the model name used by *agent* for rate-limit bucketing. The Agents SDK stores the model on the agent itself, but the agent constructor pinned it at import time. We re-resolve from the env at call time so per-agent overrides honoured at runtime — important for tests that monkeypatch ``OPENAI_MODEL_*`` between scenarios. """ return os.environ.get(default_env) or os.environ.get("OPENAI_MODEL") or fallback async def run_audit( ctx: AuditContext, job_id: str, *, file_name: str | None = None, runner: Any = Runner, on_slide_done: Callable[[int, int], None] | None = None, job_dir: Path | None = None, rate_limiter: TokenRateLimiter | None = None, ) -> FinalAuditResult: """Drive the agentic brand review and return the final audit result. Parameters ---------- ctx: The shared :class:`AuditContext` (parsed deck, render result, rubric). job_id: The audit job identifier — copied verbatim into the result envelope. file_name: Optional original PPTX file name; defaults to ``"deck.pptx"``. runner: Injection seam for tests — must expose an async ``run`` matching ``Runner.run``. Defaults to the SDK's :class:`Runner`. on_slide_done: Optional callback invoked after each slide reviewer settles (success or exception). Receives ``(completed_count, total)`` where ``completed_count`` is the monotonically increasing number of slides that have finished (not necessarily succeeded). Callback exceptions are swallowed so they never crash the audit. An initial tick with ``(0, total)`` is fired before the gather begins so callers can initialise their progress display. job_dir: Optional path to the job's on-disk directory. When supplied, the runner appends per-slide ``slide-reviewed`` events to ``{job_dir}/events.jsonl`` so the SSE generator can stream them to the client. Tests typically pass ``None``. rate_limiter: Optional :class:`TokenRateLimiter` override (test seam). Defaults to the process-global limiter when ``None``. """ file_name = file_name or "deck.pptx" slide_count = ctx.parsed_deck.slide_count errors: list[str] = [] limiter = rate_limiter if rate_limiter is not None else get_default_limiter() slide_model = _model_for(slide_reviewer, "OPENAI_MODEL_SLIDE", "gpt-4o-mini") deck_model = _model_for(deck_consistency, "OPENAI_MODEL_DECK", "gpt-4o") merge_model = _model_for(lead_auditor, "OPENAI_MODEL_MERGE", "gpt-4o") # 1. Pre-scan must-flag markers (deterministic, unconditional). marker_hits: dict[int, list[Hit]] = { n: find_text_markers_pure(ctx.parsed_deck, n, MUST_FLAG_TERMS) for n in range(1, slide_count + 1) } # 1b. Resolve slide-reviewer mode + cache deck-wide rubric snapshot once. review_mode = get_slide_reviewer_mode() active_slide_reviewer = get_slide_reviewer() rubric_full = ( build_rubric_full(ctx.rubric) if review_mode == SLIDE_REVIEWER_MODE_SINGLE_SHOT else None ) logger.info( "slide_reviewer mode=%s, model=%s, max_turns=%d", review_mode, slide_model, ( MAX_TURNS_SLIDE_REVIEWER_SINGLE_SHOT if review_mode == SLIDE_REVIEWER_MODE_SINGLE_SHOT else MAX_TURNS_SLIDE_REVIEWER ), ) # 2. Slide reviewers in parallel, semaphore-bounded *and* TPM-budgeted. semaphore = asyncio.Semaphore(MAX_CONCURRENT_SLIDES) completed_counter = {"n": 0} completed_lock = asyncio.Lock() # Initial tick so the UI can show "Reviewed 0 of N" immediately. if on_slide_done is not None: try: on_slide_done(0, slide_count) except Exception: # noqa: BLE001 — callback failure must not crash audit pass async def review_one(slide_n: int) -> Any: async with semaphore: started = time.monotonic() sf: SlideFindings | None = None err: BaseException | None = None # Build the agent input depending on the active mode. if review_mode == SLIDE_REVIEWER_MODE_SINGLE_SHOT: bundle = build_slide_bundle( slide_n, ctx.parsed_deck, ctx.render_result, ctx.rubric, rubric_full=rubric_full, include_image_b64=True, marker_hits=marker_hits[slide_n], ) slide_input: Any = _single_shot_input(bundle) slide_max_turns = MAX_TURNS_SLIDE_REVIEWER_SINGLE_SHOT else: briefing = SlideBriefing( slide_number=slide_n, marker_hits=marker_hits[slide_n] ) slide_input = _briefing_to_prompt(briefing) slide_max_turns = MAX_TURNS_SLIDE_REVIEWER try: # Rate-limit acquire happens *inside* the retry factory so a # 429 can re-acquire on the next attempt (the prior reservation # has aged out by then in the worst case). async def _do_call(): # Throttling: rely on (a) the asyncio.Semaphore concurrency # cap, (b) the OpenAI SDK's built-in max_retries, and # (c) our _run_with_retry exponential backoff with retry-after # parsing. The pre-call TokenRateLimiter was removed because # its undercounting created more 429 noise than it prevented. return await runner.run( active_slide_reviewer, input=slide_input, context=ctx, max_turns=slide_max_turns, ) result = await _run_with_retry( _do_call, label=f"slide_reviewer[slide={slide_n}]", ) sf = _extract_final_output(result, SlideFindings) return result except BaseException as exc: # noqa: BLE001 err = exc raise finally: duration_ms = int((time.monotonic() - started) * 1000) async with completed_lock: completed_counter["n"] += 1 if on_slide_done is not None: try: on_slide_done(completed_counter["n"], slide_count) except Exception: # noqa: BLE001 — callback failure must not crash audit pass # Append per-slide event for the SSE stream. if job_dir is not None: payload: dict[str, Any] = { "slide_number": slide_n, "duration_ms": duration_ms, } if err is not None: payload["error"] = f"{type(err).__name__}: {err}" payload["findings_count"] = 0 payload["max_severity"] = None else: findings = sf.findings if sf is not None else [] payload["findings_count"] = len(findings) payload["max_severity"] = _max_severity(findings) append_event(job_dir, "slide-reviewed", payload) raw_slide_results: list[Any] = await asyncio.gather( *[review_one(n) for n in range(1, slide_count + 1)], return_exceptions=True, ) slide_findings_by_n: dict[int, SlideFindings] = {} for n, result in enumerate(raw_slide_results, start=1): if isinstance(result, BaseException): errors.append(f"slide {n}: {type(result).__name__}: {result}") continue sf = _extract_final_output(result, SlideFindings) if sf is None: errors.append( f"slide {n}: agent returned no SlideFindings output" ) continue slide_findings_by_n[n] = sf # 3. Deck consistency once. deck_findings: DeckFindings try: deck_briefing = ConsistencyBriefing(slide_count=slide_count) async def _deck_call(): return await runner.run( deck_consistency, input=_briefing_to_prompt(deck_briefing), context=ctx, max_turns=MAX_TURNS_DECK_CONSISTENCY, ) deck_result = await _run_with_retry(_deck_call, label="deck_consistency") df = _extract_final_output(deck_result, DeckFindings) deck_findings = df if df is not None else DeckFindings(findings=[]) except BaseException as exc: # noqa: BLE001 errors.append(f"deck_consistency: {type(exc).__name__}: {exc}") deck_findings = DeckFindings(findings=[]) # 4. Lead Auditor merge (best-effort — fall back to a Python merge). lead_result: FinalAuditResult | None = None try: merge_input = MergeInput( job_id=job_id, file_name=file_name, slide_count=slide_count, slide_findings=list(slide_findings_by_n.values()), deck_findings=deck_findings, ) async def _merge_call(): return await runner.run( lead_auditor, input=_briefing_to_prompt(merge_input), context=ctx, max_turns=MAX_TURNS_LEAD_AUDITOR, ) merged_raw = await _run_with_retry(_merge_call, label="lead_auditor") lead_result = _extract_final_output(merged_raw, FinalAuditResult) except BaseException as exc: # noqa: BLE001 errors.append(f"lead_auditor: {type(exc).__name__}: {exc}") if lead_result is None: # Python fallback merge — keeps the audit usable when Lead Auditor fails. lead_result = _python_fallback_merge( job_id=job_id, file_name=file_name, slide_count=slide_count, slide_findings_by_n=slide_findings_by_n, deck_findings=deck_findings, ) # 5/6. Boundary validation, must_flag tagging, deterministic must-flag injection. final = _finalise( job_id=job_id, file_name=file_name, slide_count=slide_count, lead_result=lead_result, marker_hits=marker_hits, ctx=ctx, errors=errors, ) return final # --------------------------------------------------------------------------- # Lead-auditor result extraction (handles both real RunResult and mocks) # --------------------------------------------------------------------------- _SEVERITY_RANK: dict[str, int] = {"low": 1, "medium": 2, "high": 3} def _max_severity(findings: list[Any]) -> str | None: """Return the highest-severity label across a list of findings (or None).""" best: str | None = None best_rank = 0 for f in findings: sev = getattr(f, "severity", None) if sev is None and isinstance(f, dict): sev = f.get("severity") rank = _SEVERITY_RANK.get(str(sev or ""), 0) if rank > best_rank: best = str(sev) best_rank = rank return best def _extract_final_output(result: Any, expected_type: type) -> Any: """Pull the structured output of an Agents SDK ``RunResult``. The SDK stores the parsed ``output_type`` instance under ``result.final_output``. Tests may pass back a bare instance of the expected type (e.g. a ``SlideFindings`` mock), in which case we accept that directly. Returns ``None`` if the result is not usable. """ if isinstance(result, expected_type): return result final = getattr(result, "final_output", None) if isinstance(final, expected_type): return final # Some test mocks return dicts — coerce best-effort via Pydantic. if isinstance(final, dict): try: return expected_type.model_validate(final) except Exception: # noqa: BLE001 return None if isinstance(result, dict): try: return expected_type.model_validate(result) except Exception: # noqa: BLE001 return None return None def _record_actual_usage_delta( limiter: TokenRateLimiter, *, model: str, estimate: int, result: Any, ) -> None: """Backfill rate-limit accounting when SDK usage exceeds our estimate. The Agents SDK shape can vary by version, so this is deliberately best-effort. If no usage field is discoverable, the original reservation made before the call still protects the window. """ actual = _usage_total_tokens(result) if actual is None or actual <= estimate: return limiter.record(model=model, tokens=actual - estimate) def _usage_total_tokens(result: Any) -> int | None: """Extract total token usage from common OpenAI/Agents SDK result shapes.""" candidates: list[Any] = [result] raw_responses = getattr(result, "raw_responses", None) if raw_responses: candidates.extend(raw_responses) responses = getattr(result, "responses", None) if responses: candidates.extend(responses) total = 0 found = False for candidate in candidates: usage = getattr(candidate, "usage", None) if usage is None and isinstance(candidate, dict): usage = candidate.get("usage") tokens = _tokens_from_usage(usage) if tokens is not None: total += tokens found = True return total if found else None def _tokens_from_usage(usage: Any) -> int | None: if usage is None: return None for attr in ("total_tokens", "total_token_count"): value = getattr(usage, attr, None) if value is not None: try: return int(value) except (TypeError, ValueError): pass if isinstance(usage, dict): for key in ("total_tokens", "total_token_count"): value = usage.get(key) if value is not None: try: return int(value) except (TypeError, ValueError): pass input_tokens = getattr(usage, "input_tokens", None) output_tokens = getattr(usage, "output_tokens", None) if input_tokens is None and isinstance(usage, dict): input_tokens = usage.get("input_tokens") output_tokens = usage.get("output_tokens") if input_tokens is not None or output_tokens is not None: try: return int(input_tokens or 0) + int(output_tokens or 0) except (TypeError, ValueError): return None return None # --------------------------------------------------------------------------- # Python fallback merge (used when Lead Auditor agent fails) # --------------------------------------------------------------------------- def _python_fallback_merge( *, job_id: str, file_name: str, slide_count: int, slide_findings_by_n: dict[int, SlideFindings], deck_findings: DeckFindings, ) -> FinalAuditResult: """Build a :class:`FinalAuditResult` without an LLM merge pass. Used when the Lead Auditor agent fails or returns nothing. Slide-level findings retain their slide context; deck-level findings are appended to slide 1 (a sensible default — they apply across the deck). """ slides: list[SlideEnvelopeExtended] = [] for n in range(1, slide_count + 1): envelope = SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[]) sf = slide_findings_by_n.get(n) if sf is not None: for f in sf.findings: envelope.findings.append( FindingExtended( **f.model_dump(), finding_meta=FindingMeta(source="agent_slide", must_flag=False), ) ) slides.append(envelope) if slide_count >= 1: for f in deck_findings.findings: slides[0].findings.append( FindingExtended( **f.model_dump(), finding_meta=FindingMeta(source="agent_deck", must_flag=False), ) ) return FinalAuditResult( job_id=job_id, file_name=file_name, slide_count=slide_count, summary=SeverityCounts(), slides=slides, errors=[], ) # --------------------------------------------------------------------------- # Boundary validation + must-flag injection # --------------------------------------------------------------------------- def _finalise( *, job_id: str, file_name: str, slide_count: int, lead_result: FinalAuditResult, marker_hits: dict[int, list[Hit]], ctx: AuditContext, errors: list[str], ) -> FinalAuditResult: """Apply boundary validation, must_flag tagging, and safety-net injection. Determinism contract -------------------- Three classes of finding are injected here from pure-Python deterministic checks, AFTER the LLM has been allowed to add its own subjective findings. These injectors run unconditionally for every detected violation — they are NOT gated on whether the LLM also surfaced the same issue. Rationale: at temperature=1 the LLM stochastically chooses to skip these advisory inputs, which made repeated runs of the same deck produce wildly different counts. By emitting one safety_net finding per detected violation we pin those counts to a deterministic floor (#hits / #failed checks). The three classes are: 1. text_markers — DRAFT / TW question / Page to be updated 2. confidentiality — present=false OR position_hint != "footer" 3. color_palette — any in_palette=false hex on the slide Agent findings that overlap a deterministic violation are kept (LLM-side description / vision evidence may add value), and their finding_meta is upgraded with must_flag=True for marker overlaps so the dashboard badges them. Duplicate suppression of the safety_net for marker hits was REMOVED in the determinism fix — the safety_net always fires per hit. """ rubric = ctx.rubric valid_categories = {rule.category for rule in rubric.rules} must_flag_meta = rubric.metadata.must_flag_markers # Normalise the slides list to exactly slide_count entries indexed 1..N. by_n: dict[int, SlideEnvelopeExtended] = { env.slide_number: env for env in lead_result.slides } normalised: list[SlideEnvelopeExtended] = [] for n in range(1, slide_count + 1): env = by_n.get(n) or SlideEnvelopeExtended( slide_number=n, image_url=None, findings=[] ) # Force slide_number consistency. env = SlideEnvelopeExtended( slide_number=n, image_url=env.image_url, findings=list(env.findings), ) normalised.append(env) # Boundary validation: drop empty-evidence + unknown-category findings. for env in normalised: kept: list[FindingExtended] = [] for f in env.findings: if not f.evidence or not f.evidence.strip(): logger.warning( "Dropping finding on slide %d: empty evidence (title=%r)", env.slide_number, f.title, ) continue if f.category not in valid_categories: logger.warning( "Dropping finding on slide %d: unknown category %r (title=%r)", env.slide_number, f.category, f.title, ) continue kept.append(f) env.findings = kept # Tag agent findings whose evidence overlaps a marker hit's context window # with finding_meta.must_flag = True. for env in normalised: hits = marker_hits.get(env.slide_number, []) if not hits: continue for f in env.findings: if _evidence_overlaps_any_hit(f.evidence, hits): if not f.finding_meta.must_flag: f.finding_meta = FindingMeta( source=f.finding_meta.source, must_flag=True ) # ---- Determinism floor: ALWAYS inject one safety_net finding per # detected text_marker hit. Previously this was conditional on the LLM # not having already surfaced the hit, which created the stochastic # 48-vs-14-findings regression at temp=1. The duplicate cost is small # (an extra synthetic finding alongside an LLM-emitted one) and the # gain is bit-identical counts across runs. for n, hits in marker_hits.items(): env = normalised[n - 1] for hit in hits: inj = _build_safety_net_finding(n, hit, must_flag_meta=must_flag_meta) env.findings.append(inj) # ---- Determinism floor: confidentiality_statement. # Re-run the pure check (cheap) and inject one safety_net finding per # slide where the rule is violated, regardless of LLM output. The # canonical_text comes from the rubric — same source the bundle uses. canonical_conf = _canonical_confidentiality_text(rubric) if canonical_conf is not None: conf_rule_id = _confidentiality_rule_id(rubric) for n in range(1, slide_count + 1): env = normalised[n - 1] cc = check_confidentiality_pure( ctx.parsed_deck, n, canonical_conf ) if _confidentiality_violates(cc): env.findings.append( _build_confidentiality_safety_net_finding( n, cc, rule_id=conf_rule_id ) ) # ---- Determinism floor: color_palette. # Re-collect non-grayscale slide colors and check against the rubric # palette. One safety_net finding per off-palette hex per slide. allowed_palette = _allowed_palette_hexes(rubric) palette_rule_id = _palette_rule_id(rubric) if allowed_palette: for n in range(1, slide_count + 1): env = normalised[n - 1] offending = _offpalette_hexes_for_slide( ctx.parsed_deck, n, allowed_palette ) for hex_str in offending: env.findings.append( _build_palette_safety_net_finding( n, hex_str, rule_id=palette_rule_id ) ) # Recompute severity summary. summary = SeverityCounts() for env in normalised: for f in env.findings: if f.severity == "high": summary.high += 1 elif f.severity == "medium": summary.medium += 1 elif f.severity == "low": summary.low += 1 return FinalAuditResult( job_id=job_id, file_name=file_name, slide_count=slide_count, summary=summary, slides=normalised, errors=errors, ) def _evidence_overlaps_any_hit(evidence: str, hits: list[Hit]) -> bool: """True if *evidence* shares text with at least one hit's context window.""" if not evidence: return False e_low = evidence.lower() for hit in hits: # Direct: the marker term itself appears in the evidence. if hit.term.lower() in e_low: return True # Or: the evidence quotes a chunk of the context window. cw = hit.context_window.strip().lower() if cw and cw in e_low: return True # Or: the context window contains a meaningful slice of the evidence. if e_low and len(e_low) >= 12 and e_low in cw: return True return False def _hit_is_covered(hit: Hit, findings: list[FindingExtended]) -> bool: """True if any finding's evidence covers the marker term in *hit*.""" needle = hit.term.lower() cw = hit.context_window.strip().lower() for f in findings: ev = f.evidence.lower() if not ev: continue if needle in ev: return True if cw and cw in ev: return True return False def _build_safety_net_finding( slide_n: int, hit: Hit, *, must_flag_meta: dict ) -> FindingExtended: """Create a deterministic safety-net Finding for an unmatched marker hit.""" marker_def = must_flag_meta.get(hit.term) if marker_def is None: # Fallback: case-insensitive match if the rubric uses a different case. for k, v in must_flag_meta.items(): if k.lower() == hit.term.lower(): marker_def = v break if marker_def is None: # Last-ditch defaults — keeps the must-flag bar even with rubric drift. category = "writing_style" severity = "high" title_template = f"Visible internal marker: {hit.term}" rule_id = "writing_style.no_internal_comments" else: category = marker_def.category severity = marker_def.severity_default title_template = marker_def.title_template rule_id = marker_def.rule_id title = f"{title_template} (slide {slide_n})" description = ( f"Slide {slide_n} contains the must-flag marker {hit.term!r} in " f"{hit.source} content. Internal markers must be removed before the " f"deck is sent to a client." ) evidence = hit.context_window.strip() or hit.term suggested_fix = ( f"Remove the {hit.term!r} text from slide {slide_n} and verify the " f"surrounding content reads cleanly without it." ) return FindingExtended( category=category, severity=severity, # type: ignore[arg-type] # validated by Pydantic confidence=1.0, title=title, description=description, evidence=evidence, suggested_fix=suggested_fix, guideline_reference=rule_id, finding_meta=FindingMeta(source="safety_net", must_flag=True), ) # --------------------------------------------------------------------------- # Confidentiality + palette deterministic helpers (mirror slide_bundle logic) # --------------------------------------------------------------------------- def _canonical_confidentiality_text(rubric: Any) -> str | None: """Return the canonical confidentiality text from the rubric (or None). Mirrors ``slide_bundle._canonical_confidentiality_text`` so ``_finalise`` can run the deterministic check without importing the bundle module (which would import the Agents SDK transitively). """ for rule in rubric.rules: if ( rule.category == "confidentiality_statement" and rule.metadata and rule.metadata.canonical_text ): return rule.metadata.canonical_text return None def _confidentiality_rule_id(rubric: Any) -> str: """Return the rule_id for the confidentiality rule (best-effort).""" for rule in rubric.rules: if rule.category == "confidentiality_statement": return rule.id return "confidentiality_statement.present_and_positioned" def _allowed_palette_hexes(rubric: Any) -> list[str]: """Return the allowed-hex list for color_palette (uppercase, no '#').""" for rule in rubric.rules: if ( rule.category == "color_palette" and rule.metadata and rule.metadata.allowed_hex ): return [h.lstrip("#").upper() for h in rule.metadata.allowed_hex] return [] def _palette_rule_id(rubric: Any) -> str: """Return the rule_id for the color_palette rule (best-effort).""" for rule in rubric.rules: if rule.category == "color_palette": return rule.id return "color_palette.approved_colors_only" def _confidentiality_violates(cc: ConfidentialityCheck) -> bool: """True iff the confidentiality check should produce a high-severity finding. Violations: * statement absent entirely (``present == false``), OR * statement present but mispositioned (``position_hint != 'footer'``). The rubric is explicit: footer is the only acceptable position. Header / body are violations even when the text matches verbatim. """ if not cc.present: return True if cc.position_hint != "footer": return True return False def _build_confidentiality_safety_net_finding( slide_n: int, cc: ConfidentialityCheck, *, rule_id: str, ) -> FindingExtended: """Synthesize a deterministic ``confidentiality_statement`` finding. Always severity=high (the rubric default for this rule). The evidence string is non-empty by construction so the boundary validator keeps it. """ if not cc.present: title = f"Add confidentiality statement (slide {slide_n})" description = ( f"Slide {slide_n} is missing the canonical confidentiality " f"statement. The brand rubric requires it on every slide in " f"Calibri Body 8pt at the master footer position." ) evidence = ( f"No shape on slide {slide_n} contains the canonical " f"confidentiality text." ) suggested_fix = ( "Insert the canonical confidentiality statement in the master " "footer position with Calibri Body 8pt formatting." ) else: title = ( f"Move confidentiality statement to footer (slide {slide_n})" ) description = ( f"Slide {slide_n} contains the confidentiality statement but it " f"appears in the {cc.position_hint!r} region. The rubric " f"requires footer placement (mid-Y ≥ 0.80)." ) excerpt = (cc.matched_excerpt or "").strip() evidence = ( f"Confidentiality statement found at {cc.position_hint!r} " f"position" + (f" (shape {cc.matching_shape_id})" if cc.matching_shape_id else "") + (f": {excerpt!r}" if excerpt else "") ) suggested_fix = ( "Reposition the confidentiality statement to the master footer " f"slot on slide {slide_n}." ) return FindingExtended( category="confidentiality_statement", severity="high", # type: ignore[arg-type] confidence=1.0, title=title, description=description, evidence=evidence, suggested_fix=suggested_fix, guideline_reference=rule_id, finding_meta=FindingMeta(source="safety_net", must_flag=False), ) def _is_grayscale_hex(hex_norm: str) -> bool: """True if RRGGBB has R==G==B (pure grayscale).""" if len(hex_norm) != 6: return False try: r, g, b = ( int(hex_norm[0:2], 16), int(hex_norm[2:4], 16), int(hex_norm[4:6], 16), ) except ValueError: return False return r == g == b def _offpalette_hexes_for_slide( deck: Any, slide_n: int, allowed: list[str] ) -> list[str]: """Return de-duped, stable-ordered off-palette hex strings on the slide. Mirrors ``slide_bundle._collect_slide_hex_colors`` + per-color ``in_palette`` check. The output is the set of run-color hexes that (a) appear on the slide, (b) are non-grayscale, and (c) are not in the allowed palette. Ordering is first-seen — important for determinism so repeat runs yield the same finding ordering. """ if slide_n < 1 or slide_n > deck.slide_count: return [] allowed_set = {a.upper() for a in allowed} seen: list[str] = [] seen_set: set[str] = set() slide = deck.slides[slide_n - 1] for sh in slide.shapes: for run in sh.runs: if run.color_rgb is None: continue norm = run.color_rgb.lstrip("#").upper() if not norm or len(norm) != 6: continue if _is_grayscale_hex(norm): continue if norm in seen_set: continue if norm in allowed_set: continue seen_set.add(norm) seen.append(norm) return seen def _build_palette_safety_net_finding( slide_n: int, hex_norm: str, *, rule_id: str ) -> FindingExtended: """Synthesize a deterministic ``color_palette`` finding for one off-palette hex.""" pretty = f"#{hex_norm.upper()}" title = f"Off-palette color {pretty} (slide {slide_n})" description = ( f"Slide {slide_n} uses {pretty}, which is not in the approved " f"Farient brand palette. Replace it with the closest approved hex." ) evidence = f"Run color {pretty} detected in slide {slide_n} text shapes." suggested_fix = ( f"Replace {pretty} with a brand-approved palette color on slide " f"{slide_n}." ) return FindingExtended( category="color_palette", severity="medium", # type: ignore[arg-type] confidence=1.0, title=title, description=description, evidence=evidence, suggested_fix=suggested_fix, guideline_reference=rule_id, finding_meta=FindingMeta(source="safety_net", must_flag=False), ) # --------------------------------------------------------------------------- # Public exports for tests # --------------------------------------------------------------------------- __all__ = [ "MUST_FLAG_TERMS", "MAX_CONCURRENT_SLIDES", "MAX_RETRY_ATTEMPTS", "SlideBriefing", "ConsistencyBriefing", "MergeInput", "_run_with_retry", "_is_retriable", "_retry_after_hint", "_build_safety_net_finding", "_build_confidentiality_safety_net_finding", "_build_palette_safety_net_finding", "_confidentiality_violates", "_offpalette_hexes_for_slide", "_finalise", "_max_severity", "_python_fallback_merge", "run_audit", ]