# SPDX-License-Identifier: AGPL-3.0-or-later
"""Regression pin for the git-internal environment leak (R17).

A commit made from a linked worktree of this repository exports five
git-internal variables into the hook Git runs for it: ``GIT_DIR``,
``GIT_INDEX_FILE``, ``GIT_WORK_TREE``, ``GIT_PREFIX`` and
``GIT_CONFIG_PARAMETERS``. An inherited ``GIT_DIR`` overrides ``git -C <dir>``,
so a fixture-style child spawned under that leak reads and writes another
repository's HEAD, index and config instead of its own tmpdir (measured: the
phase-7 run rewrote the shared ``.git/config`` and chained sixty fixture
commits onto its branch).

The seam is a refusal on both paths: ``scripts/hooks/pre-commit`` unsets the
five before its first Git command, so the suite it execs starts clean, and
``orchestrator.worktree``'s spawn environment drops them from every child it
spawns, so a leaked parent cannot steer a trusted spawn. The harness's own
``orchestrator.git_ops`` command wrapper routes through the same seam, so the
production Git spawns (materialisation, the fixed-target snapshot and verify
reads, the integration fetch/checkout) refuse the leak as a class. The
production read spawns refuse it too: ``derive_obligations``' ``ls-tree`` /
``show`` reads and the oracle frozen-input ``cat-file --batch`` read through
the same seam, so a read of one repository under a parent leaked at another
raises instead of exiting 0 with the wrong tree's objects. This module pins
all four halves against a deliberately leaked parent.

The five are named as literals rather than imported from the seam so this pin
imports at the step's base and reddens with a named assertion there, instead of
failing to import.

The spawn-path hardening holds the refusal over the merged copy itself: an
explicit ``extra`` overlay riding the five and a caller handing
``WorktreeManager._git`` a leaked map are both refused, so the hook-exec lane
and the fixture-spawn lane route through the one refusal list. The two members
below pin those halves.

The fast-suite copying fixtures inherit the same refusal: the suite's
``{**os.environ, **GIT_ENVIRONMENT}`` fixture spawns route through the seam's
merged copy instead of merging the ambient environment themselves
(``conformance._fixture_repo`` and the fixture helpers in the milestone-3,
milestone-8 and derived-obligations modules). A copying spawn under the
faithful five-leak therefore refuses fail-closed: the child serves its own
gitdir and the sentinel's shared config stays byte-identical. The behavioral
member and the source anchor at the end of this module pin that lane.
"""

from __future__ import annotations

import ast
import os
import subprocess
from pathlib import Path

import pytest

from orchestrator.worktree import _git_environment

REPO_ROOT = Path(__file__).resolve().parents[1]
PRE_COMMIT = REPO_ROOT / "scripts" / "hooks" / "pre-commit"

# The fast-suite modules whose fixture spawns copied the ambient environment
# around the fixture identity. The source anchor below holds them to the seam.
FAST_SUITE_COPYING_FILES = (
    "src/orchestrator/conformance.py",
    "tests/test_derive_obligations.py",
    "tests/test_milestone3_acceptance.py",
    "tests/test_milestone8_readiness.py",
)

LEAKED_VARIABLES = (
    "GIT_DIR",
    "GIT_INDEX_FILE",
    "GIT_WORK_TREE",
    "GIT_PREFIX",
    "GIT_CONFIG_PARAMETERS",
)


def _git(*args: str, env: dict[str, str]) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        ("git", *args), env=env, capture_output=True, text=True, check=False
    )


def _leaked_environment(worktree: Path, git_dir: str) -> dict[str, str]:
    """The environment a commit from the linked worktree ``worktree`` exports.

    The values mirror Git's own export shape: an absolute ``GIT_DIR`` at the
    worktree's gitdir, its index, the worktree path, an empty ``GIT_PREFIX``
    and the ``-c``-derived ``GIT_CONFIG_PARAMETERS``.
    """
    return {
        "GIT_DIR": git_dir,
        "GIT_INDEX_FILE": os.path.join(git_dir, "index"),
        "GIT_WORK_TREE": str(worktree),
        "GIT_PREFIX": "",
        "GIT_CONFIG_PARAMETERS": "'user.email=leak@example.com' 'user.name=leak'",
    }


