File size: 11,021 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""End-to-end acceptance test for the Jacobs deck must-flag guarantee.

Strategy
--------
* Patches ``agents.runner.Runner.run`` so every agent call returns an empty
  ``SlideFindings`` / ``DeckFindings`` / ``FinalAuditResult`` (no agent findings).
* Posts the real Jacobs .pptx through the FastAPI TestClient.
* Drives the pipeline manually (TestClient tears down the asyncio loop between
  requests so the background task never completes on its own).
* Asserts the deterministic safety-net injection in ``agents/runner.py`` still
  produces the 5 must-flag findings on slides 1, 6, 7, 23, 24.

This test is the authoritative proof of the "safety-net guarantee" β€” i.e. the
must-flag acceptance bar holds in Python regardless of agent quota or LLM behaviour.
"""
from __future__ import annotations

import asyncio
import inspect
import json
import time
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import patch

import pytest
from fastapi.testclient import TestClient

from agents.output_schemas import (
    DeckFindings,
    FinalAuditResult,
    FindingMeta as AgentFindingMeta,
    SeverityCounts as AgentSeverityCounts,
    SlideEnvelopeExtended as AgentSlideEnvelopeExtended,
    SlideFindings,
)
from schemas.api import AuditExportJson, AuditSlidesResponse

# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------

_DOC_REF = Path(__file__).parents[3] / "Doc Reference"
JACOBS_PATH = _DOC_REF / (
    "20260429 Jacobs Assessment of Compensation Peers - DRAFT 20260327 (3).pptx"
)

MUST_FLAG_SLIDES = {1, 6, 7, 23, 24}
MUST_FLAG_MARKER_SUBSTRINGS = {
    1: "DRAFT",
    6: "TW question",
    7: "TW question",
    23: "Page to be updated",
    24: "Page to be updated",
}


# ---------------------------------------------------------------------------
# Empty-agent runner β€” returns zero findings from every agent call
# ---------------------------------------------------------------------------


class _EmptyAgentRunner:
    """Fake runner that returns empty outputs from every agent invocation.

    The safety-net injection in ``agents/runner._finalise`` must still inject
    the 5 must-flag findings based on the pre-agent marker scan alone.
    """

    def __init__(self):
        self.calls: list[dict[str, Any]] = []

    async def run(self, agent, *, input=None, context=None, max_turns=10, **_):
        self.calls.append({"agent_name": agent.name})
        data = {}
        try:
            data = json.loads(input) if isinstance(input, str) else {}
        except (json.JSONDecodeError, TypeError):
            pass

        if agent.name == "Slide Reviewer Agent":
            slide_n = int(data.get("slide_number", 1))
            result = SlideFindings(slide_number=slide_n, findings=[])
        elif agent.name == "Deck Consistency Agent":
            result = DeckFindings(findings=[])
        elif agent.name == "Lead Auditor Agent":
            slide_count = int(data.get("slide_count", 0))
            result = FinalAuditResult(
                job_id=data.get("job_id", ""),
                file_name=data.get("file_name", ""),
                slide_count=slide_count,
                summary=AgentSeverityCounts(),
                slides=[
                    AgentSlideEnvelopeExtended(
                        slide_number=n, image_url=None, findings=[]
                    )
                    for n in range(1, slide_count + 1)
                ],
                errors=[],
            )
        else:
            raise AssertionError(f"Unexpected agent name {agent.name!r}")

        return SimpleNamespace(final_output=result)


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture
def jobs_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    root = tmp_path / "audits"
    root.mkdir(parents=True, exist_ok=True)
    monkeypatch.setenv("AUDIT_JOBS_ROOT", str(root))
    monkeypatch.setenv("MAX_UPLOAD_MB", "60")
    return root


@pytest.fixture
def app_and_runner(jobs_root):
    import services.renderer as renderer_module

    with patch.object(renderer_module, "warmup", lambda: None):
        from main import create_app

        app = create_app()
        runner = _EmptyAgentRunner()
        app.state.agent_runner_override = runner
        return app, runner


@pytest.fixture
def client(app_and_runner):
    app, _ = app_and_runner
    return TestClient(app)


# ---------------------------------------------------------------------------
# Helper: drive the pipeline synchronously in the test process
# ---------------------------------------------------------------------------


def _run_pipeline(job_id: str, jobs_root: Path, runner) -> dict[str, Any]:
    from services.jobs import JobStore
    from services.orchestrator import run_audit_pipeline

    store = JobStore(jobs_root)
    asyncio.run(run_audit_pipeline(job_id, store=store, runner=runner))

    # Return the final job record as a dict via the store.
    return store.read(job_id).__dict__


def _poll_until_terminal(
    client: TestClient, job_id: str, *, timeout_s: float = 5.0
) -> dict[str, Any]:
    deadline = time.time() + timeout_s
    last: dict[str, Any] | None = None
    while time.time() < deadline:
        r = client.get(f"/api/audits/{job_id}")
        assert r.status_code == 200, r.text
        last = r.json()
        if last["status"] in ("reviewed", "partial", "failed"):
            return last
        time.sleep(0.05)
    raise AssertionError(f"job {job_id} never reached terminal: last={last!r}")


# ---------------------------------------------------------------------------
# Core acceptance test
# ---------------------------------------------------------------------------


@pytest.mark.skipif(not JACOBS_PATH.exists(), reason="Jacobs deck not present")
def test_jacobs_must_flag_safety_net(
    app_and_runner, client: TestClient, jobs_root: Path
):
    """POST Jacobs deck, run pipeline with empty agents, assert 5 must-flag findings."""
    app, runner = app_and_runner

    # 1. Upload the Jacobs deck.
    with JACOBS_PATH.open("rb") as f:
        post_resp = client.post(
            "/api/audits",
            files={
                "file": (
                    JACOBS_PATH.name,
                    f,
                    "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                )
            },
        )
    assert post_resp.status_code == 200, post_resp.text
    job_id = post_resp.json()["job_id"]
    assert job_id

    # 2. Drive the pipeline (TestClient's event-loop is torn down between calls).
    _run_pipeline(job_id, jobs_root, runner)

    # 3. Poll status β€” should be terminal.
    status = _poll_until_terminal(client, job_id)
    assert status["status"] in ("reviewed", "partial"), (
        f"Expected reviewed/partial, got {status['status']!r}. "
        f"Errors: {status.get('errors')}"
    )

    # 4. GET /api/audits/{id}/slides β€” extended shape.
    slides_resp = client.get(f"/api/audits/{job_id}/slides")
    assert slides_resp.status_code == 200, slides_resp.text
    slides_body = slides_resp.json()

    # Validate full shape.
    validated_slides = AuditSlidesResponse.model_validate(slides_body)

    # 4a. Exactly 33 slides.
    assert slides_body["slide_count"] == 33, (
        f"Expected 33 slides, got {slides_body['slide_count']}"
    )
    assert len(slides_body["slides"]) == 33

    # 4b. At least 5 findings tagged must_flag=true.
    all_extended_findings = [
        f
        for slide in slides_body["slides"]
        for f in slide["findings"]
    ]
    must_flag_findings = [
        f for f in all_extended_findings if f["finding_meta"]["must_flag"] is True
    ]
    assert len(must_flag_findings) >= 5, (
        f"Expected β‰₯5 must_flag findings, got {len(must_flag_findings)}"
    )

    # 4c. Slides 1, 6, 7, 23, 24 each carry at least one safety_net finding
    #     with the expected marker substring in evidence.
    slides_by_n = {s["slide_number"]: s for s in slides_body["slides"]}
    for slide_n, marker_substr in MUST_FLAG_MARKER_SUBSTRINGS.items():
        slide = slides_by_n.get(slide_n)
        assert slide is not None, f"Slide {slide_n} missing from response"

        safety_net_findings = [
            f
            for f in slide["findings"]
            if f["finding_meta"]["source"] == "safety_net"
            and f["finding_meta"]["must_flag"] is True
            and f["severity"] == "high"
        ]
        assert len(safety_net_findings) >= 1, (
            f"Slide {slide_n}: expected β‰₯1 safety_net high finding, "
            f"got {len(safety_net_findings)}. All findings: {slide['findings']}"
        )

        # At least one safety_net finding's evidence contains the marker substring.
        evidences = [f["evidence"] for f in safety_net_findings]
        matched = any(marker_substr.lower() in ev.lower() for ev in evidences)
        assert matched, (
            f"Slide {slide_n}: no safety_net finding evidence contains "
            f"{marker_substr!r}. Evidences: {evidences}"
        )

    # 5. GET /api/audits/{id}/export?fmt=json β€” strict shape.
    export_resp = client.get(f"/api/audits/{job_id}/export?fmt=json")
    assert export_resp.status_code == 200, export_resp.text
    export_body = export_resp.json()

    # 5a. Validates against AuditExportJson schema (additionalProperties: false).
    validated_export = AuditExportJson.model_validate(export_body)
    schema = AuditExportJson.model_json_schema()
    assert schema.get("additionalProperties") is False

    # 5b. Export contains the 5 must-flag findings (evidence contains marker).
    #     The strict export strips finding_meta; we check evidence substrings.
    export_slides_by_n = {s["slide_number"]: s for s in export_body["slides"]}
    for slide_n, marker_substr in MUST_FLAG_MARKER_SUBSTRINGS.items():
        slide = export_slides_by_n.get(slide_n)
        assert slide is not None, f"Export slide {slide_n} missing"
        evidences = [f["evidence"] for f in slide["findings"]]
        matched = any(marker_substr.lower() in ev.lower() for ev in evidences)
        assert matched, (
            f"Export slide {slide_n}: no finding evidence contains "
            f"{marker_substr!r}. Evidences: {evidences}"
        )

    # 6. GET /api/audits/{id}/export?fmt=md β€” Markdown export.
    md_resp = client.get(f"/api/audits/{job_id}/export?fmt=md")
    assert md_resp.status_code == 200, md_resp.text
    md_text = md_resp.text

    # Must contain all three marker substrings somewhere in the markdown.
    for marker in ("DRAFT", "TW question", "Page to be updated"):
        assert marker in md_text, (
            f"Markdown export missing marker {marker!r}. "
            f"(first 2000 chars): {md_text[:2000]}"
        )