Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

134 KB
Raw Blame
"""Architecture fences: the invariants cross-user safety rests on.

Two invariants argued during the OpenWebUI-advisory mapping were
assertions, not contracts. These tests pin them -- and run the *same*
scanner scripts the pre-commit hooks run, invoked the way pre-commit
invokes them (repo-root cwd, repo-relative paths), so the hook and the
contract cannot drift:

1. **Per-user isolation (smoke check)**: every construction of a
   user-data service/session under the routers, ``research_library/``
   and ``web/services/`` passes a username-named argument explicitly.
   Where that username came from (it must be the ``require_auth``-derived
   one) is enforced for router call sites by
   tests/security/test_cross_user_isolation_census.py, not here.
2. **Web-layer file-serving references are fenced**: report artifacts
   land in an install-shared directory whose cross-user safety rests on
   root confinement, no path disclosure, and no serving route. Any
   ``FileResponse`` / ``StaticFiles`` / ``StreamingResponse`` reference
   (or star import) under ``web/`` outside the hook's per-file
   ALLOWED_FILES is flagged; LDR's serving wrappers
   (``WorkerCleanupStreamingResponse``) must be handed a same-module
   generator call; and a serving call referencing the outputs directory
   inline is flagged everywhere, allowlisted files included.

Plus: ``_generate_report_path`` (currently without production callers)
yields collision-free names, as preventive hardening for the shared
directory.
"""

from __future__ import annotations

import ast
import os
import subprocess
import sys
from importlib import import_module
from pathlib import Path

import pytest

from local_deep_research.web.services import research_service

REPO_ROOT = Path(__file__).resolve().parents[2]
HOOKS = REPO_ROOT / ".pre-commit-hooks"
sys.path.insert(0, str(HOOKS))

# Hook filenames are hyphenated, so they must be imported by string via
# import_module (the same idiom tests/security/test_sensitive_logging_hook.py
# and tests/hooks/test_hook_common.py use).
_isolation_hook = import_module("check-per-user-isolation")
_reports_hook = import_module("check-reports-dir-not-served")

# Read the scopes from the hook modules themselves, so the contract
# scans exactly what the hooks fence.
ISOLATION_DIRS = list(_isolation_hook.ISOLATION_SCAN_DIRS)
WEB_DIR = _reports_hook.FENCED_PREFIX
ISOLATION_HOOK = "check-per-user-isolation.py"
REPORTS_HOOK = "check-reports-dir-not-served.py"

# Near-actual *.py counts per scanned dir (actual minus 3; minus 4 for
# web/, which has 71), so a rename, typo or wholesale move that shrinks
# a scan fails loudly.
MIN_PY_FILES = {
    "src/local_deep_research/web/routers/": 19,
    "src/local_deep_research/research_library/": 43,
    "src/local_deep_research/web/services/": 5,
    "src/local_deep_research/web/": 67,
}


def _files_under(rel_dirs: list[str]) -> list[str]:
    """Repo-relative paths (pre-commit style) of the *.py files under."""
    files: list[str] = []
    for rel in rel_dirs:
        files.extend(
            p.relative_to(REPO_ROOT).as_posix()
            for p in (REPO_ROOT / rel).rglob("*.py")
        )
    return files