def _seed_sentinel_repository(tmp_path: Path) -> Path:
    """A repository with a real linked worktree, whose register Git exports.

    ``git worktree add`` registers the worktree under
    ``<main>/.git/worktrees/<name>`` exactly as this repository's own
    disposable worktrees are registered, so the leak shape below is the real
    linked-worktree export and not a synthetic directory layout.
    """
    main = tmp_path / "sentinel"
    main.mkdir()
    (main / "tracked.txt").write_text("base\n")
    environment = _git_environment()
    for args in (("init", "-q"), ("add", "-A"), ("commit", "-q", "-m", "base")):
        _git("-C", str(main), *args, env=environment)
    linked = tmp_path / "sentinel-linked"
    _git("-C", str(main), "worktree", "add", "-q", "-b", "leak-probe", str(linked), env=environment)
    return linked


def _linked_worktree_git_dir(worktree: Path) -> str:
    """The absolute gitdir Git exports as ``GIT_DIR`` for a linked worktree."""
    return _git(
        "-C", str(worktree), "rev-parse", "--absolute-git-dir", env=_git_environment()
    ).stdout.strip()


def _seed_hooked_repository(tmp_path: Path) -> Path:
    """A repository with a real failing ``pre-commit`` hook installed.

    The hook exits 1, so a commit in this repository lands only when the
    hook is suppressed — the observable the suppression member grades.
    """
    repo = tmp_path / "hooked"
    repo.mkdir()
    (repo / "app.txt").write_text("app\n")
    environment = _git_environment()
    for args in (("init", "-q"), ("add", "-A")):
        _git("-C", str(repo), *args, env=environment)
    hook = repo / ".git" / "hooks" / "pre-commit"
    hook.write_text("#!/bin/sh\nexit 1\n")
    hook.chmod(0o755)
    return repo


def test_a_linked_worktree_leak_cannot_move_a_fixture_child_outside_its_tmpdir(
    tmp_path, monkeypatch
):
    linked = _seed_sentinel_repository(tmp_path)
    main = linked.parent / "sentinel"
    shared_config = (main / ".git" / "config").read_bytes()
    shared_head = _git("-C", str(main), "rev-parse", "HEAD", env=_git_environment()).stdout

    # The deliberate leak: a faithful linked-worktree parent shape, all five at
    # once, so the GIT_CONFIG_PARAMETERS-rides-into-children channel is
    # exercised alongside GIT_DIR.
    leak = _leaked_environment(linked, _linked_worktree_git_dir(linked))
    for name, value in leak.items():
        monkeypatch.setenv(name, value)

    # A fixture-style child: the init/add/commit sequence the suite's own Git
    # fixtures run as `git -C <tmpdir>`, spawned through the repository's
    # trusted spawn seam.
    child = tmp_path / "fixture-child"
    child.mkdir()
    (child / "app.txt").write_text("app\n")
    environment = _git_environment()
    for args in (("init", "-q"), ("add", "-A"), ("commit", "-q", "-m", "base")):
        _git("-C", str(child), *args, env=environment)

    assert (main / ".git" / "config").read_bytes() == shared_config, (
        "the shared config moved outside the child's tmpdir"
    )
    assert (
        _git("-C", str(main), "rev-parse", "HEAD", env=_git_environment()).stdout
        == shared_head
    ), "the shared HEAD moved outside the child's tmpdir"
    assert (child / ".git").is_dir(), "the child did not write into its own tmpdir"


