summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/tests/test_second_look_diff.py
blob: e6eb2f58e73d2c7ccf6957ae16ab0a2915a6d348 (plain)
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
"""The second look judges a candidate against the diff the first look read.

It used to get the first 8,000 characters, with the rule that code on no + line
of the diff it is shown is pre-existing. A finding further on failed that
whatever the model did.
"""
import sys

import pytest

import llm
import review_api
from test_reviewer_tools import sdk  # noqa: F401  (a fixture)

SINK = "+    os.system(cmd)  # the candidate"


def _files():
    padding = "@@ -0,0 +1,30 @@\n" + "+x = 1  # padding line for the diff\n" * 30
    files = [(f"src/mod{i:02}.py", padding) for i in range(14)]
    return files + [("src/handler.py", "@@ -0,0 +1,2 @@\n+def run(cmd):\n" + SINK + "\n")]


@pytest.fixture
def prompts(sdk, monkeypatch):  # noqa: F811
    """The text each stage of the review was given."""
    module, seen = sys.modules["claude_agent_sdk"], []
    answer = module.query

    async def query(prompt, options):
        text = prompt if isinstance(prompt, str) else "".join(
            [str(m["message"]["content"]) async for m in prompt])
        seen.append(text)
        async for msg in answer(text, options):
            yield msg

    monkeypatch.setattr(module, "query", query)
    return seen


def test_every_stage_reads_the_same_diff(prompts, tmp_path):
    files = _files()
    llm.agentic_review(str(tmp_path), files, [name for name, _ in files])
    diff = "\n\n".join(f"=== DIFF: {name} ===\n{text}" for name, text in files)
    assert len(diff) > 8000
    assert len(prompts) == 3
    for prompt in prompts:
        assert diff in prompt
    assert "adversarially try to DISPROVE" in prompts[-1]


def test_a_cut_file_is_marked_in_both_looks(prompts, tmp_path):
    big = "@@ -0,0 +1 @@\n" + "+y = 2\n" * (review_api.DIFF_PER_FILE_BYTES // 5)
    llm.agentic_review(str(tmp_path), [("big.py", big)], ["big.py"])
    shown = llm._cap_files_for_prompt([("big.py", big)])[0][1]
    assert len(shown) < len(big)
    assert all(shown in prompt for prompt in prompts)


def test_importable_prompt_has_the_whole_diff():
    diff = "+padding\n" * 2000 + SINK
    assert diff in review_api.build_refute_prompt([{"filePath": "a.py"}], diff)
    raw = "+padding\n" * review_api.DIFF_TOTAL_BYTES
    prompt = review_api.build_refute_prompt([{"filePath": "a.py"}], raw)
    assert len(prompt) < 2 * review_api.DIFF_TOTAL_BYTES and "diff truncated" in prompt