def _run_hook(
    script: str,
    files: list[str],
    cwd: Path = REPO_ROOT,
    hooks_dir: Path = HOOKS,
    env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess:
    return subprocess.run(
        [sys.executable, str(hooks_dir / script), *files],
        capture_output=True,
        text=True,
        timeout=120,
        cwd=cwd,
        env=env,
    )


def _write(root: Path, rel: str, source: str) -> str:
    target = root / rel
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(source, encoding="utf-8")
    return rel


def _mirror_hooks(root: Path) -> Path:
    """Copy both hook scripts into ``root/.pre-commit-hooks``.

    The hooks derive REPO_ROOT from their own location, so the copies
    treat ``root`` as the repository: fixtures written under it get the
    real scope filter and allowlist, exactly as in-repo files would.
    """
    hooks = root / ".pre-commit-hooks"
    hooks.mkdir(parents=True, exist_ok=True)
    for script in (ISOLATION_HOOK, REPORTS_HOOK):
        (hooks / script).write_text(
            (HOOKS / script).read_text(encoding="utf-8"), encoding="utf-8"
        )
    return hooks


class TestFenceCoverageFloors:
    def test_scanned_dirs_exist_and_feed_the_scanners(self):
        """Vacuous-pass guard for the tree scans below.

        If a fenced dir were renamed or its path typo'd, ``_files_under()``
        would yield nothing and the scans would pass vacuously over an
        empty list. Pinning on-disk existence and a non-trivial ``*.py``
        floor per scan makes that case fail loudly.
        """
        scanned = ISOLATION_DIRS + [WEB_DIR]
        missing = [rel for rel in scanned if not (REPO_ROOT / rel).is_dir()]
        assert not missing, (
            "fence scans list dirs absent from the tree: " + ", ".join(missing)
        )
        assert sorted(scanned) == sorted(MIN_PY_FILES), (
            "scanned dirs and MIN_PY_FILES floors diverged"
        )
        for rel, floor in MIN_PY_FILES.items():
            count = len(_files_under([rel]))
            assert count >= floor, (
                f"{rel} feeds its fence scan only {count} .py files "
                f"(floor {floor}); a rename or typo shrank the scanned set"
            )
        for allowed in _reports_hook.ALLOWED_FILES:
            assert (REPO_ROOT / allowed).is_file(), (
                f"stale ALLOWED_FILES entry: {allowed}"
            )

    def test_detector_sets_pinned(self):
        """Partial-loss guard: deleting ANY detector must fail loudly.

        If a set were narrowed (a constructor or serving primitive
        dropped) or the allowlist widened, every remaining scan would
        stay green while coverage silently shrank. Pin the exact
        membership so any change must consciously update this list too.
        """
        assert _isolation_hook.ISOLATION_SCAN_DIRS == (
            "src/local_deep_research/web/routers/",
            "src/local_deep_research/research_library/",
            "src/local_deep_research/web/services/",
        ), (
            "ISOLATION_SCAN_DIRS changed; if intentional, update the "
            "pinned scope and MIN_PY_FILES with it"
        )
        assert _reports_hook.WRAPPER_SUFFIXES == (
            "StreamingResponse",
            "FileResponse",
        ), "WRAPPER_SUFFIXES changed; update the pinned tuple with it"
        assert sorted(_reports_hook.SERVING_HELPERS) == [
            "static_file_response",
        ], "SERVING_HELPERS changed; update the pinned list with it"
        assert sorted(_isolation_hook.USER_DATA_CONSTRUCTORS) == [
            "BulkDeletionService",
            "CollectionDeletionService",
            "DocumentDeletionService",
            "DownloadService",
            "FollowUpResearchService",
            "LibraryService",
            "NoteAIService",
            "NoteService",
            "get_user_db_session",
        ], (
            "USER_DATA_CONSTRUCTORS membership changed; if intentional, "
            "update the pinned expected list with it"
        )
        assert sorted(_isolation_hook.ALLOWED_ATTRIBUTE_READS) == [
            ("NoteService", "_rollback_quietly"),
        ], (
            "ALLOWED_ATTRIBUTE_READS changed; an attribute read off a "
            "constructor can construct it without a username, so a new "
            "pair needs review and a conscious update of this list"
        )
        assert sorted(_reports_hook.SERVING_PRIMITIVES) == [
            "FileResponse",
            "StaticFiles",
            "StreamingResponse",
        ], (
            "SERVING_PRIMITIVES membership changed; if intentional, "
            "update the pinned expected list with it"
        )
        assert sorted(_reports_hook.ALLOWED_FILES) == [
            "src/local_deep_research/web/dependencies/threadpool.py",
            "src/local_deep_research/web/fastapi_app.py",
            "src/local_deep_research/web/static_files.py",
        ], (
            "ALLOWED_FILES changed; a new file-serving site needs review "
            "and a conscious update of this pinned list"
        )
        parameter_text = {
            "alias",
            "description",
            "example",
            "examples",
            "pattern",
            "regex",
            "title",
        }
        for hook in (_isolation_hook, _reports_hook):
            assert {
                callee: set(positions)
                for callee, positions in hook.VALUE_ARGUMENTS.items()
            } == {
                **{
                    f"fastapi.{name}": parameter_text
                    for name in (
                        "Body",
                        "Cookie",
                        "File",
                        "Form",
                        "Header",
                        "Path",
                        "Query",
                    )
                },
                "fastapi.Depends": {"scope"},
                "pydantic.Field": {
                    "alias",
                    "description",
                    "examples",
                    "pattern",
                    "title",
                },
                "pydantic.constr": {"pattern"},
                "typing.ForwardRef": {2, "module"},
                "typing.NewType": {0, "name"},
            }, (
                "VALUE_ARGUMENTS changed; a string passed to a listed "
                "argument is exempt from parsing where its call is proven "
                "and on an approved path, so a new entry needs review and "
                "a conscious update of this pinned table"
            )
            assert hook.PLAIN_FORMS == {
                "typing.Annotated",
                "typing.Literal",
                "typing_extensions.Annotated",
                "typing_extensions.Literal",
            }, (
                "PLAIN_FORMS changed; a listed form's string members or "
                "metadata are exempt from parsing where it is proven and on "
                "an approved path, so a new entry needs review and a "
                "conscious update of this pinned set"
            )
            assert hook._GENERIC_MODULES == {
                "collections.abc",
                "typing",
                "typing_extensions",
            } and hook._GENERIC_BUILTINS == {
                "dict",
                "frozenset",
                "list",
                "set",
                "tuple",
                "type",
            }, (
                "the generic subscript heads changed; a subscript of one "
                "is a step of an approved path, so a new entry needs "
                "review and a conscious update of these pinned sets"
            )
            assert hook._DYNAMIC_NAMES == {
                "__builtins__",
                "__delattr__",
                "__dict__",
                "__import__",
                "__setattr__",
                "delattr",
                "eval",
                "exec",
                "globals",
                "import_module",
                "importlib",
                "locals",
                "modules",
                "setattr",
                "vars",
            }, (
                "_DYNAMIC_NAMES changed; a reference to one voids every "
                "proof in the file, so dropping one lets a file rewrite a "
                "proven form unseen and needs review"
            )


class TestPerUserIsolationFence:
    def test_every_user_data_construction_passes_a_username(self):
        result = _run_hook(ISOLATION_HOOK, _files_under(ISOLATION_DIRS))
        assert result.returncode == 0, (
            f"user-data access without username:\n{result.stdout}"
        )

    def test_the_scanner_catches_an_unbound_construction(self, tmp_path):
        """Mutation guard: the fence must actually fire."""
        hostile = tmp_path / "routes_violation.py"
        hostile.write_text(
            "from x import NoteService, get_user_db_session\n"
            "svc = NoteService()\n"
            "s = get_user_db_session(username=None)\n"
            "import x as ns\n"
            "t = ns.NoteService()\n"
            'u = get_user_db_session(username=f"alice")\n'
            "from x import LibraryService as LS\n"
            "v = LS()\n"
            "w = NoteService(owner=username)\n"
            "y = get_user_db_session(username=None, owner_username=u)\n"
            "z = NoteService(username, username=None)\n",
            encoding="utf-8",
        )
        attr_ok = tmp_path / "attribute_binding_ok.py"
        attr_ok.write_text(
            "from x import NoteService\n"
            "class H:\n"
            "    def __init__(self, username):\n"
            "        self.username = username\n"
            "    def go(self):\n"
            "        return NoteService(self.username)\n"
            "def kw_value(username, auth):\n"
            "    a = NoteService(username=username)\n"
            '    return get_user_db_session(username=auth["name"])\n',
            encoding="utf-8",
        )
        result = _run_hook(ISOLATION_HOOK, [str(hostile), str(attr_ok)])
        assert result.returncode == 1
        assert "routes_violation.py:2: NoteService" in result.stdout
        assert "routes_violation.py:3: get_user_db_session" in result.stdout, (
            "username=None (a literal constant) must be flagged"
        )
        assert "routes_violation.py:5: NoteService" in result.stdout, (
            "module-attribute construction (ns.NoteService()) must be flagged"
        )
        assert "routes_violation.py:6: get_user_db_session" in result.stdout, (
            'username=f"alice" (a placeholder-free f-string) must be flagged'
        )
        assert "routes_violation.py:8: LibraryService" in result.stdout, (
            "an aliased constructor import (LS = LibraryService) must be "
            "flagged under its real name"
        )
        assert "routes_violation.py:9: NoteService" in result.stdout, (
            "a username-named value under a non-username keyword "
            "(owner=username) must be flagged"
        )
        for lineno in (10, 11):
            assert f"routes_violation.py:{lineno}: " in result.stdout, (
                f"line {lineno}: a literal username= must be flagged even "
                "when another argument names a username"
            )
        assert "attribute_binding_ok" not in result.stdout, (
            "a positional self.username attribute and a non-literal "
            "username= expression must not be flagged"
        )

    def test_every_fenced_service_is_flagged_without_a_username(self, tmp_path):
        """Each constructor beyond the original four is fenced too: the
        destructive deletion services, NoteAIService, and
        FollowUpResearchService, whose ``username`` defaults to None, so
        a bare ``FollowUpResearchService()`` is exactly the defaulted
        construction the fence exists to catch. Aliased and
        module-attribute forms are flagged under the real name, and the
        router call shapes used on main pass."""
        added = (
            "DocumentDeletionService",
            "CollectionDeletionService",
            "BulkDeletionService",
            "NoteAIService",
            "FollowUpResearchService",
        )
        hostile = tmp_path / "services_violation.py"
        hostile.write_text(
            "from x import "
            + ", ".join(added)
            + "\n"
            + "".join(f"s{i} = {name}()\n" for i, name in enumerate(added))
            + "f = FollowUpResearchService(username=None)\n"
            "from x import BulkDeletionService as BDS\n"
            "b = BDS()\n"
            "import x as svc\n"
            "n = svc.NoteAIService()\n",
            encoding="utf-8",
        )
        ok = tmp_path / "services_ok.py"
        ok.write_text(
            "from x import " + ", ".join(added) + "\n"
            "def route(username, dbpw):\n"
            "    DocumentDeletionService(username)\n"
            "    CollectionDeletionService(username)\n"
            "    BulkDeletionService(\n"
            "        username\n"
            "    ).delete_documents([])\n"
            "    NoteAIService(username, dbpw=dbpw)\n"
            "    return FollowUpResearchService(username=username)\n",
            encoding="utf-8",
        )
        result = _run_hook(ISOLATION_HOOK, [str(hostile), str(ok)])
        assert result.returncode == 1
        for lineno, name in enumerate(added, start=2):
            assert f"services_violation.py:{lineno}: {name}" in result.stdout, (
                f"a bare {name}() must be flagged"
            )
        for expected, why in (
            (
                "services_violation.py:7: FollowUpResearchService",
                "username=None",
            ),
            ("services_violation.py:9: BulkDeletionService", "an import alias"),
            ("services_violation.py:11: NoteAIService", "a module attribute"),
        ):
            assert expected in result.stdout, f"{why} must be flagged"
        assert "services_ok" not in result.stdout, (
            "the username-passing call shapes used by the routers must pass"
        )

    def test_a_literal_under_any_username_named_keyword_is_flagged(
        self, tmp_path
    ):
        """The literal check must apply to EVERY keyword whose name
        contains 'username', not just the exact 'username' keyword: a
        literal owner_username, and a literal owner_username alongside
        a non-literal positional username, are both flagged. A
        non-literal owner_username= expression is accepted, as
        documented."""
        hostile = tmp_path / "owner_username.py"
        hostile.write_text(
            "from x import NoteService, get_user_db_session\n"
            "a = get_user_db_session(owner_username=None)\n"
            'b = NoteService(username, owner_username="alice")\n',
            encoding="utf-8",
        )
        ok = tmp_path / "owner_username_ok.py"
        ok.write_text(
            "from x import NoteService\n"
            "def go(username, u):\n"
            "    return NoteService(username, owner_username=u)\n",
            encoding="utf-8",
        )
        result = _run_hook(ISOLATION_HOOK, [str(hostile), str(ok)])
        assert result.returncode == 1
        assert "owner_username.py:2: get_user_db_session" in result.stdout, (
            "a literal owner_username=None must be flagged"
        )
        assert "owner_username.py:3: NoteService" in result.stdout, (
            "a literal owner_username= must be flagged even when a "
            "non-literal positional username argument is also present"
        )
        assert "owner_username_ok" not in result.stdout, (
            "owner_username=u (a non-literal expression) must be accepted"
        )

    def test_repo_relative_invocation_applies_the_scan_scope(self, tmp_path):
        """Pre-commit passes repo-relative paths: the scope filter must
        scan every ISOLATION_SCAN_DIRS file and skip the rest."""
        hooks = _mirror_hooks(tmp_path)
        bad = "svc = NoteService()\n"
        in_scope = [
            _write(tmp_path, rel + "bad.py", bad) for rel in ISOLATION_DIRS
        ]
        out_of_scope = _write(
            tmp_path, "src/local_deep_research/other/bad.py", bad
        )
        result = _run_hook(
            ISOLATION_HOOK,
            [*in_scope, out_of_scope],
            cwd=tmp_path,
            hooks_dir=hooks,
        )
        assert result.returncode == 1
        for rel in in_scope:
            assert rel in result.stdout, f"{rel} not scanned"
        assert out_of_scope not in result.stdout

    def test_paths_are_normalised_before_the_scope_filter(self, tmp_path):
        """``..`` segments, a non-root cwd and absolute in-repo paths
        all resolve to the true repo-relative path (fail closed)."""
        hooks = _mirror_hooks(tmp_path)
        bad = "svc = NoteService()\n"
        router = ISOLATION_DIRS[0]
        _write(tmp_path, router + "bad.py", bad)
        _write(tmp_path, "src/local_deep_research/other/bad.py", bad)
        dotted = "src/local_deep_research/other/../../../" + router + "bad.py"
        result = _run_hook(
            ISOLATION_HOOK, [dotted], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, "a '..' path escaped the scan scope"
        from_subdir = router.removeprefix("src/") + "bad.py"
        result = _run_hook(
            ISOLATION_HOOK,
            [from_subdir],
            cwd=tmp_path / "src",
            hooks_dir=hooks,
        )
        assert result.returncode == 1, "a non-root cwd escaped the scope"
        result = _run_hook(
            ISOLATION_HOOK,
            [str(tmp_path / "src/local_deep_research/other/bad.py")],
            cwd=tmp_path,
            hooks_dir=hooks,
        )
        assert result.returncode == 0, (
            "an absolute in-repo path outside the scope must be skipped"
        )

    def test_a_constructor_cannot_leave_a_module_under_another_name(
        self, tmp_path
    ):
        """Cross-module rename: no rule follows a name from one module
        into another, so ``sessions.py`` re-exporting
        ``get_user_db_session as open_session`` would let a router call
        ``open_session()`` unchecked. The rename (and any loaded
        non-call reference such as ``make = NoteService``) is flagged
        where it happens; an alias keeping the constructor name behind
        leading underscores is accepted and its calls are checked in
        every importer. Type-only annotations and ALL_CAPS constant reads
        off the class are not rebindings."""
        hooks = _mirror_hooks(tmp_path)
        sessions = _write(
            tmp_path,
            "src/local_deep_research/web/services/sessions.py",
            "from ...database.session_context import (\n"
            "    get_user_db_session as open_session,\n"
            ")\n"
            "from ...database.session_context import (\n"
            "    get_user_db_session as _get_user_db_session,\n"
            ")\n"
            "from .notes import NoteService, LibraryService\n"
            "make = NoteService\n"
            "class Mine(LibraryService):\n"
            "    pass\n"
            "def ok(username, s: NoteService) -> LibraryService:\n"
            "    cap = NoteService.MAX_LEN\n"
            "    return _get_user_db_session(username)\n",
        )
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/notes_export.py",
            "from ..services.sessions import open_session, _get_user_db_session\n"
            "def a():\n"
            "    with open_session() as s:\n"
            "        return s\n"
            "def b():\n"
            "    return _get_user_db_session()\n",
        )
        result = _run_hook(
            ISOLATION_HOOK, [sessions, router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for expected, why in (
            (
                f"{sessions}:1: get_user_db_session imported as open_session",
                "a rename to a non-constructor name",
            ),
            (f"{sessions}:8: non-call reference to NoteService", "make = ..."),
            (
                f"{sessions}:9: non-call reference to LibraryService",
                "a subclass",
            ),
            (
                f"{router}:6: get_user_db_session(...) without",
                "an underscore-prefixed alias imported into another module",
            ),
        ):
            assert expected in result.stdout, f"{why} not flagged"
        for lineno in (4, 11, 12, 13):
            assert f"{sessions}:{lineno}:" not in result.stdout, (
                f"line {lineno}: an underscore alias, an annotation or an "
                "attribute read must not be flagged"
            )

    def test_attribute_reads_off_a_constructor_are_references(self, tmp_path):
        """``NoteService.__call__`` / ``get_user_db_session.__wrapped__``
        is the constructor under another name: binding it, or calling
        it without a username, must be flagged exactly like ``make =
        NoteService``, whether the class is reached by bare name or as
        a module attribute. Only ALL_CAPS constants and the pinned
        ALLOWED_ATTRIBUTE_READS pairs may be read off a constructor."""
        hooks = _mirror_hooks(tmp_path)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/dunder.py",
            "from ..services.x import NoteService, get_user_db_session\n"
            "from ..services.x import FollowUpResearchService as _FURS\n"
            "from ..services import mod\n"
            "make = NoteService.__call__\n"
            "open_session = get_user_db_session.__wrapped__\n"
            "make2 = mod.NoteService.__call__\n"
            "def a():\n"
            "    return NoteService.__call__()\n"
            "def b():\n"
            "    return FollowUpResearchService.__call__()\n"
            "def c():\n"
            "    with get_user_db_session.__call__() as s:\n"
            "        return s\n"
            "def d():\n"
            "    return _FURS.from_request()\n"
            "def ok(username, s):\n"
            "    NoteService._rollback_quietly(s)\n"
            "    cap = mod.NoteAIService.MAX_CLAIMS_PER_NOTE\n"
            "    return NoteService(username), cap\n",
        )
        result = _run_hook(
            ISOLATION_HOOK, [router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for lineno, name, attr in (
            (4, "NoteService", "__call__"),
            (5, "get_user_db_session", "__wrapped__"),
            (6, "NoteService", "__call__"),
            (8, "NoteService", "__call__"),
            (10, "FollowUpResearchService", "__call__"),
            (12, "get_user_db_session", "__call__"),
            (15, "FollowUpResearchService", "from_request"),
        ):
            expected = (
                f"{router}:{lineno}: non-call reference to {name} (via .{attr}:"
            )
            assert expected in result.stdout, f"{expected!r} not flagged"
        for lineno in (16, 17, 18, 19):
            assert f"{router}:{lineno}:" not in result.stdout, (
                f"line {lineno}: an allowlisted attribute read, an ALL_CAPS "
                "constant or a username-passing call must be accepted"
            )

    def test_evaluated_annotations_are_references(self, tmp_path):
        """An annotation is exempt only while it is just a type. FastAPI
        CALLS the annotated class of a ``Depends()`` parameter (and
        every ``Depends(f)`` target), filling ``username`` from the
        request (``?username=victim``); a walrus in an annotation binds
        the constructor in the enclosing scope (annotations are
        evaluated eagerly before 3.14). Each shape below is a reference;
        a plain type annotation, a non-constructor ``Depends()`` and an
        auth dependency in ``Annotated`` are not."""
        hooks = _mirror_hooks(tmp_path)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/injected.py",
            "from dataclasses import dataclass\n"
            "from typing import Annotated\n"
            "import fastapi\n"
            "from fastapi import Depends as D\n"
            "from ..services.x import NoteService, get_user_db_session\n"
            "def a(svc: NoteService = D()):\n"
            "    return svc\n"
            "def b(svc: Annotated[NoteService, D()]):\n"
            "    return svc\n"
            "def c(svc: Annotated[NoteService, D(NoteService)]):\n"
            "    return svc\n"
            "def d(db: Annotated[object, D(get_user_db_session)]):\n"
            "    return db\n"
            "def e(db: Annotated[object, D(get_user_db_session.__wrapped__)]):\n"
            "    return db\n"
            "def f(*, svc: NoteService = fastapi.Security(scopes=['x'])):\n"
            "    return svc\n"
            "def g(svc: 'NoteService' = D(None)):\n"
            "    return svc\n"
            "x: (open_session := get_user_db_session) = 1\n"
            "def h(a: (make := NoteService) = None):\n"
            "    return make()\n"
            "@dataclass\n"
            "class Deps:\n"
            "    svc: NoteService = D()\n"
            "def ok(\n"
            "    username,\n"
            "    s: NoteService,\n"
            "    csrf_protect: CsrfProtect = D(),\n"
            "    user: Annotated[str, D(require_auth)] = None,\n"
            ") -> NoteService:\n"
            "    svc: NoteService = NoteService(username)\n"
            "    return svc\n"
            "dep = D()\n"
            "def i(svc: NoteService = dep):\n"
            "    return svc\n"
            "from typing import Annotated as A\n"
            "def j(svc: A[NoteService, dep]):\n"
            "    return svc\n"
            "def typed(\n"
            "    s: NoteService = None,\n"
            "    t: dict[str, NoteService] | None = None,\n"
            "    u: A[NoteService, 'a constant'] = None,\n"
            ") -> NoteService:\n"
            "    return s\n"
            "def l(a: register(NoteService)):\n"
            "    return a\n",
        )
        result = _run_hook(
            ISOLATION_HOOK, [router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for lineno, name, why in (
            (6, "NoteService", "a bare Depends() default"),
            (8, "NoteService", "Annotated[..., Depends()]"),
            (10, "NoteService", "Depends(NoteService) inside Annotated"),
            (12, "get_user_db_session", "Depends(f) inside Annotated"),
            (14, "get_user_db_session", "Depends(f.__wrapped__)"),
            (16, "NoteService", "a qualified Security(...) default"),
            (18, "NoteService", "a quoted forward reference + Depends(None)"),
            (20, "get_user_db_session", "a walrus in a variable annotation"),
            (21, "NoteService", "a walrus in a parameter annotation"),
            (25, "NoteService", "a Depends() dataclass field"),
            (35, "NoteService", "a Depends() bound to a name"),
            (38, "NoteService", "an aliased Annotated with a name"),
            (46, "NoteService", "a call inside a plain annotation"),
        ):
            expected = f"{router}:{lineno}: non-call reference to {name}"
            assert expected in result.stdout, f"{why} not flagged"
        for lineno in (*range(26, 35), *range(40, 46)):
            assert f"{router}:{lineno}:" not in result.stdout, (
                f"line {lineno}: a type-only annotation, a non-constructor "
                "Depends() or an auth dependency must be accepted"
            )

    def test_quoted_starred_and_nested_annotations_are_references(
        self, tmp_path
    ):
        """FastAPI evaluates a wholly quoted annotation, unpacks a starred
        ``Annotated`` element and sees a class field declared under
        ``if`` / ``try`` in the class body or defaulted by a separate
        binding of its name (``svc: T`` then ``svc = Depends()``), so
        each of these builds ``NoteService`` with ``username`` from the
        request. A string in a type position that does not parse fails
        closed; plain quoted types, ``Annotated`` doc strings and
        constant class defaults stay type-only."""
        hooks = _mirror_hooks(tmp_path)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/quoted.py",
            "from dataclasses import dataclass\n"
            "from typing import Annotated, Optional\n"
            "from fastapi import Depends\n"
            "from ..services.x import NoteService, get_user_db_session\n"
            "dep = Depends()\n"
            'def a(svc: "Annotated[NoteService, Depends()]"):\n'
            "    return svc\n"
            'def b(db: "Annotated[object, Depends(get_user_db_session)]"):\n'
            "    return db\n"
            "def c(svc: Optional[\"'Annotated[NoteService, dep]'\"]):\n"
            "    return svc\n"
            "def d(svc: Annotated[*(NoteService, dep)]):\n"
            "    return svc\n"
            "def e(svc: Annotated[*(NoteService, Depends())]):\n"
            "    return svc\n"
            "@dataclass\n"
            "class F:\n"
            "    if True:\n"
            "        svc: NoteService = Depends()\n"
            "    try:\n"
            "        db: get_user_db_session = dep\n"
            "    except ImportError:\n"
            "        pass\n"
            'def g(svc: tuple[NoteService, "not an ) expression"]):\n'
            "    return svc\n"
            'def h(svc: Annotated[NoteService, "not an ) expression"]):\n'
            "    return svc\n"
            "def ok(\n"
            '    s: "NoteService",\n'
            '    t: Optional["NoteService"] = None,\n'
            '    u: Annotated["NoteService", "a doc string"] = None,\n'
            '    v: "Annotated[NoteService, 0]" = None,\n'
            ") -> \"Optional['NoteService']\":\n"
            "    return s\n"
            "class G:\n"
            "    def m(self):\n"
            "        svc: NoteService = dep\n"
            "        return svc\n"
            "    name: NoteService\n"
            "    name = 'a constant'\n"
            "@dataclass\n"
            "class H:\n"
            "    svc: NoteService\n"
            "    svc = Depends()\n"
            "    db: get_user_db_session\n"
            "    for db in [dep]:\n"
            "        pass\n",
        )
        result = _run_hook(
            ISOLATION_HOOK, [router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for lineno, name, why in (
            (6, "NoteService", "a wholly quoted Annotated[..., Depends()]"),
            (8, "get_user_db_session", "a quoted Depends(f) in Annotated"),
            (10, "NoteService", "a doubly quoted Annotated with a name"),
            (12, "NoteService", "a starred Annotated with a name"),
            (14, "NoteService", "a starred Annotated with Depends()"),
            (19, "NoteService", "a Depends() field under if in a class"),
            (21, "get_user_db_session", "a field under try in a class"),
            (24, "NoteService", "an unparsable string in a type position"),
            (43, "NoteService", "a field defaulted by a later assignment"),
            (45, "get_user_db_session", "a field bound by a loop target"),
        ):
            expected = f"{router}:{lineno}: non-call reference to {name}"
            assert expected in result.stdout, f"{why} not flagged"
        for lineno in range(26, 42):
            assert f"{router}:{lineno}:" not in result.stdout, (
                f"line {lineno}: a quoted type, an Annotated doc string, "
                "a constant class default or a function-local annotation "
                "must be accepted"
            )

    def test_unchecked_annotation_strings_and_inherited_defaults(
        self, tmp_path
    ):
        """A string in a type position that cannot be checked (does not
        parse as an expression, e.g. ``"*[NoteService]"``, which is a
        valid ForwardRef but not an expression, or nests deeper than
        ``_MAX_QUOTE_DEPTH``) is an offender in itself. A class field
        with no binding in its own body, on a class with a base other
        than ``object`` / ``Generic`` / ``Protocol``, may inherit a
        ``Depends()`` default, so it is a reference. Exempt strings (a
        listed ``Query(description=...)`` argument, a ``Literal`` member,
        ``Annotated`` metadata) and fields of base-less classes stay
        accepted."""
        hooks = _mirror_hooks(tmp_path)
        deep = "NoteService"
        for _ in range(_isolation_hook._MAX_QUOTE_DEPTH + 1):
            deep = repr(deep)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/unchecked.py",
            "from typing import Annotated, Generic, Literal, Optional\n"
            "from typing import Protocol, TypeVar\n"
            "from fastapi import Query\n"
            "from pydantic import BaseModel\n"
            "from ..services.x import NoteService\n"
            'T = TypeVar("T")\n'
            'def a(x: "not an ) expression"):\n'
            "    return x\n"
            'def b(x: Optional["*[NoteService]"]):\n'
            "    return x\n"
            "def c(x: " + deep + "):\n"
            "    return x\n"
            "class Model(BaseModel):\n"
            "    svc: NoteService\n"
            "class Sub(Model):\n"
            "    db: NoteService\n"
            "def ok_d(\n"
            '    x: Annotated[str, Query(description="free ) text")] = None,\n'
            '    y: Literal["in progress", "a ) b"] = "a ) b",\n'
            '    z: Annotated[int, "a ) doc"] = 0,\n'
            "):\n"
            "    return x\n"
            "class Plain:\n"
            "    svc: NoteService\n"
            "class Obj(object):\n"
            "    svc: NoteService\n"
            "class Gen(Generic[T]):\n"
            "    svc: NoteService\n"
            "class Proto(Protocol):\n"
            "    svc: NoteService\n"
            "class Defaulted(BaseModel):\n"
            "    svc: NoteService = None\n",
        )
        result = _run_hook(
            ISOLATION_HOOK, [router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for lineno, what, why in (
            (7, "annotation string that cannot be checked", "unparsable"),
            (9, "annotation string that cannot be checked", "ForwardRef-only"),
            (11, "annotation string that cannot be checked", "too deep"),
            (14, "non-call reference to NoteService", "inherited default"),
            (16, "non-call reference to NoteService", "inherited (subclass)"),
        ):
            assert f"{router}:{lineno}: {what}" in result.stdout, (
                f"{why} not flagged"
            )
        for lineno in range(17, 33):
            assert f"{router}:{lineno}:" not in result.stdout, (
                f"line {lineno}: a plain-value string, a field of a "
                "base-less class or a constant default must be accepted"
            )

    def test_a_symlink_into_the_scope_is_scanned(self, tmp_path):
        """A symlink inside a scanned dir whose target lies outside it
        is still scanned: the scope accepts the lexical OR the resolved
        repo-relative path."""
        hooks = _mirror_hooks(tmp_path)
        target = _write(
            tmp_path,
            "src/local_deep_research/other/real.py",
            "svc = NoteService()\n",
        )
        link = ISOLATION_DIRS[0] + "linked.py"
        (tmp_path / link).parent.mkdir(parents=True, exist_ok=True)
        try:
            (tmp_path / link).symlink_to(tmp_path / target)
        except (OSError, NotImplementedError):
            pytest.skip("symlinks unsupported here")
        result = _run_hook(
            ISOLATION_HOOK, [link], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, "a symlink escaped the scan scope"
        result = _run_hook(
            ISOLATION_HOOK, [target], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 0, "the out-of-scope target is skipped"


class TestReportsDirNotServedFence:
    def test_no_new_file_serving_site_in_the_web_layer(self):
        result = _run_hook(REPORTS_HOOK, _files_under([WEB_DIR]))
        assert result.returncode == 0, (
            f"new HTTP file-serving site:\n{result.stdout}"
        )

    def test_absolute_in_repo_path_to_an_allowlisted_file_passes(self):
        """Absolute paths go through the repo-relative resolution, so an
        allowlisted file (which does reference FileResponse) is exempt."""
        allowed = [str(REPO_ROOT / rel) for rel in _reports_hook.ALLOWED_FILES]
        result = _run_hook(REPORTS_HOOK, allowed)
        assert result.returncode == 0, result.stdout

    def test_the_scanner_catches_serving_routes(self, tmp_path):
        """Positive controls: the fence must fire on inline outputs
        references, aliased imports and module-attribute access."""
        inline = tmp_path / "serve_inline.py"
        inline.write_text(
            "from fastapi.responses import FileResponse\n"
            "from svc import OUTPUT_DIR\n"
            "def download(name):\n"
            "    return FileResponse(OUTPUT_DIR / name)\n",
            encoding="utf-8",
        )
        bound = tmp_path / "serve_bound.py"
        bound.write_text(
            "from fastapi.responses import FileResponse as FR\n"
            "from svc import get_research_outputs_directory\n"
            "def download(name):\n"
            "    root = get_research_outputs_directory().resolve()\n"
            "    return FR(root / name)\n",
            encoding="utf-8",
        )
        attr = tmp_path / "serve_attr.py"
        attr.write_text(
            "import starlette.staticfiles as sf\n"
            "def mount(app, reports_dir):\n"
            "    app.mount('/r', sf.StaticFiles(directory=reports_dir))\n",
            encoding="utf-8",
        )
        result = _run_hook(REPORTS_HOOK, [str(inline), str(bound), str(attr)])
        assert result.returncode == 1
        for name in ("serve_inline.py", "serve_bound.py", "serve_attr.py"):
            assert name in result.stdout, f"{name} not flagged"

    def test_star_imports_and_bare_names_are_flagged(self, tmp_path):
        """Positive controls: the fence must fire on star imports and on
        bare primitive names."""
        star_ldr = tmp_path / "star_ldr.py"
        star_ldr.write_text(
            "from ..dependencies.threadpool import *\n"
            "def f(g):\n"
            "    return StreamingResponse(g())\n",
            encoding="utf-8",
        )
        star_fastapi = tmp_path / "star_fastapi.py"
        star_fastapi.write_text(
            "from fastapi.responses import *\n", encoding="utf-8"
        )
        bare = tmp_path / "bare_name.py"
        bare.write_text(
            "def f(p):\n    return FileResponse(p)\n", encoding="utf-8"
        )
        result = _run_hook(
            REPORTS_HOOK, [str(star_ldr), str(star_fastapi), str(bare)]
        )
        assert result.returncode == 1
        for expected in (
            "star_ldr.py:1: star import",
            "star_ldr.py:3: reference to StreamingResponse",
            "star_fastapi.py:1: star import",
            "bare_name.py:2: reference to FileResponse",
        ):
            assert expected in result.stdout, f"{expected!r} not flagged"

    def test_serving_wrappers_must_take_a_local_generator(self, tmp_path):
        """WorkerCleanupStreamingResponse is defined in an allowlisted
        file, so importing it is fine -- but handing it a file object, a
        path or any non-generator content is flagged, under any alias."""
        # Every name but b_decorated and b_lambda is also defined as an
        # undecorated module-level generator (def <name>(): yield ...);
        # one other binding must disqualify it. b_decorated has only
        # ONE def, which yields but is decorated (the decorator alone
        # disqualifies it); b_lambda's own body never yields (only a
        # nested lambda does, which doesn't count), so it is never a
        # generator to begin with.
        disqualified = (
            "b_assign",
            "b_walrus",
            "b_for",
            "b_with",
            "b_del",
            "b_import",
            "b_class",
            "b_except",
            "b_global",
            "b_match",
            "b_star",
            "b_rest",
            "b_decorated",
            "b_lambda",
            "b_async",
        )
        hostile = tmp_path / "wrapper_hostile.py"
        hostile.write_text(
            "from ..dependencies.threadpool import (\n"
            "    WorkerCleanupStreamingResponse,\n"
            "    WorkerCleanupStreamingResponse as W,\n"
            ")\n"
            "from ..dependencies import threadpool as tp\n"
            "def a(reports_path):\n"
            "    return WorkerCleanupStreamingResponse(open(reports_path, 'rb'))\n"
            "def b(p):\n"
            "    return W(iter(open(p, 'rb')))\n"
            "def c(p):\n"
            "    return tp.WorkerCleanupStreamingResponse(content=p)\n"
            "def d(self):\n"
            "    return W(self.body)\n"
            "Alias = WorkerCleanupStreamingResponse\n"
            "from ..dependencies.threadpool import SafeFileResponse\n"
            "def e(p):\n"
            "    return SafeFileResponse(p)\n"
            "def _load(p):\n"
            "    return open(p, 'rb')\n"
            "def f(p):\n"
            "    return W(_load(p))\n"
            "class Exporter:\n"
            "    def open(self):\n"
            "        yield b'x'\n"
            "    def stream(self):\n"
            "        yield b'x'\n"
            "def g(p):\n"
            "    return W(open(p, 'rb'))\n"
            "def h(p):\n"
            "    return W(iter(open(p, 'rb')))\n"
            "def gen_a():\n"
            "    yield b'x'\n"
            "def i(gen_a):\n"
            "    return W(gen_a())\n"
            "def gen_b():\n"
            "    yield b'x'\n"
            "def j(p):\n"
            "    def gen_b():\n"
            "        return open(p, 'rb')\n"
            "    return W(gen_b())\n"
            "def iter(x):\n"
            "    yield x\n"
            "def k():\n"
            "    return W(stream())\n"
            "def gen_c(p):\n"
            "    def inner():\n"
            "        yield b'x'\n"
            "    return open(p, 'rb')\n"
            "def m(p):\n"
            "    return W(gen_c(p))\n"
            # 51-57: a non-generator def inside a method disqualifies a
            # module-level generator of the same name.
            "def generate():\n"
            "    yield b'x'\n"
            "class Svc:\n"
            "    def dl(self, p):\n"
            "        def generate():\n"
            "            return open(p, 'rb')\n"
            "        return W(generate())\n"
            # 58-: one line per disqualifying binding kind of a name
            # that is also defined as a module-level generator.
            "def b_assign():\n    yield b''\n"
            "b_assign = lambda p: open(p, 'rb')\n"
            "def b_walrus():\n    yield b''\n"
            "if (b_walrus := None):\n    pass\n"
            "def b_for():\n    yield b''\n"
            "for b_for in []:\n    pass\n"
            "def b_with():\n    yield b''\n"
            "with ctx() as b_with:\n    pass\n"
            "def b_del():\n    yield b''\n"
            "del b_del\n"
            "def b_import():\n    yield b''\n"
            "from x import y as b_import\n"
            "def b_class():\n    yield b''\n"
            "class b_class:\n    pass\n"
            "def b_except():\n    yield b''\n"
            "try:\n    pass\nexcept Exception as b_except:\n    pass\n"
            "def b_global():\n    yield b''\n"
            "def rebind():\n    global b_global\n"
            "def b_match():\n    yield b''\n"
            "match 1:\n    case b_match:\n        pass\n"
            "def b_star():\n    yield b''\n"
            "match 1:\n    case [*b_star]:\n        pass\n"
            "def b_rest():\n    yield b''\n"
            "match 1:\n    case {**b_rest}:\n        pass\n"
            # R1: a decorator can replace the generator.
            "@reader\n"
            "def b_decorated(p):\n    yield b''\n"
            # R7: a yield only inside a nested lambda does not make the
            # outer def a generator.
            "def b_lambda(p):\n"
            "    f = lambda: (yield)\n"
            "    return open(p, 'rb')\n"
            # An async non-generator def disqualifies the name too.
            "def b_async():\n    yield b''\n"
            "def holder():\n"
            "    async def b_async(p):\n"
            "        return open(p, 'rb')\n"
            "def route_bindings(p):\n"
            "    return [\n"
            + "".join(f"        W({name}(p)),\n" for name in disqualified)
            + "    ]\n",
            encoding="utf-8",
        )
        ok = tmp_path / "wrapper_ok.py"
        ok.write_text(
            "from ..dependencies.threadpool import "
            "WorkerCleanupStreamingResponse\n"
            "def route():\n"
            "    def generate():\n"
            "        yield b'x'\n"
            "    return WorkerCleanupStreamingResponse(\n"
            "        generate(), media_type='text/event-stream'\n"
            "    )\n"
            "def route_kw():\n"
            "    def stream():\n"
            "        yield b'x'\n"
            "    return WorkerCleanupStreamingResponse(content=stream())\n"
            "def module_gen(p):\n"
            "    yield from [p]\n"
            "def route_module_gen(p):\n"
            "    return WorkerCleanupStreamingResponse(module_gen(p))\n"
            "async def agen():\n"
            "    yield b'x'\n"
            "def route_async():\n"
            "    return WorkerCleanupStreamingResponse(agen())\n",
            encoding="utf-8",
        )
        result = _run_hook(REPORTS_HOOK, [str(hostile), str(ok)])
        assert result.returncode == 1
        # 21: a same-module helper that returns open() is not a
        # generator; 28/30: open/iter are builtins, never accepted even
        # though a method (open) or a module-level generator (iter) of
        # that name exists; 34/40: a generator name shadowed by a
        # parameter or by a non-generator def of the same name; 44: a
        # class-body method is not a bare-name callee; 50: a yield in a
        # nested function does not make the outer one a generator.
        # 57: a module-level generator whose name is also a
        # non-generator def nested in a method.
        for lineno in (7, 9, 11, 13, 17, 21, 28, 30, 34, 40, 44, 50, 57):
            assert f"wrapper_hostile.py:{lineno}: " in result.stdout, (
                f"wrapper call on line {lineno} not flagged"
            )
        lines = hostile.read_text(encoding="utf-8").splitlines()
        for name in disqualified:
            lineno = lines.index(f"        W({name}(p)),") + 1
            assert f"wrapper_hostile.py:{lineno}: " in result.stdout, (
                f"W({name}(p)) on line {lineno} not flagged: {name} is "
                "disqualified by another binding or def shape"
            )
        assert "wrapper_hostile.py:14: non-call reference" in result.stdout
        assert "wrapper_ok.py" not in result.stdout, (
            "a same-module generator call must not be flagged"
        )

    def test_a_decorated_def_anywhere_disqualifies_the_name(self, tmp_path):
        """A decorator can replace the function, so a name is never a
        trusted generator if ANY def of it anywhere in the module is
        decorated -- even a def nested inside another function, and
        even though that nested def's own body does yield."""
        hostile = tmp_path / "decorated_anywhere.py"
        hostile.write_text(
            "from ..dependencies.threadpool import "
            "WorkerCleanupStreamingResponse as W\n"
            "def g():\n"
            "    yield b''\n"
            "def route(p):\n"
            "    @reader\n"
            "    def g():\n"
            "        yield b''\n"
            "    return W(g())\n",
            encoding="utf-8",
        )
        result = _run_hook(REPORTS_HOOK, [str(hostile)])
        assert result.returncode == 1
        assert "decorated_anywhere.py:8: " in result.stdout, (
            "a decorated def nested in another function must disqualify "
            "the name everywhere, including a module-level generator call"
        )

    def test_an_unaliased_import_binding_disqualifies_the_name(self, tmp_path):
        """``_other_bindings`` must bind the import's natural name, not
        only an explicit ``as`` alias: a bare ``from evil import g`` and
        a dotted ``import g.sub`` (which binds the top-level name
        ``g``) each disqualify a same-named module-level generator."""
        from_import = tmp_path / "from_import.py"
        from_import.write_text(
            "from ..dependencies.threadpool import "
            "WorkerCleanupStreamingResponse as W\n"
            "def g():\n"
            "    yield b''\n"
            "from evil import g\n"
            "def route(p):\n"
            "    return W(g())\n",
            encoding="utf-8",
        )
        dotted_import = tmp_path / "dotted_import.py"
        dotted_import.write_text(
            "from ..dependencies.threadpool import "
            "WorkerCleanupStreamingResponse as W\n"
            "def g():\n"
            "    yield b''\n"
            "import g.sub\n"
            "def route(p):\n"
            "    return W(g())\n",
            encoding="utf-8",
        )
        result = _run_hook(REPORTS_HOOK, [str(from_import), str(dotted_import)])
        assert result.returncode == 1
        assert "from_import.py:6: " in result.stdout, (
            "an unaliased 'from evil import g' must bind g and "
            "disqualify the module-level generator of the same name"
        )
        assert "dotted_import.py:6: " in result.stdout, (
            "'import g.sub' binds the top-level name g too, and must "
            "disqualify the module-level generator of the same name"
        )

    def test_star_import_disqualifies_every_generator_candidate(self, tmp_path):
        """A ``from x import *`` can rebind any name in the module,
        including one that would otherwise pass as a same-module
        generator -- so its mere presence must disqualify every
        candidate, in every scanned file (allowlisted ones included:
        the wrapper-content rule applies there too)."""
        hooks = _mirror_hooks(tmp_path)
        allowed = _write(
            tmp_path,
            "src/local_deep_research/web/fastapi_app.py",
            "from ..dependencies.threadpool import "
            "WorkerCleanupStreamingResponse as W\n"
            "from evil import *\n"
            "def g():\n"
            "    yield b''\n"
            "def route(p):\n"
            "    return W(g())\n",
        )
        result = _run_hook(
            REPORTS_HOOK, [allowed], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1
        assert f"{allowed}:6: " in result.stdout, (
            "a star import anywhere in the module must disqualify g as "
            "a trusted same-module generator, even in an allowlisted file"
        )

    def test_unparsable_files_fail_closed_and_bom_files_are_scanned(
        self, tmp_path
    ):
        """A UTF-8 BOM or a PEP 263 coding cookie must not hide a file
        from either scanner, and a file neither can parse (a syntax
        error, or nesting too deep for the parser) is reported, never
        silently skipped and never a crash."""
        serving = b"from starlette.responses import FileResponse\n"
        unbound = b"svc = NoteService()\n"
        bom = tmp_path / "bom.py"
        bom.write_bytes(b"\xef\xbb\xbf" + serving + unbound)
        latin1 = tmp_path / "latin1.py"
        latin1.write_bytes(
            b"# -*- coding: latin-1 -*-\n"
            b'label = "caf\xe9"\n' + serving + unbound
        )
        broken = tmp_path / "broken.py"
        broken.write_bytes(b"def f(:\n")
        # Nesting too deep for the parser raises RecursionError or
        # MemoryError (not SyntaxError): it must be reported, not crash
        # the run and hide the files after it.
        deep = tmp_path / "deep.py"
        deep.write_bytes(b"x = " + b"-" * 100000 + b"1\n")
        # A deep attribute chain (unlike the unary-minus chain above,
        # which raises MemoryError) raises RecursionError specifically:
        # both must be in the except tuple, not just one of them. A
        # generous C stack (seen with Python 3.12+, which bounds
        # recursion by actual C stack depth rather than
        # sys.getrecursionlimit() alone -- e.g. a 64 MB main-thread
        # stack) can let a shallower chain parse cleanly, making this
        # assertion fail spuriously and unable to exercise the
        # RecursionError arm of the hook's except tuple. Widen the
        # margin, and probe it in-process first: the hook subprocess is
        # launched with this same sys.executable (see _run_hook), so an
        # in-process ast.parse() is a faithful proxy for whether the
        # subprocess would raise too.
        recursion_depth = 2_000_000
        recursion_content = b"x = a" + b".b" * recursion_depth + b"\n"
        try:
            ast.parse(recursion_content)
        except RecursionError:
            pass
        else:
            pytest.skip(
                "ast.parse did not raise RecursionError for a "
                f"{recursion_depth}-deep attribute chain in this "
                "interpreter (unusually large C stack?); the hook "
                "subprocess shares sys.executable, so it would parse "
                "this fixture too and the RecursionError-catch "
                "assertion below cannot be exercised here"
            )
        recursion = tmp_path / "recursion.py"
        recursion.write_bytes(recursion_content)
        files = [str(deep), str(recursion), str(bom), str(latin1), str(broken)]

        result = _run_hook(REPORTS_HOOK, files)
        assert result.returncode == 1
        assert "Traceback" not in result.stderr, result.stderr
        for expected in (
            "deep.py:1: could not parse",
            "recursion.py:1: could not parse",
            "bom.py:1: import of FileResponse",
            "latin1.py:3: import of FileResponse",
            "broken.py:1: could not parse",
        ):
            assert expected in result.stdout, f"{expected!r} not reported"

        result = _run_hook(ISOLATION_HOOK, files)
        assert result.returncode == 1
        assert "Traceback" not in result.stderr, result.stderr
        for expected in (
            "deep.py:1: could not parse",
            "recursion.py:1: could not parse",
            "bom.py:2: NoteService",
            "latin1.py:4: NoteService",
            "broken.py:1: could not parse",
        ):
            assert expected in result.stdout, f"{expected!r} not reported"

    def test_non_utf8_filename_offender_is_printed_not_crashed(self, tmp_path):
        """An offender path whose filename bytes are not valid UTF-8
        must still be printable, even under a strict-UTF-8 stdout
        encoder (no locale/UTF-8-mode fallback to rescue it).

        Argv is decoded with surrogateescape, so such a filename
        reaches the hook as a Python str carrying lone surrogates.
        ``print()``-ing that str directly raises UnicodeEncodeError
        under a strict encoder; ``_safe_print`` must round-trip it
        through ``backslashreplace`` instead.
        """
        name_bytes = b"\xff\xfe.py"
        dir_bytes = os.fsencode(str(tmp_path))
        path_bytes = dir_bytes + os.sep.encode() + name_bytes
        violation = (
            b"from starlette.responses import FileResponse\n"
            b"svc = NoteService()\n"
        )
        try:
            fd = os.open(
                path_bytes, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644
            )
        except OSError:
            pytest.skip(
                "this filesystem rejects a non-UTF-8-encodable filename"
            )
        with os.fdopen(fd, "wb") as handle:
            handle.write(violation)
        # The same surrogateescape decoding argv gets, so the fixture
        # name below matches what the hook subprocess actually sees.
        path_str = os.fsdecode(path_bytes)
        env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "0"}

        for hook in (REPORTS_HOOK, ISOLATION_HOOK):
            result = _run_hook(hook, [path_str], env=env)
            assert result.returncode == 1, (hook, result.stdout, result.stderr)
            assert "Traceback" not in result.stderr, (hook, result.stderr)
            assert "\\udcff\\udcfe.py" in result.stdout, (hook, result.stdout)

    def test_unreadable_files_are_reported_not_raised(self, tmp_path):
        """An OSError while reading a file is an offender line, not a
        crash (both scanners share the fail-closed contract)."""
        missing = tmp_path / "vanished.py"
        for hook in (_reports_hook, _isolation_hook):
            tree, error = hook._parse(missing)
            assert tree is None
            assert error.startswith(f"{missing}:1: could not read ("), error

    def test_permission_denied_file_is_reported_via_subprocess(self, tmp_path):
        """A PermissionError while reading a file (unreadable via
        chmod, not merely missing) is an offender line through the
        real hook subprocess, not a crash -- for both scanners."""
        if os.geteuid() == 0:
            pytest.skip("root bypasses file permission checks")
        locked = tmp_path / "locked.py"
        locked.write_text("svc = NoteService()\n", encoding="utf-8")
        locked.chmod(0o000)
        try:
            result = _run_hook(REPORTS_HOOK, [str(locked)])
            assert result.returncode == 1
            assert "Traceback" not in result.stderr, result.stderr
            assert "could not read (PermissionError" in result.stdout, (
                result.stdout
            )

            result = _run_hook(ISOLATION_HOOK, [str(locked)])
            assert result.returncode == 1
            assert "Traceback" not in result.stderr, result.stderr
            assert "could not read (PermissionError" in result.stdout, (
                result.stdout
            )
        finally:
            locked.chmod(0o644)

    def test_inline_outputs_are_flagged_even_in_allowlisted_files(
        self, tmp_path
    ):
        """The outputs-directory arm applies to every scanned file: an
        allowlisted file (exempt from the primitive rule) and a router
        using the wrapper are both flagged for serving OUTPUT_DIR."""
        hooks = _mirror_hooks(tmp_path)
        allowed = _write(
            tmp_path,
            "src/local_deep_research/web/fastapi_app.py",
            "from fastapi.responses import FileResponse\n"
            "from fastapi.responses import FileResponse as FR\n"
            "def dl(n):\n"
            "    return FileResponse(OUTPUT_DIR / n)\n"
            "def dl2(self, n):\n"
            "    return FR(self.outputs_dir / n)\n"
            "from svc import OUTPUT_DIR as OD\n"
            "def dl3(n):\n"
            "    return FileResponse(OD / n)\n",
        )
        router = _write(
            tmp_path,
            WEB_DIR + "routers/downloads.py",
            "from ..dependencies.threadpool import "
            "WorkerCleanupStreamingResponse\n"
            "def dl(n):\n"
            "    return WorkerCleanupStreamingResponse(\n"
            "        open(get_research_outputs_directory() / n, 'rb')\n"
            "    )\n",
        )
        result = _run_hook(
            REPORTS_HOOK, [allowed, router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1
        outputs = "serves from the shared research outputs directory"
        for expected in (
            f"{allowed}:4: FileResponse(...) {outputs}",
            f"{allowed}:6: FileResponse(...) {outputs}",
            f"{allowed}:9: FileResponse(...) {outputs}",
            f"{router}:3: WorkerCleanupStreamingResponse(...) {outputs}",
        ):
            assert expected in result.stdout, f"{expected!r} not flagged"
        assert "file-serving primitive outside" not in result.stdout, (
            "the allowlisted file must stay exempt from the primitive rule"
        )

    def test_serving_helper_handed_the_outputs_dir_is_flagged(self, tmp_path):
        """Helper indirection: ``static_file_response`` lives in an
        allowlisted file, so a router calling it never references a
        primitive. Its current signature takes only ``path`` (the root is
        always STATIC_DIR), so the flagged calls below cannot run today;
        the rule is defensive, so that a future directory parameter
        cannot be handed the outputs directory (direct, aliased, as a
        module attribute, positionally or as a keyword) unflagged. A
        plain single-path call must not be flagged."""
        hooks = _mirror_hooks(tmp_path)
        router = _write(
            tmp_path,
            WEB_DIR + "routers/report_files.py",
            "from ..static_files import static_file_response\n"
            "from ..static_files import static_file_response as sfr\n"
            "from .. import static_files\n"
            "def a(n):\n"
            "    return static_file_response(n, get_research_outputs_directory())\n"
            "def b(n):\n"
            "    return sfr(n, static_dir=OUTPUT_DIR)\n"
            "def c(self, n):\n"
            "    return static_files.static_file_response(n, self.outputs_dir)\n"
            "def ok(n):\n"
            "    return static_file_response(n)\n",
        )
        result = _run_hook(
            REPORTS_HOOK, [router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1
        outputs = "serves from the shared research outputs directory"
        for lineno in (5, 7, 9):
            assert (
                f"{router}:{lineno}: static_file_response(...) {outputs}"
                in result.stdout
            ), f"line {lineno}: helper handed the outputs dir not flagged"
        assert f"{router}:11:" not in result.stdout, (
            "a plain single-path helper call must not be flagged"
        )

    @pytest.mark.parametrize(
        ("source", "flagged"),
        [
            pytest.param(
                "def a(path):\n"
                "    from ..dependencies.threadpool import (\n"
                "        WorkerCleanupStreamingResponse as respond,\n"
                "    )\n"
                "    return respond(open(path, 'rb'))\n"
                "def b(n):\n"
                "    from ..static_files import static_file_response as respond\n"
                "    return respond(n)\n",
                {5: "content"},
                id="wrapper-alias-then-helper-alias",
            ),
            pytest.param(
                "def b(n):\n"
                "    from ..static_files import static_file_response as respond\n"
                "    return respond(n)\n"
                "def a(path):\n"
                "    from ..dependencies.threadpool import (\n"
                "        WorkerCleanupStreamingResponse as respond,\n"
                "    )\n"
                "    return respond(open(path, 'rb'))\n",
                {8: "content"},
                id="helper-alias-then-wrapper-alias",
            ),
            pytest.param(
                "from typing import TYPE_CHECKING\n"
                "from ..dependencies.threadpool import (\n"
                "    WorkerCleanupStreamingResponse as respond,\n"
                ")\n"
                "if TYPE_CHECKING:\n"
                "    from ..static_files import static_file_response as respond\n"
                "def a(path):\n"
                "    return respond(open(path, 'rb'))\n"
                "handler = respond\n",
                {8: "content", 9: "non-call"},
                id="helper-alias-under-type-checking",
            ),
            pytest.param(
                "from ..static_files import (\n"
                "    static_file_response as WorkerCleanupStreamingResponse,\n"
                ")\n"
                "def a(path):\n"
                "    return WorkerCleanupStreamingResponse(open(path, 'rb'))\n",
                {5: "content"},
                id="helper-imported-under-a-wrapper-name",
            ),
        ],
    )
    def test_a_helper_alias_never_masks_a_wrapper_alias(
        self, tmp_path, source, flagged
    ):
        """Aliases are resolved file-wide, without scopes. A local name
        imported both as a serving wrapper and as a ``SERVING_HELPERS``
        function (in two functions, either order, or once under
        ``TYPE_CHECKING``) must still get the wrapper rules (content is a
        same-module generator call; no non-call reference), and a helper
        imported under a wrapper's own name stays a wrapper: fail closed,
        whichever import ``ast.walk`` happens to reach last."""
        hooks = _mirror_hooks(tmp_path)
        router = _write(tmp_path, WEB_DIR + "routers/report_files.py", source)
        result = _run_hook(
            REPORTS_HOOK, [router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        messages = {
            "content": "WorkerCleanupStreamingResponse(...) content is not",
            "non-call": "non-call reference to WorkerCleanupStreamingResponse",
        }
        for lineno, kind in flagged.items():
            expected = f"{router}:{lineno}: {messages[kind]}"
            assert expected in result.stdout, f"{expected!r} not flagged"

    def test_repo_relative_invocation_applies_the_web_scope(self, tmp_path):
        """Pre-commit passes repo-relative paths: web/ files are scanned,
        web_search_engines/ (shared name prefix) is not, and the
        allowlist matches by repo-relative path -- also for absolute
        in-repo paths and paths with '..' segments."""
        hooks = _mirror_hooks(tmp_path)
        serving = (
            "from fastapi.responses import FileResponse\n"
            "def f(p):\n"
            "    return FileResponse(p)\n"
        )
        in_scope = _write(tmp_path, WEB_DIR + "routers/bad.py", serving)
        sibling = _write(
            tmp_path, "src/local_deep_research/web_search_engines/x.py", serving
        )
        allowed = _write(
            tmp_path, next(iter(_reports_hook.ALLOWED_FILES)), serving
        )
        result = _run_hook(
            REPORTS_HOOK,
            [in_scope, sibling, allowed],
            cwd=tmp_path,
            hooks_dir=hooks,
        )
        assert result.returncode == 1
        assert in_scope in result.stdout
        assert sibling not in result.stdout
        assert allowed not in result.stdout

        result = _run_hook(
            REPORTS_HOOK,
            [str(tmp_path / allowed), str(tmp_path / sibling)],
            cwd=tmp_path,
            hooks_dir=hooks,
        )
        assert result.returncode == 0, (
            "absolute in-repo paths must get the allowlist and scope: "
            + result.stdout
        )

        dotted = (
            "src/local_deep_research/web_search_engines/../"
            + in_scope.removeprefix("src/local_deep_research/")
        )
        result = _run_hook(
            REPORTS_HOOK, [dotted], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, "a '..' path escaped the web scope"

    def test_a_serving_callable_cannot_leave_a_module_renamed(self, tmp_path):
        """Cross-module rename: a module re-exporting the wrapper as
        ``CleanupStream`` or the helper as ``serve`` lets a router call
        them with no rule applying (the router sees no serving name), so
        the renaming import is flagged where it happens, as is a helper
        rebound by assignment. An alias that keeps the role
        (``...StreamingResponse`` suffix, underscore-prefixed helper) is
        accepted and stays fenced in its importers."""
        hooks = _mirror_hooks(tmp_path)
        streaming = _write(
            tmp_path,
            WEB_DIR + "utils/streaming.py",
            "from ..dependencies.threadpool import (\n"
            "    WorkerCleanupStreamingResponse as CleanupStream,\n"
            ")\n"
            "from ..static_files import static_file_response as serve\n"
            "from ..dependencies.threadpool import (\n"
            "    WorkerCleanupStreamingResponse as CleanupStreamingResponse,\n"
            ")\n"
            "from ..static_files import static_file_response as _static_file_response\n"
            "from ..static_files import static_file_response\n"
            "serve2 = static_file_response\n",
        )
        router = _write(
            tmp_path,
            WEB_DIR + "routers/downloads.py",
            "from ..utils.streaming import CleanupStream, serve\n"
            "from ..utils.streaming import (\n"
            "    CleanupStreamingResponse, _static_file_response,\n"
            ")\n"
            "def a(name):\n"
            "    return CleanupStream(\n"
            "        open(get_research_outputs_directory() / name, 'rb')\n"
            "    )\n"
            "def b(name):\n"
            "    return serve(name, OUTPUT_DIR)\n"
            "def c(p):\n"
            "    return CleanupStreamingResponse(open(p, 'rb'))\n"
            "def d(name):\n"
            "    return _static_file_response(name, OUTPUT_DIR)\n",
        )
        result = _run_hook(
            REPORTS_HOOK, [streaming, router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for expected in (
            f"{streaming}:1: import of WorkerCleanupStreamingResponse "
            "renamed to CleanupStream",
            f"{streaming}:4: import of static_file_response renamed to serve",
            f"{streaming}:10: non-call reference to static_file_response",
            f"{router}:12: CleanupStreamingResponse(...) content is not",
        ):
            assert expected in result.stdout, f"{expected!r} not flagged"
        assert (
            f"{router}:14: _static_file_response(...) serves from the "
            "shared research outputs directory"
        ) in result.stdout, (
            "an underscore-prefixed helper alias must stay a helper"
        )
        for lineno in (5, 8, 9):
            assert f"{streaming}:{lineno}:" not in result.stdout, (
                f"line {lineno}: a role-keeping alias must be accepted"
            )

    def test_attribute_reads_off_a_serving_callable_are_references(
        self, tmp_path
    ):
        """Same shapes as the isolation fence's dunder test:
        ``W.__call__`` / ``helper.__wrapped__`` is the callable under
        another name, so it is flagged as a non-call reference, both
        outside the allowlist and inside an allowlisted file."""
        hooks = _mirror_hooks(tmp_path)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/dunder.py",
            "from ..dependencies.threadpool import "
            "WorkerCleanupStreamingResponse\n"
            "from ..static_files import static_file_response\n"
            "make = WorkerCleanupStreamingResponse.__call__\n"
            "serve = static_file_response.__wrapped__\n"
            "def a(p):\n"
            "    return WorkerCleanupStreamingResponse.__call__(open(p))\n"
            "def b(p):\n"
            "    return static_file_response.__call__(p)\n",
        )
        threadpool = _write(
            tmp_path,
            "src/local_deep_research/web/dependencies/threadpool.py",
            "from starlette.responses import StreamingResponse\n"
            "class WorkerCleanupStreamingResponse(StreamingResponse):\n"
            "    pass\n"
            "D = WorkerCleanupStreamingResponse.__call__\n"
            "F = StreamingResponse.__wrapped__\n",
        )
        result = _run_hook(
            REPORTS_HOOK, [router, threadpool], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for expected in (
            f"{router}:3: non-call reference to WorkerCleanupStreamingResponse",
            f"{router}:4: non-call reference to static_file_response",
            f"{router}:6: non-call reference to WorkerCleanupStreamingResponse",
            f"{router}:8: non-call reference to static_file_response",
            f"{threadpool}:4: non-call reference to "
            "WorkerCleanupStreamingResponse in an allowlisted file",
            f"{threadpool}:5: non-call reference to StreamingResponse in an "
            "allowlisted file",
        ):
            assert expected in result.stdout, f"{expected!r} not flagged"

    def test_allowlisted_files_cannot_hand_on_a_serving_callable(
        self, tmp_path
    ):
        """An allowlisted file may use primitives, but not re-bind or
        hand one on under a name the fence does not recognise: a plain
        assignment, a return of the class, a non-wrapper-named subclass
        and a role-dropping import alias are flagged. A wrapper-named
        subclass and type-only annotations are accepted."""
        hooks = _mirror_hooks(tmp_path)
        threadpool = _write(
            tmp_path,
            "src/local_deep_research/web/dependencies/threadpool.py",
            "from starlette.responses import StreamingResponse\n"
            "class WorkerCleanupStreamingResponse(StreamingResponse):\n"
            "    pass\n"
            "Download = WorkerCleanupStreamingResponse\n"
            "class Exporter(StreamingResponse):\n"
            "    pass\n"
            "def factory():\n"
            "    return StreamingResponse\n"
            "def typed(x: StreamingResponse) -> StreamingResponse | None:\n"
            "    return x\n"
            "from fastapi.responses import FileResponse as Download2\n",
        )
        result = _run_hook(
            REPORTS_HOOK, [threadpool], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for expected in (
            f"{threadpool}:4: non-call reference to "
            "WorkerCleanupStreamingResponse in an allowlisted file",
            f"{threadpool}:5: class Exporter subclasses StreamingResponse",
            f"{threadpool}:8: non-call reference to StreamingResponse",
            f"{threadpool}:11: import of FileResponse renamed to Download2",
        ):
            assert expected in result.stdout, f"{expected!r} not flagged"
        for lineno in (1, 2, 9):
            assert f"{threadpool}:{lineno}:" not in result.stdout, (
                f"line {lineno}: an import, a wrapper-named subclass or an "
                "annotation must be accepted"
            )

    def test_evaluated_annotations_cannot_inject_a_serving_callable(
        self, tmp_path
    ):
        """``= Depends()`` makes FastAPI call the annotated class with
        request-filled arguments, and ``Annotated[T,
        Depends(static_file_response)]`` calls the helper with a
        request-supplied ``path`` (FastAPI refuses ``FileResponse``
        itself at route registration; the hook fails closed regardless),
        so even an allowlisted file may not name a serving callable in
        an annotation that is evaluated: one with a non-constant default,
        a call, walrus or lambda inside, or (in any scanned file) a
        quoted forward reference there."""
        hooks = _mirror_hooks(tmp_path)
        app = _write(
            tmp_path,
            "src/local_deep_research/web/fastapi_app.py",
            "from typing import Annotated\n"
            "from fastapi import Depends\n"
            "from starlette.responses import FileResponse\n"
            "from .static_files import static_file_response\n"
            "def a(f: FileResponse = Depends()):\n"
            "    return f\n"
            "def b(f: Annotated[FileResponse, Depends()]):\n"
            "    return f\n"
            "def c(f: Annotated[object, Depends(static_file_response)]):\n"
            "    return f\n"
            "def d(f: 'FileResponse' = Depends()):\n"
            "    return f\n"
            "x: (served := FileResponse) = 1\n"
            "def ok(f: FileResponse, c: CsrfProtect = Depends()) -> FileResponse:\n"
            "    return f\n"
            "dep = Depends()\n"
            "def e(f: Annotated[FileResponse, dep]):\n"
            "    return f\n",
        )
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/quoted.py",
            "from fastapi import Depends\n"
            "from ..dependencies.threadpool import WorkerCleanupStreamingResponse\n"
            "def r(f: 'WorkerCleanupStreamingResponse' = Depends()):\n"
            "    return f\n",
        )
        result = _run_hook(
            REPORTS_HOOK, [app, router], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for expected, why in (
            (f"{app}:5: non-call reference to FileResponse", "Depends()"),
            (f"{app}:7: non-call reference to FileResponse", "Annotated"),
            (
                f"{app}:9: non-call reference to static_file_response",
                "Depends(helper) inside Annotated",
            ),
            (f"{app}:11: reference to FileResponse quoted", "a quoted name"),
            (f"{app}:13: non-call reference to FileResponse", "a walrus"),
            (
                f"{app}:17: non-call reference to FileResponse",
                "Annotated metadata bound to a name",
            ),
            (
                f"{router}:3: reference to WorkerCleanupStreamingResponse "
                "quoted",
                "a quoted wrapper outside the allowlist",
            ),
        ):
            assert expected in result.stdout, f"{why} not flagged"
        assert f"{app}:14:" not in result.stdout, (
            "type-only annotations and a non-serving Depends() must be accepted"
        )

    def test_quoted_starred_and_nested_annotations_cannot_inject(
        self, tmp_path
    ):
        """The same evaluated shapes in an allowlisted file: a wholly
        quoted ``Annotated``, a starred ``Annotated`` element, a class
        field under ``if`` / ``try`` or defaulted by a later assignment,
        and an unparsable string in a type position each make the
        serving name a reference."""
        hooks = _mirror_hooks(tmp_path)
        app = _write(
            tmp_path,
            "src/local_deep_research/web/fastapi_app.py",
            "from dataclasses import dataclass\n"
            "from typing import Annotated\n"
            "from fastapi import Depends\n"
            "from starlette.responses import FileResponse\n"
            "from .static_files import static_file_response\n"
            "dep = Depends()\n"
            'def a(f: "Annotated[object, Depends(static_file_response)]"):\n'
            "    return f\n"
            "def b(f: Annotated[*(FileResponse, dep)]):\n"
            "    return f\n"
            "@dataclass\n"
            "class C:\n"
            "    if True:\n"
            "        f: FileResponse = Depends()\n"
            "    try:\n"
            "        g: static_file_response = dep\n"
            "    except ImportError:\n"
            "        pass\n"
            'def d(f: tuple[FileResponse, "1 +"]):\n'
            "    return f\n"
            "def ok(\n"
            '    f: "FileResponse",\n'
            '    g: Annotated["FileResponse", "a doc string"] = None,\n'
            ') -> "FileResponse":\n'
            "    return f\n"
            "@dataclass\n"
            "class E:\n"
            "    f: FileResponse\n"
            "    f = Depends()\n",
        )
        result = _run_hook(REPORTS_HOOK, [app], cwd=tmp_path, hooks_dir=hooks)
        assert result.returncode == 1, result.stdout
        for expected, why in (
            (
                f"{app}:7: reference to static_file_response quoted",
                "a wholly quoted Annotated",
            ),
            (f"{app}:9: non-call reference to FileResponse", "a starred one"),
            (
                f"{app}:14: non-call reference to FileResponse",
                "a Depends() field under if",
            ),
            (
                f"{app}:16: non-call reference to static_file_response",
                "a field under try",
            ),
            (
                f"{app}:19: non-call reference to FileResponse",
                "an unparsable string in a type position",
            ),
            (
                f"{app}:28: non-call reference to FileResponse",
                "a field defaulted by a later assignment",
            ),
        ):
            assert expected in result.stdout, f"{why} not flagged"
        for lineno in range(21, 26):
            assert f"{app}:{lineno}:" not in result.stdout, (
                f"line {lineno}: a quoted type or an Annotated doc string "
                "must be accepted"
            )

    def test_unchecked_annotation_strings_and_inherited_defaults(
        self, tmp_path
    ):
        """In every scanned file a string in a type position that does
        not parse is an offender in itself; in an allowlisted file a
        class field with no binding in its own body, on a class with a
        real base, may inherit a ``Depends()`` default, so a serving
        name in its annotation is a reference."""
        hooks = _mirror_hooks(tmp_path)
        app = _write(
            tmp_path,
            "src/local_deep_research/web/fastapi_app.py",
            "from typing import Literal\n"
            "from starlette.responses import FileResponse\n"
            "class Base:\n"
            "    pass\n"
            'def a(f: "1 +"):\n'
            "    return f\n"
            "class Sub(Base):\n"
            "    f: FileResponse\n"
            'def ok(f: Literal["a ) b"] = "a ) b") -> "FileResponse":\n'
            "    return f\n"
            "class Plain:\n"
            "    f: FileResponse\n",
        )
        other = _write(
            tmp_path,
            "src/local_deep_research/web/routers/other.py",
            'def a(x: "*[int]"):\n    return x\n',
        )
        result = _run_hook(
            REPORTS_HOOK, [app, other], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 1, result.stdout
        for expected, why in (
            (
                f"{app}:5: annotation string that cannot be checked",
                "unparsable",
            ),
            (f"{app}:8: non-call reference to FileResponse", "inherited"),
            (
                f"{other}:1: annotation string that cannot be checked",
                "unparsable outside the allowlist",
            ),
        ):
            assert expected in result.stdout, f"{why} not flagged"
        for lineno in range(9, 13):
            assert f"{app}:{lineno}:" not in result.stdout, (
                f"line {lineno}: a Literal string, a quoted type or a field "
                "of a base-less class must be accepted"
            )

    def test_a_symlink_into_the_web_scope_is_scanned(self, tmp_path):
        """A symlink inside web/ whose target lies outside it is still
        scanned (lexical OR resolved path in scope), and gets no
        allowlist exemption from its name."""
        hooks = _mirror_hooks(tmp_path)
        serving = "from fastapi.responses import FileResponse\n"
        target = _write(
            tmp_path, "src/local_deep_research/other/real.py", serving
        )
        link = WEB_DIR + "routers/linked.py"
        allowed_link = next(iter(_reports_hook.ALLOWED_FILES))
        for rel in (link, allowed_link):
            (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
            try:
                (tmp_path / rel).symlink_to(tmp_path / target)
            except (OSError, NotImplementedError):
                pytest.skip("symlinks unsupported here")
        for rel in (link, allowed_link):
            result = _run_hook(
                REPORTS_HOOK, [rel], cwd=tmp_path, hooks_dir=hooks
            )
            assert result.returncode == 1, f"symlink {rel} escaped the fence"
        result = _run_hook(
            REPORTS_HOOK, [target], cwd=tmp_path, hooks_dir=hooks
        )
        assert result.returncode == 0, "the out-of-scope target is skipped"


@pytest.mark.parametrize(
    "script,name",
    [(ISOLATION_HOOK, "NoteService"), (REPORTS_HOOK, "FileResponse")],
    ids=["isolation", "reports"],
)
@pytest.mark.parametrize("quoted", [False, True], ids=["unquoted", "quoted"])
class TestAnnotationPlainValues:
    @pytest.mark.parametrize(
        "annotation",
        [
            'Annotated[Literal["{name}"], Query()]',
            'Annotated[str, Query(description="{name}")]',
            'Annotated[Literal["{name}()"], Query()]',
            'Annotated[str, {"description": "{name}"}, Query()]',
            'Annotated[NewType("{name}", str), Query()]',
            'Annotated[constr(pattern=r"^[A-Z]+$"), Query()]',
            'Annotated[ForwardRef("str", module="{name}"), Query()]',
            'Annotated[Optional[Literal["{name}"]], Query()]',
            'Annotated[list[Literal["{name}"]], Query()]',
            'Annotated[dict[str, Optional[Literal["{name}"]]], Query()]',
            'Annotated[str, "{name}", Query()]',
            'Annotated[str, {"{name}": "a key"}, Query()]',
            'Annotated[str, Query(None, description="{name}"), "{name}"]',
            "Annotated[Optional[\"Literal['{name}']\"], Query()]",
        ],
        ids=[
            "literal",
            "description",
            "call-text",
            "metadata",
            "newtype-name",
            "constraint-pattern",
            "forward-ref-module",
            "literal-in-a-subscript",
            "literal-in-a-builtin-generic",
            "literal-in-nested-generics",
            "metadata-string",
            "metadata-key",
            "listed-argument-after-a-positional",
            "literal-quoted-in-a-type-slot",
        ],
    )
    def test_plain_strings_do_not_become_references(
        self, tmp_path, script, name, quoted, annotation
    ):
        """Parseable value strings stay data, even in quoted annotations:
        each shape is a path ``_approved_children`` approves, step by
        step, from the annotation's root to the string."""
        hooks = _mirror_hooks(tmp_path)
        annotation = annotation.replace("{name}", name)
        if quoted:
            annotation = repr(annotation)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/annotation_values.py",
            "from typing import Annotated, ForwardRef, Literal, NewType\n"
            "from typing import Optional\n"
            "from fastapi import Query\n"
            "from pydantic import constr\n"
            f"def route(value: {annotation}):\n"
            "    return value\n",
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        assert result.returncode == 0, result.stdout + result.stderr

    def test_quoted_type_references_remain_fenced(
        self, tmp_path, script, name, quoted
    ):
        """A quoted dependency type is still a reference, not a value."""
        hooks = _mirror_hooks(tmp_path)
        annotation = f'Annotated["{name}", Depends()]'
        if quoted:
            annotation = repr(annotation)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/annotation_dependency.py",
            "from typing import Annotated\n"
            "from fastapi import Depends\n"
            f"def route(value: {annotation}):\n"
            "    return value\n",
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        assert result.returncode == 1, result.stdout + result.stderr
        assert f"{router}:3:" in result.stdout
        assert name in result.stdout


@pytest.mark.parametrize(
    "script,name",
    [
        (ISOLATION_HOOK, "NoteService"),
        (REPORTS_HOOK, "FileResponse"),
        (REPORTS_HOOK, "static_file_response"),
    ],
    ids=["isolation", "reports-primitive", "reports-helper"],
)
@pytest.mark.parametrize("quoted", [False, True], ids=["unquoted", "quoted"])
class TestAnnotationForwardReferences:
    @pytest.mark.parametrize(
        "call",
        [
            "ForwardRef({reference})",
            "typing.ForwardRef({reference})",
            "FR({reference})",
            "ForwardRef(arg={reference})",
            "typing.cast(object, ForwardRef({reference}))",
            "ForwardRef(*({reference},))",
            "ForwardRef(**{{'arg': {reference}}})",
            "ForwardRef(*(*({reference},),))",
            "ForwardRef(**{{**{{'arg': {reference}}}}})",
        ],
        ids=[
            "bare",
            "qualified",
            "alias",
            "keyword",
            "nested-call",
            "unpacked-positional",
            "unpacked-keyword",
            "nested-unpacked-positional",
            "nested-unpacked-keyword",
        ],
    )
    def test_forward_reference_type_arguments_remain_fenced(
        self, tmp_path, script, name, quoted, call
    ):
        """ForwardRef arguments are types, including through import aliases."""
        hooks = _mirror_hooks(tmp_path)
        reference = call.format(reference=repr(name))
        annotation = f"Annotated[{reference}, Depends()]"
        if quoted:
            annotation = repr(annotation)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/forward_reference.py",
            "from __future__ import annotations\n"
            "import typing\n"
            "from typing import Annotated, ForwardRef\n"
            "from typing import ForwardRef as FR\n"
            "from fastapi import Depends\n"
            f"def route(value: {annotation}):\n"
            "    return value\n",
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        assert result.returncode == 1, result.stdout + result.stderr
        assert f"{router}:6:" in result.stdout
        assert name in result.stdout

    @pytest.mark.parametrize("invalid", ["syntax", "depth"])
    def test_unchecked_forward_reference_strings_are_rejected(
        self, tmp_path, script, name, quoted, invalid
    ):
        """ForwardRef strings retain the parser's fail-closed checks."""
        hooks = _mirror_hooks(tmp_path)
        reference = "not a ) type" if invalid == "syntax" else name
        if invalid == "depth":
            for _ in range(_isolation_hook._MAX_QUOTE_DEPTH + 1):
                reference = repr(reference)
        annotation = f"Annotated[ForwardRef({reference!r}), Depends()]"
        if quoted:
            annotation = repr(annotation)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/unchecked_forward_ref.py",
            "from __future__ import annotations\n"
            "from typing import Annotated, ForwardRef\n"
            "from fastapi import Depends\n"
            f"def route(value: {annotation}):\n"
            "    return value\n",
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        assert result.returncode == 1, result.stdout + result.stderr
        assert f"{router}:4: annotation string that cannot be checked" in (
            result.stdout
        )


def _reported(
    result: subprocess.CompletedProcess, router: str, line: int, name: str
) -> bool:
    """True if the hook reported ``name`` on line ``line`` of ``router``."""
    prefix = f"{router}:{line}:"
    return any(
        out.lstrip().startswith(prefix) and name in out
        for out in result.stdout.splitlines()
    )


#: Fenced names quoted where ``typing`` can resolve them although no rule
#: knows the call: an argument a call may hand on to a type position, a
#: ``Literal`` member other than a plain string, or a ``ForwardRef`` that
#: is evaluated by calling it (even in metadata, where FastAPI then gets
#: the ``Depends``). ``{ref}`` is the quoted name, ``{name}`` the bare one.
_TYPE_STRING_CALLS = {
    "cast": "Annotated[typing.cast(object, {ref}), Depends()]",
    "cast-union": (
        "Annotated[typing.cast(type, typing.Union[{ref}]), Depends()]"
    ),
    "str": "Annotated[str({ref}), Depends()]",
    "unknown-callee": "Annotated[convert({ref}), Depends()]",
    "unknown-callee-in-metadata": "Annotated[str, Depends(convert({ref}))]",
    "non-literal-mapping": (
        "Annotated[ForwardRef(**dict(arg={ref})), Depends()]"
    ),
    "type-check": 'Annotated[typing._type_check({ref}, ""), Depends()]',
    "dunder-call": "Annotated[ForwardRef.__call__({ref}), Depends()]",
    "literal-forward-ref": "Annotated[Literal[ForwardRef({ref})], Depends()]",
    "literal-generic": "Annotated[Literal[Optional[{ref}]], Depends()]",
    "star-form": 'Annotated[typing.cast(object, "*[{name}]"), Depends()]',
    "evaluated-forward-ref": (
        'Annotated[str, ForwardRef("Depends({name})", module=__name__)'
        ".evaluate()]"
    ),
}

#: VALUE_ARGUMENTS callees that build a type: fixtures call them in the
#: annotation's type position, the others in its metadata.
_TYPE_CONSTRUCTORS = frozenset(
    {"typing.NewType", "typing.ForwardRef", "pydantic.constr"}
)


def _value_argument_calls(
    callee: str, position: int | str, probe: str
) -> tuple[str, str]:
    """``(listed, neighbour)`` calls of ``callee``: ``probe`` in the
    listed argument ``position``, then in a neighbouring argument that
    VALUE_ARGUMENTS does not list."""
    if callee == "typing.NewType" and position == 0:
        return f"NewType({probe}, str)", f"NewType('Label', {probe})"
    if callee == "typing.NewType" and position == "name":
        return (
            f"NewType(name={probe}, tp=str)",
            f"NewType(name='Label', tp={probe})",
        )
    if callee == "typing.ForwardRef" and position == 2:
        return (
            f"ForwardRef('str', True, {probe})",
            f"ForwardRef('str', {probe}, 'builtins')",
        )
    if callee == "typing.ForwardRef" and position == "module":
        return (
            f"ForwardRef('str', module={probe})",
            f"ForwardRef({probe}, module='builtins')",
        )
    if callee == "pydantic.constr" and isinstance(position, str):
        return f"constr({position}={probe})", f"constr(max_length={probe})"
    if callee.startswith(("fastapi.", "pydantic.")) and isinstance(
        position, str
    ):
        # A keyword after the positional default (or dependency).
        local = callee.rpartition(".")[2]
        return (
            f"{local}(None, {position}={probe})",
            f"{local}({probe}, {position}=None)",
        )
    raise AssertionError(f"no fixture for {callee} {position!r}")


#: ``(lines before the route, annotation, accepted)``: a VALUE_ARGUMENTS
#: exemption needs the callee imported from its own module under a name
#: nothing else in the file binds, in a file that cannot change it (see
#: ``_proven_names``); any other callee's arguments are parsed.
_VALUE_CALLEE_BINDINGS = {
    "import-alias": (
        "from fastapi import Query as Q\n",
        "Annotated[str, Q(description={ref})]",
        True,
    ),
    "module-attribute": (
        "import fastapi\n",
        "Annotated[str, fastapi.Query(description={ref})]",
        True,
    ),
    "module-alias": (
        "import typing as t\n",
        "Annotated[t.NewType({ref}, str), Depends()]",
        True,
    ),
    "local-def": (
        "def Query(**kw):\n    return kw['description']\n",
        "Annotated[Query(description={ref}), Depends()]",
        False,
    ),
    "rebound": (
        "from fastapi import Query\nQuery = lambda **kw: kw['description']\n",
        "Annotated[Query(description={ref}), Depends()]",
        False,
    ),
    "relative-import": (
        "from .compat import Query\n",
        "Annotated[Query(description={ref}), Depends()]",
        False,
    ),
    "two-imports": (
        "from fastapi import Query\nfrom .compat import Query\n",
        "Annotated[Query(description={ref}), Depends()]",
        False,
    ),
    "star-import": (
        "from fastapi import Query\nfrom .compat import *\n",
        "Annotated[Query(description={ref}), Depends()]",
        False,
    ),
    "unlisted-module": (
        "from fastapi import params\n",
        "Annotated[str, params.Query(description={ref})]",
        False,
    ),
    "forward-ref-elsewhere": (
        "from compat import ForwardRef\n",
        "Annotated[str, {{'r': ForwardRef({ref})}}]",
        False,
    ),
    "module-replaced": (
        "import fastapi\n"
        "fastapi.Query = lambda **kw: kw['description']\n"
        "from fastapi import Query\n",
        "Annotated[Query(description={ref}), Depends()]",
        False,
    ),
    "callee-mutated": (
        "from fastapi import Query\n"
        "Query.__code__ = (lambda **kw: kw['description']).__code__\n",
        "Annotated[Query(description={ref}), Depends()]",
        False,
    ),
}


@pytest.mark.parametrize(
    "script,name",
    [(ISOLATION_HOOK, "NoteService"), (REPORTS_HOOK, "FileResponse")],
    ids=["isolation", "reports"],
)
@pytest.mark.parametrize("quoted", [False, True], ids=["unquoted", "quoted"])
class TestAnnotationCallArguments:
    @pytest.mark.parametrize(
        "shape", list(_TYPE_STRING_CALLS), ids=list(_TYPE_STRING_CALLS)
    )
    def test_strings_a_call_may_hand_to_a_type_are_rejected(
        self, tmp_path, script, name, quoted, shape
    ):
        """An argument of a call no rule knows is parsed and checked (fail
        closed): the callee may return it into a type position, which
        FastAPI resolves (``typing.cast(object, "NoteService")`` builds
        NoteService with ``username`` from the request). A ``Literal``
        member other than a plain string is resolved by ``typing`` too,
        and a call no rule lists ends the approved path, so a
        ``ForwardRef`` evaluated in metadata is checked."""
        hooks = _mirror_hooks(tmp_path)
        annotation = _TYPE_STRING_CALLS[shape].format(ref=repr(name), name=name)
        if quoted:
            annotation = repr(annotation)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/call_arguments.py",
            "import typing\n"
            "from typing import Annotated, ForwardRef, Literal, Optional\n"
            "from fastapi import Depends\n"
            f"def route(value: {annotation}):\n"
            "    return value\n",
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        assert result.returncode == 1, result.stdout + result.stderr
        assert _reported(result, router, 4, name), result.stdout

    def test_value_arguments_are_exempt_only_where_listed(
        self, tmp_path, script, name, quoted
    ):
        """For every VALUE_ARGUMENTS entry, the fenced name quoted in the
        listed argument is exempt, and the same string in a neighbouring
        argument that is not listed is parsed and reported."""
        hooks = _mirror_hooks(tmp_path)
        lines = [
            "from typing import Annotated, ForwardRef, NewType",
            "from fastapi import Body, Cookie, Depends, File, Form, Header",
            "from fastapi import Path, Query",
            "from pydantic import Field, constr",
        ]
        listed: list[tuple[int, str, int | str]] = []
        neighbours: list[tuple[int, str, int | str]] = []
        for callee, positions in sorted(
            _isolation_hook.VALUE_ARGUMENTS.items()
        ):
            for position in sorted(positions, key=str):
                calls = _value_argument_calls(callee, position, repr(name))
                for call, found in zip(calls, (listed, neighbours)):
                    if callee in _TYPE_CONSTRUCTORS:
                        annotation = f"Annotated[{call}, Query()]"
                    else:
                        annotation = f"Annotated[str, {call}]"
                    if quoted:
                        annotation = repr(annotation)
                    lineno = len(lines) + 1
                    lines.append(
                        f"def route_{lineno}(value: {annotation}): return value"
                    )
                    found.append((lineno, callee, position))
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/value_arguments.py",
            "\n".join(lines) + "\n",
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        assert result.returncode == 1, result.stdout + result.stderr
        for lineno, callee, position in listed:
            assert f"{router}:{lineno}:" not in result.stdout, (
                f"{callee} {position!r} is listed, so its string is a value"
            )
        for lineno, callee, position in neighbours:
            assert _reported(result, router, lineno, name), (
                f"{callee}: the argument next to {position!r} was not parsed"
            )

    @pytest.mark.parametrize(
        "binding",
        list(_VALUE_CALLEE_BINDINGS),
        ids=list(_VALUE_CALLEE_BINDINGS),
    )
    def test_value_arguments_need_the_callee_imported_from_its_module(
        self, tmp_path, script, name, quoted, binding
    ):
        """A listed argument is exempt only for a callee provably the
        listed one: imported from its module (or read off the imported
        module) under a name nothing else binds, in a file that cannot
        change it. A local pass-through named ``Query``, a rebinding, a
        relative or star import, another module's ``Query``, another
        ``ForwardRef``, a ``Query`` replaced on its module or with an
        attribute assigned is an unknown callee, whose arguments are
        parsed."""
        hooks = _mirror_hooks(tmp_path)
        prelude, template, accepted = _VALUE_CALLEE_BINDINGS[binding]
        annotation = template.format(ref=repr(name))
        if quoted:
            annotation = repr(annotation)
        source = (
            "import typing\n"
            "from typing import Annotated\n"
            "from fastapi import Depends\n"
            f"{prelude}"
            f"def route(value: {annotation}):\n"
            "    return value\n"
        )
        lineno = source.count("\n", 0, source.index("def route(")) + 1
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/value_callees.py",
            source,
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        if accepted:
            assert result.returncode == 0, result.stdout + result.stderr
        else:
            assert result.returncode == 1, result.stdout + result.stderr
            assert _reported(result, router, lineno, name), result.stdout

    def test_call_arguments_nested_too_deep_are_rejected(
        self, tmp_path, script, name, quoted
    ):
        """``typing`` resolves nested quotes one level at a time, so a call
        argument quoted deeper than ``_MAX_QUOTE_DEPTH`` cannot be checked
        and is reported, as in a type position."""
        hooks = _mirror_hooks(tmp_path)
        reference = name
        for _ in range(_isolation_hook._MAX_QUOTE_DEPTH + 1):
            reference = repr(reference)
        annotation = f"Annotated[typing.cast(object, {reference}), Depends()]"
        if quoted:
            annotation = repr(annotation)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/deep_argument.py",
            "import typing\n"
            "from typing import Annotated\n"
            "from fastapi import Depends\n"
            f"def route(value: {annotation}):\n"
            "    return value\n",
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        assert result.returncode == 1, result.stdout + result.stderr
        assert f"{router}:4: annotation string that cannot be checked" in (
            result.stdout
        )


#: Strings read back out of their ``Literal``, ``Annotated`` or listed
#: call -- through an attribute read, a subscript, a call, or a subscript
#: of a head that is not a proven generic, whose ``__class_getitem__``
#: gets the key -- into a type position, and ``Annotated`` metadata after
#: a starred first element, which may be the type. ``_approved_children``
#: approves none of these paths, so each string is checked.
#: ``typing.get_type_hints`` resolves each to the class or to a type
#: holding it, a type position the hooks check as they check
#: ``Optional["NoteService"]``; the fixtures default the parameter to
#: ``Depends()``, and most of these then make FastAPI build the class
#: with ``username`` taken from the request. ``{ref}`` is the quoted
#: name, ``{name}`` the bare one, ``{literal}`` the quoted
#: ``Literal[...]`` of it; ``G`` reads the string out of its key or an
#: operand.
_READ_OUT_VALUES = {
    "literal-args": "Literal[{ref}].__args__[0]",
    "get-args": "typing.get_args(Literal[{ref}])[0]",
    "metadata-list": "Annotated[str, [{ref}]].__metadata__[0][0]",
    "metadata-string": "Annotated[int, {ref}].__metadata__[0]",
    "metadata-forward-ref": (
        "Annotated[str, ForwardRef({ref})].__metadata__[0]"
    ),
    "description": "Query(description={ref}).description",
    "getattr": "getattr(Query(description={ref}), 'description')",
    "newtype-name": "NewType({ref}, str).__name__",
    "forward-ref-module": (
        "ForwardRef('str', module={ref}).__forward_module__"
    ),
    "through-a-tuple": "(Literal[{ref}],)[0].__args__[0]",
    "in-a-type": "Optional[Literal[{ref}].__args__[0]]",
    "as-annotated-type": "Annotated[Literal[{ref}].__args__[0], Depends()]",
    "parsed-string": "eval({literal}).__args__[0]",
    "class-getitem-literal": "G[Literal[{ref}]]",
    "class-getitem-description": "G[Query(description={ref})]",
    "starred-first-element": "Annotated[*(), {ref}, Depends()]",
}

#: Off-path shapes whose string stays a value or never reaches a type
#: position, checked all the same (fail closed): the allowlist approves
#: paths, not outcomes, so a form read out inside metadata or a listed
#: argument, and the object of a subscript whose head is not a proven
#: generic, are checked whatever the expression does with them.
_READ_OUT_FAIL_CLOSED = {
    "in-metadata": "Annotated[str, Literal[{ref}].__args__[0]]",
    "in-a-listed-argument": (
        "Annotated[str, Query(description=Literal[{ref}].__args__[0])]"
    ),
    "forward-ref-in-metadata": (
        "Annotated[str, ForwardRef({ref}).__forward_arg__]"
    ),
    "subscript-object": "Annotated[List[T], {ref}][int]",
}

#: Strings on a path ``_approved_children`` does not approve, whatever
#: the node that ends it: an operator, comparison, boolean or unary
#: operator, conditional, walrus, lambda, f-string, a subscript of a head
#: that is not a proven generic, a list, a ``Literal`` in metadata, an
#: ``Annotated`` whose metadata holds an object pydantic hands the type
#: to, a dict outside metadata or with ``**``, literal unpacking into a
#: listed callee, a ``ForwardRef`` held in metadata, a starred
#: ``Literal`` member, or a string parsed out of a call argument. Several
#: read the string back out into a type position (``G |
#: Literal["NoteService"]`` runs ``G``'s ``__or__``, and
#: ``Annotated[Literal["NoteService"], G]`` its
#: ``__get_pydantic_core_schema__``), and each is checked.
_UNAPPROVED_PATHS = {
    "or": "G | Literal[{ref}]",
    "add": "Literal[{ref}] + G",
    "add-description": "Query(description={ref}) + G",
    "compare": "G < Literal[{ref}]",
    "matmul": "G @ Annotated[int, {ref}]",
    "boolean": "G or Literal[{ref}]",
    "unary": "~Literal[{ref}]",
    "conditional": "Literal[{ref}] if G else G",
    "walrus": "(alias := Literal[{ref}])",
    "lambda": "(lambda: Literal[{ref}])()",
    "f-string": "f\"{{Literal[{ref}]}}{{str('.__args__[0]')}}\"",
    "f-string-description": 'f"{{Query(description={ref}).description}}"',
    "metadata-subscript": "Annotated[str, G[{ref}]]",
    "metadata-object": "Annotated[Literal[{ref}], G]",
    "metadata-unlisted-call": "Annotated[Literal[{ref}], G()]",
    "metadata-list": "Annotated[str, [{ref}]]",
    "metadata-literal": "Annotated[str, Literal[{ref}]]",
    "metadata-forward-ref": "Annotated[str, {{'r': ForwardRef({ref})}}]",
    "dict-unpacking": "Annotated[str, {{**{{}}, 'd': {ref}}}]",
    "dict-in-a-type-slot": "Annotated[{{'d': {ref}}}, Query()]",
    "unpacked-positional": (
        "Annotated[ForwardRef(*('str', True, {ref})), Query()]"
    ),
    "unpacked-keyword": (
        "Annotated[ForwardRef(**{{'arg': 'str', 'module': {ref}}}), Query()]"
    ),
    "unpacked-description": "Annotated[str, Query(**{{'description': {ref}}})]",
    "starred-literal-member": "Literal[*({ref},)]",
    "parsed-out-of-an-argument": "typing.cast(object, {literal}).__args__[0]",
}

#: ``{change: (lines before the route, annotation)}``: in-file code
#: through which a file could change what a proven name denotes, each
#: caught by a different rule of ``_proven_names``. The annotation alone
#: holds an exempt string; after the change nothing in the file is
#: proven, so the string is checked. ``G`` stands for any replacement.
_PROOF_CHANGES = {
    "star-import": ("from compat import *\n", "Literal[{ref}]"),
    "setattr": (
        "setattr(typing, 'Literal', typing.Annotated)\n",
        "Literal[{ref}]",
    ),
    "vars": ("vars(typing)['Literal'] = typing.Annotated\n", "Literal[{ref}]"),
    "globals": ("globals()['Literal'] = typing.Annotated\n", "Literal[{ref}]"),
    "locals": ("locals()['Literal'] = typing.Annotated\n", "Literal[{ref}]"),
    "sys-modules": (
        "import sys\nalias = sys.modules['typing']\nalias.Union = G\n",
        "Optional[Literal[{ref}]]",
    ),
    "exec": (
        "exec('import typing; typing.Literal = typing.Annotated')\n",
        "Literal[{ref}]",
    ),
    "import-module": (
        "from importlib import import_module as load\n"
        "alias = load('typing')\nalias.Union = G\n",
        "Optional[Literal[{ref}]]",
    ),
    "imported-root": (
        "try:\n"
        "    import fastapi.params as params\n"
        "except ImportError:\n"
        "    params = None\n"
        "params.Query.default = G\n",
        "Annotated[str, Query(description={ref})]",
    ),
    "unbound-root": (
        "bound_elsewhere.copy_with = G\n",
        "List[Literal[{ref}]]",
    ),
    "expression-root": ("get_alias().copy_with = G\n", "List[Literal[{ref}]]"),
    "attribute-named-like-a-form": (
        "def rebind(module):\n    module.Literal = G\n",
        "Literal[{ref}]",
    ),
    "dunder-in-a-target": (
        "class Patch:\n"
        "    def apply(self):\n"
        "        self.__class__.copy_with = G\n",
        "List[Literal[{ref}]]",
    ),
    "private-attribute": (
        "def patch(form):\n    form._getitem = G\n",
        "Literal[{ref}]",
    ),
    "module-alias": ("alias = typing\n", "Literal[{ref}]"),
    "module-through-a-module": (
        "import typing_extensions\nalias = typing_extensions.typing\n",
        "Literal[{ref}]",
    ),
    "private-module-attribute": (
        "alias = typing._SpecialGenericAlias\n",
        "List[Literal[{ref}]]",
    ),
    "private-import": (
        "from typing import _GenericAlias\n",
        "List[Literal[{ref}]]",
    ),
    "form-alias": ("alias = Literal\n", "Literal[{ref}]"),
    "callee-alias": (
        "alias = ForwardRef\n",
        "Annotated[ForwardRef('str', module={ref}), Query()]",
    ),
    "head-class": (
        "alias = type(List)\nRows = List[int]\n",
        "List[Literal[{ref}]]",
    ),
}

#: Ordinary code that leaves every proof standing: a subscripted generic
#: head used as a whole annotation or in the key of a proven head,
#: ``typing.TYPE_CHECKING``, a builtin passed to ``isinstance``, ``from
#: importlib import resources``, and stores on objects the file binds
#: (attributes of ``self``, private ones included, and of a local).
_PROOF_KEEPING = (
    "from typing import Dict\n"
    "from importlib import resources\n"
    "Rows = List[Dict]\n"
    "Table = dict[str, Dict]\n"
    "Cells = Dict[str, int]\n"
    "def helper(value: Dict) -> Dict:\n"
    "    if typing.TYPE_CHECKING or isinstance(value, dict):\n"
    "        return value\n"
    "    return resources\n"
    "class Holder:\n"
    "    def __init__(self):\n"
    "        self._cache = {}\n"
    "        self._cache['key'] = 1\n"
    "        self.items = []\n"
    "record = Holder()\n"
    "record.items = [1]\n"
)

#: The lines before the route in the read-out fixtures: ``G`` reads the
#: string back out of its key, of the other operand of an operator, and
#: of the type pydantic hands it as ``Annotated`` metadata.
_READ_OUT_PRELUDE = (
    "import typing\n"
    "from typing import Annotated, ForwardRef, List, Literal, NewType\n"
    "from typing import Optional, TypeVar\n"
    "from fastapi import Depends, Query\n"
    'T = TypeVar("T")\n'
    "def _read(value):\n"
    "    return getattr(value, 'description', None) or (\n"
    "        typing.get_args(value)[0]\n"
    "    )\n"
    "class _Reader(type):\n"
    "    def __or__(cls, other):\n"
    "        return _read(other)\n"
    "    __ror__ = __add__ = __radd__ = __lt__ = __gt__ = __or__\n"
    "    __matmul__ = __rmatmul__ = __or__\n"
    "class G(metaclass=_Reader):\n"
    "    def __class_getitem__(cls, key):\n"
    "        return _read(key)\n"
    "    @classmethod\n"
    "    def __get_pydantic_core_schema__(cls, source, handler):\n"
    "        return handler(_read(source))\n"
)

#: ``(lines before the route, annotation, accepted)``: ``Literal`` and
#: ``Annotated`` hold exempt strings only as the forms ``typing`` and
#: ``typing_extensions`` define, imported under a name nothing else in
#: the file binds, in a file that cannot change them; a head merely
#: named like one is checked.
_FORM_BINDINGS = {
    "typing": (
        "from typing import Literal\n",
        "Annotated[Literal[{ref}], Depends()]",
        True,
    ),
    "import-alias": (
        "from typing import Literal as L\n",
        "Annotated[L[{ref}], Depends()]",
        True,
    ),
    "module-attribute": (
        "import typing as t\n",
        "Annotated[t.Literal[{ref}], Depends()]",
        True,
    ),
    "typing-extensions": (
        "from typing_extensions import Literal\n",
        "Annotated[Literal[{ref}], Depends()]",
        True,
    ),
    "typing-extensions-annotated": (
        "from typing_extensions import Annotated as A\n",
        "A[str, {ref}, Depends()]",
        True,
    ),
    "annotated-as-literal": (
        "from typing import Annotated as Literal\n",
        "Literal[{ref}, Depends()]",
        False,
    ),
    "optional-as-literal": (
        "from typing import Optional as Literal\n",
        "Literal[{ref}, Depends()]",
        False,
    ),
    "assigned": (
        "Literal = typing.Annotated\n",
        "Literal[{ref}, Depends()]",
        False,
    ),
    "other-module": (
        "from compat import Literal\n",
        "Literal[{ref}, Depends()]",
        False,
    ),
    "other-module-attribute": (
        "import compat\n",
        "compat.Literal[{ref}, Depends()]",
        False,
    ),
    "two-imports": (
        "from typing import Literal\nfrom typing_extensions import Literal\n",
        "Literal[{ref}, Depends()]",
        False,
    ),
    "star-import": (
        "from typing import Literal\nfrom .compat import *\n",
        "Literal[{ref}, Depends()]",
        False,
    ),
    "rebound-annotated": (
        "Annotated = typing.Annotated\n",
        "Annotated[str, {ref}, Depends()]",
        False,
    ),
    "module-replaced": (
        "typing.Literal = typing.Annotated\nfrom typing import Literal\n",
        "Literal[{ref}, Depends()]",
        False,
    ),
    "module-item-replaced": (
        "typing.__dict__['Literal'] = typing.Annotated\n"
        "from typing import Literal\n",
        "Literal[{ref}, Depends()]",
        False,
    ),
}


#: ``(lines before the route, annotation, accepted)``: a subscript is a
#: step of an approved path only under a head provably from ``typing``,
#: ``typing_extensions`` or ``collections.abc`` or a builtin generic;
#: ``G`` reads the string out of its key, and ``typing`` resolves the
#: annotation to a type holding the class wherever ``G`` stands in.
_GENERIC_HEAD_BINDINGS = {
    "builtin": ("", "Annotated[list[Literal[{ref}]], Depends()]", True),
    "typing": ("", "Annotated[typing.List[Literal[{ref}]], Depends()]", True),
    "builtin-rebound": (
        "list = G\n",
        "Annotated[list[Literal[{ref}]], Depends()]",
        False,
    ),
    "builtins-replaced": (
        "import builtins\nbuiltins.list = G\n",
        "Annotated[list[Literal[{ref}]], Depends()]",
        False,
    ),
    "dunder-builtins-replaced": (
        "__builtins__['list'] = G\n",
        "Annotated[list[Literal[{ref}]], Depends()]",
        False,
    ),
    "typing-replaced": (
        "typing.List = G\n",
        "Annotated[typing.List[Literal[{ref}]], Depends()]",
        False,
    ),
    "user-generic": (
        "class Page(typing.Generic[T]):\n    pass\n",
        "Annotated[Page[Literal[{ref}]], Depends()]",
        False,
    ),
}


def _read_out_route(
    tmp_path: Path,
    script: str,
    template: str,
    name: str,
    quoted: bool,
    extra: str = "",
) -> tuple[subprocess.CompletedProcess, str, int]:
    """Run ``script`` on a router whose route parameter is annotated with
    ``template`` and defaults to ``Depends()``, after the read-out
    prelude and ``extra``; ``(result, router, line of the route)``."""
    hooks = _mirror_hooks(tmp_path)
    annotation = template.format(
        ref=repr(name), name=name, literal=repr(f"Literal[{name!r}]")
    )
    if quoted:
        annotation = repr(annotation)
    source = (
        f"{_READ_OUT_PRELUDE}"
        f"{extra}"
        f"def route(value: {annotation} = Depends()):\n"
        "    return value\n"
    )
    lineno = source.count("\n", 0, source.index("def route(")) + 1
    router = _write(
        tmp_path, "src/local_deep_research/web/routers/read_out.py", source
    )
    result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
    return result, router, lineno


@pytest.mark.parametrize(
    "script,name",
    [(ISOLATION_HOOK, "NoteService"), (REPORTS_HOOK, "FileResponse")],
    ids=["isolation", "reports"],
)
@pytest.mark.parametrize("quoted", [False, True], ids=["unquoted", "quoted"])
class TestAnnotationPlainValueProvenance:
    @pytest.mark.parametrize(
        "shape", list(_READ_OUT_VALUES), ids=list(_READ_OUT_VALUES)
    )
    def test_plain_values_read_out_are_rejected(
        self, tmp_path, script, name, quoted, shape
    ):
        """A ``Literal``, ``Annotated`` or listed call holds exempt strings
        only on an approved path, and none of these is one:
        ``Literal["NoteService"].__args__[0]``,
        ``typing.get_args(Literal["NoteService"])[0]``,
        ``Query(description="NoteService").description`` or a subscript
        whose ``__class_getitem__`` reads its key hands the string on to
        a type position, which FastAPI resolves (with a ``Depends()``
        default it builds NoteService, ``username`` taken from the
        request), so those strings are checked. So is ``Annotated``
        metadata after a starred first element, which may be the type."""
        result, router, lineno = _read_out_route(
            tmp_path, script, _READ_OUT_VALUES[shape], name, quoted
        )
        assert result.returncode == 1, result.stdout + result.stderr
        assert _reported(result, router, lineno, name), result.stdout

    @pytest.mark.parametrize(
        "shape", list(_READ_OUT_FAIL_CLOSED), ids=list(_READ_OUT_FAIL_CLOSED)
    )
    def test_read_out_values_are_checked_where_they_stay_plain(
        self, tmp_path, script, name, quoted, shape
    ):
        """Fail closed: the allowlist approves paths, not outcomes, so a
        form read out is checked even where what it yields stays a value
        -- inside metadata or a listed argument -- and so is the object
        of a subscript whose head is not a proven generic
        (``Annotated[List[T], "NoteService"][int]`` keeps the string as
        metadata)."""
        result, router, lineno = _read_out_route(
            tmp_path, script, _READ_OUT_FAIL_CLOSED[shape], name, quoted
        )
        assert result.returncode == 1, result.stdout + result.stderr
        assert _reported(result, router, lineno, name), result.stdout

    @pytest.mark.parametrize(
        "binding",
        list(_GENERIC_HEAD_BINDINGS),
        ids=list(_GENERIC_HEAD_BINDINGS),
    )
    def test_subscript_keys_stay_plain_only_under_a_generic_head(
        self, tmp_path, script, name, quoted, binding
    ):
        """A subscript hands its key to ``__class_getitem__``, which can
        read a string back out of it (``G[Literal["NoteService"]]``
        resolves to the class), so a subscript is a step of an approved
        path only under a head provably from ``typing``,
        ``typing_extensions`` or ``collections.abc`` or a builtin
        generic: not one rebound or replaced in the file (``list =
        G``, ``builtins.list = G``, ``typing.List = G``), and not a
        class of the project's own (fail closed)."""
        hooks = _mirror_hooks(tmp_path)
        prelude, template, accepted = _GENERIC_HEAD_BINDINGS[binding]
        annotation = template.format(ref=repr(name))
        if quoted:
            annotation = repr(annotation)
        source = (
            f"{_READ_OUT_PRELUDE}"
            f"{prelude}"
            f"def route(value: {annotation}):\n"
            "    return value\n"
        )
        lineno = source.count("\n", 0, source.index("def route(")) + 1
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/generic_heads.py",
            source,
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        if accepted:
            assert result.returncode == 0, result.stdout + result.stderr
        else:
            assert result.returncode == 1, result.stdout + result.stderr
            assert _reported(result, router, lineno, name), result.stdout

    @pytest.mark.parametrize(
        "binding", list(_FORM_BINDINGS), ids=list(_FORM_BINDINGS)
    )
    def test_plain_forms_need_the_form_imported_from_typing(
        self, tmp_path, script, name, quoted, binding
    ):
        """``Literal`` and ``Annotated`` hold exempt strings only where the
        head is provably the form ``typing`` or ``typing_extensions``
        defines, as a VALUE_ARGUMENTS callee must be: after ``from typing
        import Annotated as Literal``, ``Literal["NoteService",
        Depends()]`` is an ``Annotated`` whose type FastAPI builds. A head
        merely named ``Literal`` or ``Annotated`` (another module's, an
        assignment or rebinding, a second import, a star import, or one
        whose module has ``Literal`` replaced in the file) is checked; a
        proven alias is not."""
        hooks = _mirror_hooks(tmp_path)
        prelude, template, accepted = _FORM_BINDINGS[binding]
        annotation = template.format(ref=repr(name))
        if quoted:
            annotation = repr(annotation)
        source = (
            "import typing\n"
            "from typing import Annotated\n"
            "from fastapi import Depends\n"
            f"{prelude}"
            f"def route(value: {annotation}):\n"
            "    return value\n"
        )
        lineno = source.count("\n", 0, source.index("def route(")) + 1
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/plain_forms.py",
            source,
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        if accepted:
            assert result.returncode == 0, result.stdout + result.stderr
        else:
            assert result.returncode == 1, result.stdout + result.stderr
            assert _reported(result, router, lineno, name), result.stdout

    @pytest.mark.parametrize(
        "shape", list(_UNAPPROVED_PATHS), ids=list(_UNAPPROVED_PATHS)
    )
    def test_strings_off_an_approved_path_are_checked(
        self, tmp_path, script, name, quoted, shape
    ):
        """Exemption is an allowlist of shapes, so any node it does not
        approve ends the path, whatever its kind, and the string under it
        is checked: ``G | Literal["NoteService"]`` runs ``G``'s
        ``__or__``, which reads the string back out into a type position
        (with a ``Depends()`` default FastAPI then builds NoteService,
        ``username`` taken from the request)."""
        result, router, lineno = _read_out_route(
            tmp_path, script, _UNAPPROVED_PATHS[shape], name, quoted
        )
        assert result.returncode == 1, result.stdout + result.stderr
        assert _reported(result, router, lineno, name), result.stdout

    @pytest.mark.parametrize(
        "change", list(_PROOF_CHANGES), ids=list(_PROOF_CHANGES)
    )
    def test_a_file_that_may_change_a_proven_name_proves_nothing(
        self, tmp_path, script, name, quoted, change
    ):
        """Provenance fails closed: the annotation alone holds an exempt
        string, and after code through which the file could change what a
        proven name denotes (a dynamic namespace write, a store rooted in
        an import, an attribute store named like a form, an alias of a
        form or module ...) nothing in the file is proven, so the string
        is checked."""
        prelude, template = _PROOF_CHANGES[change]
        result, router, lineno = _read_out_route(
            tmp_path, script, template, name, quoted
        )
        assert result.returncode == 0, result.stdout + result.stderr
        result, router, lineno = _read_out_route(
            tmp_path, script, template, name, quoted, prelude
        )
        assert result.returncode == 1, result.stdout + result.stderr
        assert _reported(result, router, lineno, name), result.stdout

    @pytest.mark.parametrize(
        "template",
        [
            "Literal[{ref}]",
            "Optional[Literal[{ref}]]",
            "Annotated[str, Query(description={ref})]",
            "Annotated[str, {{'description': {ref}}}]",
        ],
        ids=["literal", "generic-head", "listed-argument", "metadata-dict"],
    )
    def test_ordinary_code_keeps_the_proofs(
        self, tmp_path, script, name, quoted, template
    ):
        """A generic head used as a whole annotation or in the key of a
        proven head, ``typing.TYPE_CHECKING``, ``isinstance(x, dict)``,
        ``from importlib import resources`` and stores on objects the
        file binds leave every proof standing."""
        result, _router, _lineno = _read_out_route(
            tmp_path, script, template, name, quoted, _PROOF_KEEPING
        )
        assert result.returncode == 0, result.stdout + result.stderr


#: ``{form: (annotation, string)}``: strings that parse as an expression
#: only as written or only stripped of surrounding whitespace -- a line
#: continuation at the end (FastAPI hands the raw string to
#: ``ForwardRef``, which compiles it as it is), leading whitespace, or
#: both (only the starred reading, ``({string},)[0]``, accepts that) --
#: in a call argument and in a type slot. ``{ref}`` is the string's
#: literal, and ``{name}`` the fenced name in the string.
_STRING_FORMS = {
    "continuation-in-an-argument": ("str({ref})", "{name} \\\n\t"),
    "continuation-in-cast": ("typing.cast(object, {ref})", "{name}\\\n "),
    "space-and-continuation-in-cast": (
        "typing.cast(object, {ref})",
        " {name}\\\n ",
    ),
    "continuation-in-a-type-slot": (
        "Annotated[{ref}, Depends()]",
        "{name}\\\n ",
    ),
    "space-in-a-type-slot": ("Annotated[{ref}, Depends()]", " {name}"),
}


@pytest.mark.parametrize(
    "script,name",
    [
        (ISOLATION_HOOK, "NoteService"),
        (REPORTS_HOOK, "FileResponse"),
        (REPORTS_HOOK, "static_file_response"),
    ],
    ids=["isolation", "reports-primitive", "reports-helper"],
)
@pytest.mark.parametrize("quoted", [False, True], ids=["unquoted", "quoted"])
class TestAnnotationStringForms:
    @pytest.mark.parametrize(
        "form", list(_STRING_FORMS), ids=list(_STRING_FORMS)
    )
    def test_strings_are_checked_as_written_and_stripped(
        self, tmp_path, script, name, quoted, form
    ):
        """A string that parses only as written -- the fenced name, then a
        backslash and a newline -- is the class to ``ForwardRef``, which
        compiles the raw string (``str()`` of it as a ``Depends()``
        parameter's annotation builds NoteService from the request), and
        one that parses only stripped is read that way too, so each form
        of a string is parsed and checked."""
        template, string = _STRING_FORMS[form]
        hooks = _mirror_hooks(tmp_path)
        annotation = template.format(ref=repr(string.format(name=name)))
        if quoted:
            annotation = repr(annotation)
        router = _write(
            tmp_path,
            "src/local_deep_research/web/routers/string_forms.py",
            "import typing\n"
            "from typing import Annotated\n"
            "from fastapi import Depends\n"
            f"def route(value: {annotation} = Depends()):\n"
            "    return value\n",
        )
        result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)
        assert result.returncode == 1, result.stdout + result.stderr
        assert _reported(result, router, 4, name), result.stdout


#: The parameter each VALUE_ARGUMENTS index stands for.
_INDEXED_VALUE_ARGUMENTS = {
    ("typing.NewType", 0): "name",
    ("typing.ForwardRef", 2): "module",
}


class TestValueArgumentSignatures:
    def test_value_arguments_match_the_signatures(self):
        """Each VALUE_ARGUMENTS entry is a parameter of the installed
        callee: a keyword it accepts, or the index of the positional
        parameter named in ``_INDEXED_VALUE_ARGUMENTS``. On Python 3.14
        ``ForwardRef``'s ``module`` is keyword-only, so index 2 cannot be
        passed at all there. Both hooks share one table."""
        import inspect
        import typing

        import fastapi
        import pydantic

        assert _reports_hook.VALUE_ARGUMENTS == (
            _isolation_hook.VALUE_ARGUMENTS
        ), "the hooks' VALUE_ARGUMENTS diverged"
        modules = {"fastapi": fastapi, "pydantic": pydantic, "typing": typing}
        named_kinds = (
            inspect.Parameter.POSITIONAL_OR_KEYWORD,
            inspect.Parameter.KEYWORD_ONLY,
        )
        for callee, positions in _isolation_hook.VALUE_ARGUMENTS.items():
            module, _, attribute = callee.rpartition(".")
            parameters = inspect.signature(
                getattr(modules[module], attribute)
            ).parameters
            positional = [
                p.name
                for p in parameters.values()
                if p.kind
                in (
                    inspect.Parameter.POSITIONAL_ONLY,
                    inspect.Parameter.POSITIONAL_OR_KEYWORD,
                )
            ]
            for position in positions:
                if isinstance(position, str):
                    assert position in parameters, f"{callee} has no {position}"
                    assert parameters[position].kind in named_kinds, (
                        f"{callee}'s {position} is not a keyword"
                    )
                    continue
                expected = _INDEXED_VALUE_ARGUMENTS[(callee, position)]
                if position < len(positional):
                    assert positional[position] == expected, (
                        f"{callee}'s index {position} is "
                        f"{positional[position]}, not {expected}"
                    )
                else:
                    assert callee == "typing.ForwardRef" and (
                        sys.version_info >= (3, 14)
                    ), f"{callee} has no positional index {position}"
                    assert parameters[expected].kind is (
                        inspect.Parameter.KEYWORD_ONLY
                    )


class TestReportFilenameCollisions:
    def test_same_query_same_second_yields_distinct_paths(
        self, tmp_path, monkeypatch
    ):
        """Same query, same second: the helper must still yield distinct
        names (preventive hardening; no production caller today)."""
        monkeypatch.setattr(research_service, "OUTPUT_DIR", tmp_path)
        import local_deep_research.web.services.research_service as rs

        real_datetime = rs.datetime

        class _FrozenDatetime(real_datetime):
            @classmethod
            def now(cls, tz=None):
                return real_datetime.fromtimestamp(1700000000, tz=tz)

        monkeypatch.setattr(rs, "datetime", _FrozenDatetime)

        first = research_service._generate_report_path("shared query")
        second = research_service._generate_report_path("shared query")

        assert first != second, (
            "deterministic filename: same query + same second collides "
            "in the shared directory"
        )