def test_the_spawn_seam_removes_every_leaked_variable_from_the_child_environment(
    monkeypatch,
):
    for name in LEAKED_VARIABLES:
        monkeypatch.setenv(name, "leaked")
    environment = _git_environment()
    surviving = sorted(name for name in LEAKED_VARIABLES if name in environment)
    assert surviving == [], (
        f"the spawn seam passed the leaked variables through: {surviving}"
    )


def test_the_pre_commit_hook_scrubs_the_leak_before_its_first_git_child(
    tmp_path, monkeypatch
):
    # A stub `git` on PATH records the environment the hook hands its first Git
    # child and mimics `git rev-parse --show-toplevel`. The stubbed toplevel has
    # no `.venv/bin/python`, so the hook exits cleanly right after that read.
    stub_dir = tmp_path / "bin"
    stub_dir.mkdir()
    captured = tmp_path / "hook-child.env"
    toplevel = tmp_path / "hook-toplevel"
    toplevel.mkdir()
    stub = stub_dir / "git"
    stub.write_text(
        "#!/bin/sh\n"
        'env > "$CAPTURED_ENVIRONMENT"\n'
        'printf \'%s\\n\' "$STUB_TOPLEVEL"\n'
    )
    stub.chmod(0o755)

    for name in LEAKED_VARIABLES:
        monkeypatch.setenv(name, "leaked")
    environment = {
        **os.environ,
        "PATH": f"{stub_dir}{os.pathsep}{os.environ['PATH']}",
        "CAPTURED_ENVIRONMENT": str(captured),
        "STUB_TOPLEVEL": str(toplevel),
    }

    result = subprocess.run(
        ("bash", str(PRE_COMMIT)), env=environment, capture_output=True, text=True
    )
    assert result.returncode == 0, result.stderr

    observed = dict(
        line.split("=", 1) for line in captured.read_text().splitlines() if "=" in line
    )
    surviving = sorted(name for name in LEAKED_VARIABLES if name in observed)
    assert surviving == [], (
        f"the hook passed the leaked variables to its first Git child: {surviving}"
    )


def test_a_riding_hooks_path_cannot_silently_disable_a_real_hook(
    tmp_path, monkeypatch
):
    # The suppression shape: a riding ``GIT_CONFIG_PARAMETERS`` naming a
    # missing hooks directory silently disables the child's real failing
    # hook — the commit that exits 1 without the parameter exits 0 with it.
    # The seam refuses the ride, so the hook stays live however the parent
    # leaks.
    repo = _seed_hooked_repository(tmp_path)
    suppressed = _git(
        "-C",
        str(repo),
        "commit",
        "-m",
        "probe",
        env={
            **os.environ,
            "GIT_CONFIG_PARAMETERS": "'core.hooksPath=/nonexistent/missing-hooks'",
        },
    )
    assert suppressed.returncode == 0, (
        "the suppression control did not suppress: the riding hooksPath "
        f"must disable the failing hook, stderr={suppressed.stderr.strip()!r}"
    )
    assert "empty" not in suppressed.stderr.lower(), (
        "the suppression control is vacuous: the commit must land by hook "
        f"suppression, not on an empty stage, stderr={suppressed.stderr.strip()!r}"
    )

    before = _git(
        "-C", str(repo), "rev-list", "--count", "HEAD", env=_git_environment()
    ).stdout.strip()
    leak = {"GIT_CONFIG_PARAMETERS": "'core.hooksPath=/nonexistent/missing-hooks'"}
    for name, value in leak.items():
        monkeypatch.setenv(name, value)
    (repo / "second.txt").write_text("second\n")
    _git("-C", str(repo), "add", "-A", env=_git_environment())
    landed = _git("-C", str(repo), "commit", "-m", "probe", env=_git_environment())
    after = _git(
        "-C", str(repo), "rev-list", "--count", "HEAD", env=_git_environment()
    ).stdout.strip()
    assert (landed.returncode, after) == (1, before), (
        "the seam let the riding hooksPath suppress the real hook: "
        f"a commit that must fail exited {landed.returncode} "
        f"(commits before={before} after={after})"
    )


def test_the_materialise_tar_fetch_refuses_a_diverting_parent(
    tmp_path, monkeypatch
):
    # The tar-fetch site routes through the same seam: with the parent's
    # ``GIT_DIR`` diverted at an unrelated repository, the fetch must still
    # read the authoritative repository and materialise its tree — not fail
    # against the diverted gitdir, and not serve the other tree's content.
    from orchestrator.worktree import GIT_ENVIRONMENT, WorktreeManager

    authoritative = tmp_path / "authoritative.git"
    authoritative.mkdir()
    seed = tmp_path / "seed"
    seed.mkdir()
    seed_environment = _git_environment()
    _git("init", "-q", "--bare", str(authoritative), env=seed_environment)
    for args in (("init", "-q"),):
        _git("-C", str(seed), *args, env=seed_environment)
    (seed / "tracked.txt").write_text("base\n")
    for args in (("add", "-A"), ("commit", "-q", "-m", "base")):
        _git("-C", str(seed), *args, env=seed_environment)
    _git(
        "-C",
        str(seed),
        "push",
        "-q",
        str(authoritative),
        "HEAD:refs/heads/main",
        env=seed_environment,
    )
    base_commit = _git(
        "-C", str(seed), "rev-parse", "HEAD", env=seed_environment
    ).stdout.strip()

    other = tmp_path / "other"
    other.mkdir()
    _git("-C", str(other), "init", "-q", env=seed_environment)
    other_gitdir = _git(
        "-C", str(other), "rev-parse", "--absolute-git-dir", env=seed_environment
    ).stdout.strip()

    # The deliberate leak: the diverting parent shape — the leak names a
    # gitdir that exists but does not hold the base commit, so an unseamed
    # fetch reads the wrong repository and fails closed on its objects.
    monkeypatch.setenv("GIT_DIR", other_gitdir)

    manager = WorktreeManager(
        repository=str(authoritative),
        worktree_root=str(tmp_path / "worktrees"),
        artefact_root=str(tmp_path / "artefacts"),
    )
    destination = manager.materialise(base_commit, "seam-probe")
    assert (Path(destination) / "tracked.txt").read_text() == "base\n", (
        "the tar fetch did not serve the authoritative tree under the leak"
    )
    _ = GIT_ENVIRONMENT  # the seam's fixture identity rides unchanged


def test_a_linked_worktree_leak_cannot_steer_git_ops_children_outside_their_tmpdir(
    tmp_path, monkeypatch
):
    # The production-spawn half of the seam: ``orchestrator.git_ops._git``
    # (materialisation, the fixed-target snapshot and verify reads, the
    # integration fetch/checkout) routes through the same refusal, so a
    # fixture-style init/add/commit sequence spawned through it under the
    # deliberately leaked parent must still land in its own tmpdir and leave
    # the shared config and HEAD byte-identical — exactly the bar the
    # fixture-child pin sets for the worktree seam.
    from orchestrator.git_ops import _git

    linked = _seed_sentinel_repository(tmp_path)
    main = linked.parent / "sentinel"
    shared_config = (main / ".git" / "config").read_bytes()
    shared_head = subprocess.run(
        ("git", "-C", str(main), "rev-parse", "HEAD"),
        env=_git_environment(),
        capture_output=True,
        text=True,
        check=False,
    ).stdout

    # The deliberate leak: the same faithful linked-worktree parent shape as
    # the fixture-child pin, all five at once.
    leak = _leaked_environment(linked, _linked_worktree_git_dir(linked))
    for name, value in leak.items():
        monkeypatch.setenv(name, value)

    child = tmp_path / "git-ops-child"
    child.mkdir()
    (child / "app.txt").write_text("app\n")
    for args in (("init", "-q"), ("add", "-A"), ("commit", "-q", "-m", "base")):
        _git(str(child), *args)

    # The named assertion: the shared config is byte-identical. At REV the
    # leaked child's `init` steers into the sentinel and injects
    # `worktree = <linked path>` there (the same mutation the fixture-child
    # pin observes), so this assert fails there while the `(child / ".git")`
    # assert below never runs.

    shared_config_after = (main / ".git" / "config").read_bytes()
    shared_head_after = subprocess.run(
        ("git", "-C", str(main), "rev-parse", "HEAD"),
        env=_git_environment(),
        capture_output=True,
        text=True,
        check=False,
    ).stdout
    assert shared_config_after == shared_config, (
        "the shared config moved outside the child's tmpdir"
    )
    assert shared_head_after == shared_head, (
        "the shared HEAD moved outside the child's tmpdir"
    )
    assert (child / ".git").is_dir(), "the child did not write into its own tmpdir"


def test_a_linked_worktree_leak_cannot_steer_read_children_into_another_tree(
    tmp_path, monkeypatch
):
    """Every production read spawn routes through the refusal seam.

    The production reads (``derive_obligations._python_files`` /
    ``_read_blob`` and the oracle frozen-input ``cat-file --batch``) run
    through the same ``_git_environment`` seam as the write-side spawns, so a
    parent that leaks a linked worktree's exported environment can never steer
    a read into the wrong tree: the read serves its own repository's objects.
    The control first proves the leak steering-capable past the seam (the
    diverted tree's bytes land at a zero exit); then, under the deliberate
    five-leak, the two derive reads and the frozen-input batch read must each
    serve the source repository's own bytes.
    """
    from orchestrator import derive_obligations
    from orchestrator.project_oracle import (
        FrozenFloors,
        _sha256_file,
        _verify_frozen_inputs_match_commit,
    )
    from types import SimpleNamespace

    seed = _git_environment()
    bare = tmp_path / "read-source.git"
    tree = tmp_path / "read-tree"
    tree.mkdir()
    (tree / "obligation.py").write_text("VALUE = 1\n")
    _git("init", "-q", "--bare", str(bare), env=seed)
    for args in (("init", "-q"), ("add", "-A"), ("commit", "-q", "-m", "base")):
        _git("-C", str(tree), *args, env=seed)
    _git("-C", str(tree), "remote", "add", "origin", str(bare), env=seed)
    _git("-C", str(tree), "push", "-q", str(bare), "HEAD:refs/heads/main", env=seed)
    commit = _git("-C", str(bare), "rev-parse", "refs/heads/main", env=seed).stdout.strip()

    other = tmp_path / "read-other"
    other.mkdir()
    (other / "obligation.py").write_text("VALUE = 999\n")
    for args in (("init", "-q"), ("add", "-A"), ("commit", "-q", "-m", "diverter")):
        _git("-C", str(other), *args, env=seed)
    diverter = _git("-C", str(other), "rev-parse", "HEAD", env=seed).stdout.strip()
    assert diverter != commit

    linked = tmp_path / "read-linked"
    _git("-C", str(bare), "worktree", "add", "-q", "--detach", str(linked), commit, env=seed)
    linked_gitdir = _git(
        "-C", str(linked), "rev-parse", "--absolute-git-dir", env=seed
    ).stdout.strip()
    other_gitdir = _git(
        "-C", str(other), "rev-parse", "--absolute-git-dir", env=seed
    ).stdout.strip()
    leak = _leaked_environment(linked, linked_gitdir)
    leak["GIT_DIR"] = other_gitdir

    # Control: the leak is steering-capable past the seam — the diverted
    # tree's bytes land at a zero exit.
    steered = subprocess.run(
        ("git", "-C", str(bare), "show", f"{diverter}:obligation.py"),
        capture_output=True,
        env={**os.environ, **leak},
        check=False,
    )
    assert steered.returncode == 0
    assert steered.stdout == b"VALUE = 999\n"

    # Through the seam none of the five may reach the child: the leaked
    # parent shape rides os.environ, and the seam drops all five from it.
    for name, value in leak.items():
        monkeypatch.setenv(name, value)
    assert not any(name in _git_environment() for name in LEAKED_VARIABLES)

    # Under the deliberate five-leak each production read serves its own
    # repository's objects — never the diverted tree's.
    assert "obligation.py" in derive_obligations._python_files(str(bare), commit)
    assert (
        derive_obligations._read_blob(str(bare), commit, "obligation.py")
        == b"VALUE = 1\n"
    )

    floors = FrozenFloors(
        counterexample_min_covered=0,
        open_defects_min_fixed=0,
        open_defects_min_open=0,
        guard_min_parameters=0,
        fidelity_rows=0,
        gate_hashes={},
        registry_hashes={},
        control_hashes={},
        test_hashes={"obligation.py": _sha256_file(str(tree / "obligation.py"))},
        test_modules=(),
        covered_findings={},
        fixed_defects={},
        guard_parameters={},
        fidelity_fakes={},
    )
    target = SimpleNamespace(repository=str(bare), commit=commit)
    blobs = _verify_frozen_inputs_match_commit(target, str(tree), floors)
    assert blobs["obligation.py"] == b"VALUE = 1\n"
    assert (
        _git("-C", str(bare), "rev-parse", "refs/heads/main", env=seed).stdout.strip()
        == commit
    )


def test_the_seam_refuses_five_riding_in_the_extra_overlay(tmp_path, monkeypatch):
    """The refusal holds over the merged copy, not just the ambient half.

    A caller passing the five explicitly in ``extra`` (a fixture copying a
    poisoned parent into the overlay) must still observe none of them: at REV
    the builder pops before the update, so the overlay reintroduces the leak
    and this member reds at its named assertion.
    """
    linked = _seed_sentinel_repository(tmp_path)
    leak = _leaked_environment(linked, _linked_worktree_git_dir(linked))
    environment = _git_environment(dict(leak))
    surviving = sorted(name for name in LEAKED_VARIABLES if name in environment)
    assert surviving == [], (
        f"the seam let the extra overlay reintroduce the leak: {surviving}"
    )


def test_the_manager_git_scrubs_a_dirty_caller_environment(tmp_path):
    """``WorktreeManager._git`` refuses a leaked caller map at the spawn.

    A fixture-style caller handing ``_git`` a whole copied parent (the five
    included) must still serve its own repository: the child ``rev-parse``
    answers its own gitdir, never the leaked one. At REV ``_git`` trusts the
    caller map, so the leaked ``GIT_DIR`` steers the read and this member reds
    at the named assertion.
    """
    from orchestrator.worktree import WorktreeManager

    seed = _git_environment()
    child = tmp_path / "caller-child"
    child.mkdir()
    for args in (("init", "-q"), ("add", "-A"), ("commit", "-q", "-m", "base")):
        if args[0] == "init":
            (child / "app.txt").write_text("app\n")
        _git("-C", str(child), *args, env=seed)
    child_gitdir = _git(
        "-C", str(child), "rev-parse", "--absolute-git-dir", env=seed
    ).stdout.strip()

    other = tmp_path / "caller-other"
    other.mkdir()
    for args in (("init", "-q"),):
        _git("-C", str(other), *args, env=seed)
    other_gitdir = _git(
        "-C", str(other), "rev-parse", "--absolute-git-dir", env=seed
    ).stdout.strip()
    assert other_gitdir != child_gitdir

    leak = _leaked_environment(other, other_gitdir)
    dirty = {**seed, **leak}
    manager = WorktreeManager(
        repository=str(child),
        worktree_root=str(tmp_path / "worktrees"),
        artefact_root=str(tmp_path / "artefacts"),
    )
    observed = manager._git(str(child), dirty, "rev-parse", "--absolute-git-dir").strip()
    assert observed == child_gitdir, (
        "a dirty caller map steered the trusted spawn outside its own tmpdir: "
        f"observed {observed!r} != child {child_gitdir!r}"
    )


def test_a_copying_fixture_spawn_refuses_the_five_variable_leak(tmp_path, monkeypatch):
    """The fast-suite copying fixture is fail-closed under the faithful leak.

    ``conformance._fixture_repo`` is the fixture the suite builds exactly as
    ``{**os.environ, **GIT_ENVIRONMENT}``; under the five-variable linked
    worktree leak an unseamed copy steers every child at the sentinel's gitdir
    (the child gets no ``.git`` and the sentinel's config gains a ``worktree =``
    line), while a seamed copy refuses the five and the child writes its own
    gitdir. At REV the shared-config assertion reds; at FINAL the child, its
    commit and the shared repository are all its own.
    """
    from orchestrator.conformance import _fixture_repo

    linked = _seed_sentinel_repository(tmp_path)
    main = linked.parent / "sentinel"
    shared_config = (main / ".git" / "config").read_bytes()
    shared_head = _git(
        "-C", str(main), "rev-parse", "HEAD", env=_git_environment()
    ).stdout.strip()

    leak = _leaked_environment(linked, _linked_worktree_git_dir(linked))
    for name, value in leak.items():
        monkeypatch.setenv(name, value)

    root = tmp_path / "copying-fixture"
    root.mkdir()
    expected_repo = str(root / "copying-child")
    try:
        repo, commit = _fixture_repo(str(root), name="copying-child")
    except subprocess.CalledProcessError:
        # At REV the steered `git commit` exits 1 against the sentinel's
        # gitdir. The observables below are what the member grades; the
        # exception is not the red.
        repo, commit = expected_repo, None

    assert (main / ".git" / "config").read_bytes() == shared_config, (
        "the copying fixture's spawn steered the shared config outside its tmpdir"
    )
    assert (
        _git("-C", str(main), "rev-parse", "HEAD", env=_git_environment()).stdout.strip()
        == shared_head
    ), "the copying fixture's spawn moved the shared HEAD outside its tmpdir"
    assert Path(repo, ".git").is_dir(), (
        "the copying fixture's child did not write into its own tmpdir"
    )
    observed = _git(
        "-C", repo, "rev-parse", "HEAD", env=_git_environment()
    ).stdout.strip()
    assert commit == observed, (
        "the copying fixture returned another tree's commit: "
        f"returned {commit!r} != child {observed!r}"
    )


def _environ_merge_lines(source: str) -> list[int]:
    """Every line holding a dict display that unpacks ``os.environ``."""
    lines = []
    for node in ast.walk(ast.parse(source)):
        if not isinstance(node, ast.Dict):
            continue
        for value in node.values:
            if (
                isinstance(value, ast.Attribute)
                and value.attr == "environ"
                and isinstance(value.value, ast.Name)
                and value.value.id == "os"
            ):
                lines.append(node.lineno)
    return lines


def test_no_fast_suite_copying_fixture_merge_bypasses_the_seam():
    """Every fast-suite copying fixture routes through the refusal seam.

    The copying expression is only safe when the seam drops the five after the
    merge; a raw ``{**os.environ, ...}`` in these modules copies an ambient
    leak around the pop. At REV the five fixture merges are found here; at
    FINAL each module builds its fixture environment through
    ``_git_environment``.
    """
    offenders = []
    for relative in FAST_SUITE_COPYING_FILES:
        path = REPO_ROOT / relative
        for line in _environ_merge_lines(path.read_text()):
            offenders.append(f"{relative}:{line}")
    assert offenders == [], (
        "a fast-suite copying fixture still merges os.environ around the "
        f"refusal seam: {offenders}"
    )
