← Files Codex SecurityARCHIVED FILE

scripts/workbench_target.py

70.2 KB · Nov 18, 2026 · 06:11 UTC

↓ Download file

See the change to this file →

"""Target inspection and content-integrity helpers for the security workbench."""

from __future__ import annotations

import argparse
import codecs
import hashlib
import json
import os
import re
import shutil
import sqlite3
import stat
import subprocess
import sys
import tempfile
import unicodedata
from collections.abc import Iterable, Iterator
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack, contextmanager
from contextvars import ContextVar
from pathlib import Path, PurePosixPath
from typing import Any, BinaryIO, Callable, cast

# Some plugin hosts launch Python with safe-path isolation enabled.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from filesystem_identity import serialize_filesystem_identity, stored_filesystem_identity_matches
from windows_scan_local_files import copy_directory_junction, pinned_root_git_marker
from workbench_constants import GIT_REPOSITORY_ENVIRONMENT

SOURCE_METADATA_DIRECTORIES = {".git", ".svn"}
_WINDOWS = os.name == "nt"
_SCOPED_GIT: ContextVar[Callable[[Path], str] | None] = ContextVar("workbench_git", default=None)


class UnreadableLocalFile(SystemExit):
    """Source contents are unavailable for an optional review cache."""


class UnsupportedLocalFileType(SystemExit):
    """An entry cannot be read as source content for a review cache."""


def committed_diff_snapshot_digest(kind: str, base_revision: str, head_revision: str) -> str:
    digest = hashlib.sha256(
        f"codex-security-diff/v1\0{kind}\0{base_revision}\0{head_revision}".encode()
    ).hexdigest()
    return f"codex-security-snapshot/v1:sha256:{digest}"


def diff_snapshot_digest(scan: sqlite3.Row, manifest: dict[str, Any] | None) -> str | None:
    """Return the content identity used for a stored diff, or None when unavailable.

    Working-tree scans use their recorded content digest. Commit and range scans
    reuse the sealed manifest value during recovery or derive a digest from both revisions.
    """
    if scan["diff_target_kind"] == "working_tree":
        return scan["diff_content_digest"]
    if scan["diff_target_kind"] in {"commit", "range"}:
        manifest_scan = manifest.get("scan") if manifest is not None else None
        # Preserve the recorded digest when recovery rebuilds a sealed manifest.
        if isinstance(manifest_scan, dict) and (
            manifest_scan.get("sealedAt") is not None or manifest_scan.get("artifacts")
        ):
            target = manifest_scan.get("target")
            return target.get("snapshotDigest") if isinstance(target, dict) else None
        return committed_diff_snapshot_digest(
            scan["diff_target_kind"], scan["diff_base_revision"], scan["diff_head_revision"]
        )
    return None


def git_output(
    target: Path,
    *args: str,
    git_dir: Path | None = None,
    work_tree: Path | None = None,
    offline: bool = False,
) -> str | None:
    """Return decoded Git stdout with one trailing newline removed, or None on failure or empty output."""
    completed = git_command(
        target, *args, text=False, git_dir=git_dir, work_tree=work_tree, offline=offline
    )
    output = os.fsdecode(completed.stdout)
    if sys.platform == "win32" and output.endswith("\r\n"):
        output = output[:-2]
    else:
        output = output.removesuffix("\n")
    return output if completed.returncode == 0 and output else None


def git_bytes(
    target: Path,
    *args: str,
    git_dir: Path | None = None,
    work_tree: Path | None = None,
    offline: bool = False,
) -> bytes | None:
    completed = git_command(
        target, *args, text=False, git_dir=git_dir, work_tree=work_tree, offline=offline
    )
    return completed.stdout if completed.returncode == 0 else None


def git_blob_binary_flags(
    target: Path,
    object_names: list[str],
    *,
    git_dir: Path | None = None,
    work_tree: Path | None = None,
) -> list[bool | None]:
    """Classify ordered blobs without retaining their contents."""
    if not object_names:
        return []

    # Git before 2.38 rejects -z, so only names with line breaks need it.
    nul_input = any("\n" in name or "\r" in name for name in object_names)
    separator = b"\0" if nul_input else b"\n"
    request = separator.join(os.fsencode(name) for name in object_names) + separator
    read_fd, write_fd = os.pipe()
    with (
        ThreadPoolExecutor(max_workers=1) as reader,
        os.fdopen(read_fd, "rb") as output,
        os.fdopen(write_fd, "wb") as sink,
    ):

        def read_samples() -> list[bool | None]:
            # Closing the reader also unblocks Git if framing is invalid.
            with output:
                return _read_git_batch_flags(output, object_names)

        samples = reader.submit(read_samples)
        try:
            completed = git_command(
                target,
                "cat-file",
                "--batch",
                *(["-z"] if nul_input else []),
                text=False,
                input_data=request,
                git_dir=git_dir,
                work_tree=work_tree,
                stdout_file=sink,
                offline=True,
            )
        finally:
            # Git may fail before producing all requested records.
            sink.close()
        if completed.returncode != 0:
            return [None] * len(object_names)
        try:
            return samples.result()
        except ValueError:
            return [None] * len(object_names)


def _read_git_batch_flags(output: BinaryIO, object_names: list[str]) -> list[bool | None]:
    """Read the older-Git-compatible -z protocol without buffering blob bodies."""
    samples: list[bool | None] = []
    for name in object_names:
        header = output.readline()
        raw_name = os.fsencode(name)
        # Missing lookups echo the whole request, including any embedded newlines.
        if header and raw_name.startswith(header):
            header += output.read(len(raw_name) - len(header)) + output.readline()
        if header in (raw_name + b" missing\n", raw_name + b" ambiguous\n"):
            samples.append(None)
            continue
        fields = header.split(b" ")
        if len(fields) != 3 or not header.endswith(b"\n"):
            raise ValueError("invalid batch header")
        size = int(fields[2])
        if size < 0:
            raise ValueError("invalid blob size")
        # Consume non-blob objects too, so subsequent records stay aligned.
        sample = _stream_is_binary(output, size, drain=True)
        if output.read(1) != b"\n":
            raise ValueError("missing blob terminator")
        samples.append(sample if fields[1] == b"blob" else None)
    return samples


def _is_binary_sample(data: bytes) -> bool:
    if data.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)):
        return "\0" in data.decode("utf-16", errors="ignore")
    return b"\0" in data


def _stream_is_binary(output: BinaryIO, size: int, *, drain: bool = False) -> bool:
    read_size = 64 * 1024
    sample_size = min(size, read_size)
    sample = output.read(sample_size)
    if len(sample) != sample_size:
        raise ValueError("truncated blob")
    binary = _is_binary_sample(sample)
    bom = sample[:2] if sample.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)) else b""
    remaining = size - sample_size
    while remaining and (drain or not binary):
        chunk_size = min(remaining, read_size)
        chunk = output.read(chunk_size)
        if len(chunk) != chunk_size:
            raise ValueError("truncated blob")
        # Even-sized reads keep UTF-16 code units aligned; preserve the original byte order.
        if not binary:
            binary = _is_binary_sample(bom + chunk) if bom else b"\0" in chunk
        remaining -= chunk_size
    return binary


def _protected_repository_root(target: Path) -> Path:
    root = target.resolve()
    return _outer_checkout_root(root.parent if root.is_file() else root)


def _outer_checkout_root(root: Path) -> Path:
    protected = root
    for ancestor in (root, *root.parents):
        try:
            (ancestor / ".git").lstat()
        except FileNotFoundError:
            continue
        protected = ancestor
    return protected


def rejected_checkout_roots(value: str) -> list[str] | None:
    # Retain both spellings before a checkout marker or symlink can move.
    try:
        lexical = Path(value).expanduser().absolute()
        canonical = lexical.resolve()
        lexical_root = _outer_checkout_root(lexical)
        roots = {
            lexical,
            canonical,
            lexical_root,
            lexical_root.resolve(),
            _protected_repository_root(canonical),
        }
        return sorted(map(str, roots))
    except (OSError, RuntimeError):
        return None


def pin_scoped_git(target: Path) -> str | None:
    scoped = _SCOPED_GIT.get()
    return scoped(target) if scoped is not None else None


def trusted_git_executable(protected_root: Path) -> str | None:
    """Validate host-selected Git, or discover Git for a direct plugin invocation."""
    configured = os.environ.get("CODEX_SECURITY_GIT")
    if configured is None:
        configured = pin_scoped_git(protected_root)
    return _resolve_git_executable(protected_root, configured)


def _historical_repository_roots(target: Path) -> Iterator[Path]:
    try:
        yield _protected_repository_root(target)
    except (OSError, RuntimeError):
        # Keep checking lexical ancestry when the saved path cannot be resolved.
        pass
    # A moved or unavailable descendant still excludes its lexical checkout ancestry.
    root = Path(os.path.abspath(target))
    protected = root
    for ancestor in (root, *root.parents):
        try:
            (ancestor / ".git").lstat()
        except (OSError, RuntimeError):
            continue
        protected = ancestor
    yield protected
    try:
        yield protected.resolve()
    except (OSError, RuntimeError):
        # The lexical root above still excludes tools at an unavailable checkout.
        pass


def _resolve_git_executable(
    protected_root: Path,
    configured: str | None,
    *,
    discovery_roots: Iterable[Path] = (),
    recorded_git_roots: Iterable[Path] | None = (),
) -> str | None:
    windows = sys.platform == "win32"
    if configured is None:
        names = ("git.exe", "git.com") if windows else ("git",)
        candidates = (
            Path(entry.strip('"') if windows else entry) / name
            for entry in os.get_exec_path()
            for name in names
        )
    elif not configured:
        return None
    else:
        candidate = Path(configured)
        if not candidate.is_absolute():
            raise SystemExit("CODEX_SECURITY_GIT must name an absolute trusted executable.")
        candidates = iter((candidate,))

    try:
        repositories = [_protected_repository_root(protected_root)]
        if configured is None:
            # A legacy Git target has no trustworthy boundary to exclude from PATH.
            if recorded_git_roots is None:
                return None
            saved_boundaries = tuple(recorded_git_roots)
            for root in saved_boundaries:
                repositories.extend(_historical_repository_roots(root))
            for root in discovery_roots:
                for repository in _historical_repository_roots(root):
                    if not repository.is_dir() and not any(
                        repository.is_relative_to(boundary) for boundary in saved_boundaries
                    ):
                        # Its former checkout is neither discoverable nor already excluded.
                        return None
                    repositories.append(repository)
    except (OSError, RuntimeError):
        return None

    for candidate in candidates:
        try:
            lexical = Path(os.path.abspath(candidate))
            invocation = candidate.parent.resolve(strict=True) / candidate.name
            canonical = candidate.resolve(strict=True)
        except (OSError, RuntimeError):
            continue
        if (
            not canonical.is_file()
            or not os.access(canonical, os.F_OK if windows else os.X_OK)
            or (
                windows
                and (
                    candidate.suffix.lower() not in {".exe", ".com"}
                    or canonical.suffix.lower() in {".bat", ".cmd"}
                )
            )
        ):
            continue
        if any(
            path == repository or repository in path.parents
            for repository in repositories
            for path in (lexical, invocation, canonical)
        ):
            if configured is not None:
                raise SystemExit("CODEX_SECURITY_GIT must stay outside the protected repository.")
            continue
        return str(invocation)
    return None


@contextmanager
def scoped_git_discovery(
    protected_roots: Callable[[], Iterable[Path]],
    *,
    recorded_git_roots: Callable[[], Iterable[Path] | None] = lambda: (),
) -> Iterator[None]:
    """Pin ambient Git when an operation first needs to inspect repository targets."""
    if os.environ.get("CODEX_SECURITY_GIT") is not None:
        yield
        return
    executable: str | None = None

    def resolve_once(target: Path) -> str:
        nonlocal executable
        if executable is None:
            executable = (
                _resolve_git_executable(
                    Path.cwd(),
                    None,
                    discovery_roots=(*protected_roots(), target),
                    recorded_git_roots=recorded_git_roots(),
                )
                or ""
            )
        return executable

    token = _SCOPED_GIT.set(resolve_once)
    try:
        yield
    finally:
        _SCOPED_GIT.reset(token)


def git_command(
    target: Path,
    *args: str,
    text: bool,
    input_data: str | bytes | None = None,
    git_dir: Path | None = None,
    work_tree: Path | None = None,
    stdout_file: BinaryIO | None = None,
    environment_overrides: dict[str, str] | None = None,
    inherit_git_environment: bool = True,
    offline: bool = False,
) -> subprocess.CompletedProcess[str] | subprocess.CompletedProcess[bytes]:
    """Run Git against target and return the completed process with its exit status.

    Pass git_dir and work_tree together to select an explicit checkout. Set
    offline to disable transports and lazy fetches. The text flag selects
    decoded or binary output, and stdout_file can redirect it to a file.
    """
    if (git_dir is None) != (work_tree is None):
        raise ValueError("git_dir and work_tree must be provided together")
    environment = (
        os.environ.copy()
        if inherit_git_environment
        else {
            name: value for name, value in os.environ.items() if not name.upper().startswith("GIT_")
        }
    )
    for name in GIT_REPOSITORY_ENVIRONMENT:
        environment.pop(name, None)
    environment["GIT_LITERAL_PATHSPECS"] = "1"
    if environment_overrides is not None:
        environment.update(environment_overrides)
    if offline:
        # Deny transports even on Git versions that do not honor GIT_NO_LAZY_FETCH.
        environment.update(GIT_NO_LAZY_FETCH="1", GIT_ALLOW_PROTOCOL="")
    executable = trusted_git_executable(target)
    # Repository-local config is untrusted; fsmonitor may name an executable hook.
    command = [
        executable or "git",
        "-c",
        "core.fsmonitor=false",
        "-c",
        "i18n.logOutputEncoding=UTF-8",
        "-C",
        str(target),
    ]
    if git_dir is not None and work_tree is not None:
        command.extend(["--git-dir", str(git_dir), "--work-tree", str(work_tree)])
    full_command = [*command, *args]
    if executable is None:
        empty_output = "" if text else b""
        return subprocess.CompletedProcess(full_command, 127, empty_output, empty_output)
    try:
        output_options = (
            {"capture_output": True}
            if stdout_file is None
            else {"stdout": stdout_file, "stderr": subprocess.PIPE}
        )
        return subprocess.run(
            full_command,
            check=False,
            env=environment,
            text=text,
            encoding="utf-8" if text else None,
            errors="surrogateescape" if text else None,
            input=input_data,
            **output_options,
        )
    except FileNotFoundError:
        # Git is optional for Codebase scans. Treat an unavailable executable like
        # any other failed Git probe so the target falls back to a directory snapshot.
        empty_output = "" if text else b""
        return subprocess.CompletedProcess(full_command, 127, empty_output, empty_output)


def run_git_changed_paths(repo: Path, diff_args: list[str]) -> list[tuple[str, str, str | None]]:
    """Return changed regular files from the selected side of each change."""
    result = git_command(
        repo,
        "diff",
        "--ignore-submodules=all",
        "--raw",
        "-z",
        "--diff-filter=ACMRDT",
        *diff_args,
        "--",
        text=False,
        offline=True,
    )
    result.check_returncode()
    fields = result.stdout.split(b"\0")
    if fields and not fields[-1]:
        fields.pop()

    changed: list[tuple[str, str, str | None]] = []
    index = 0
    while index < len(fields):
        metadata = fields[index].split()
        status = chr(metadata[-1][0])
        index += 1
        rename_source = os.fsdecode(fields[index]) if status == "R" else None
        if status in {"C", "R"}:
            index += 1
        path = os.fsdecode(fields[index])
        index += 1
        selected_mode = metadata[0].removeprefix(b":") if status == "D" else metadata[1]
        if selected_mode.startswith(b"100"):
            changed.append((path, status, rename_source))
    return changed


def git_changed_paths(repo: Path, base: str, head: str, mode: str) -> list[tuple[Path, str]]:
    if mode == "revisions":
        return [
            (repo / name, status)
            for name, status, _ in run_git_changed_paths(repo, [f"{base}..{head}"])
        ]
    if mode == "local-patch":
        unstaged = run_git_changed_paths(repo, [base])
        staged = run_git_changed_paths(repo, ["--cached", base])
        untracked = git_command(
            repo,
            "ls-files",
            "--others",
            "--exclude-standard",
            "-z",
            text=False,
            offline=True,
        )
        untracked.check_returncode()
        combined = {name: (status, source) for name, status, source in [*staged, *unstaged]}
        selected: dict[str, str] = {}
        linked_prefixes: dict[str, bool] = {}

        def local_status(name: str, status: str) -> str | None:
            if not SOURCE_METADATA_DIRECTORIES.isdisjoint(PurePosixPath(name).parts):
                return None
            if status == "D":
                return status
            path = repo / name
            try:
                if (
                    status in {"M", "R"}
                    and _directory_link_boundary(repo, path, linked_prefixes) != path
                ):
                    return "D" if status == "M" else None
                return status if stat.S_ISREG(path.lstat().st_mode) else None
            except (FileNotFoundError, NotADirectoryError):
                return None

        for name, (status, source) in combined.items():
            if chosen := local_status(name, status):
                selected[name] = chosen
            elif source is not None and local_status(source, "D"):
                selected.setdefault(source, "D")
        for relative in untracked.stdout.split(b"\0"):
            if relative and not relative.endswith(b"/"):
                name = os.fsdecode(relative)
                if local_status(name, "A"):
                    selected[name] = "A"
        return sorted((repo / name, status) for name, status in selected.items())
    raise SystemExit(f"Unknown diff mode: {mode}")


def diff_scope_file_count(target: Path, diff_target: dict[str, str]) -> int | None:
    base, head = diff_target["baseRevision"], diff_target["headRevision"]
    local = diff_target["kind"] == "working_tree"
    selected: list[str] = []
    committed: dict[str, str] = {}
    try:
        changes = git_changed_paths(target, base, head, "local-patch" if local else "revisions")
    except subprocess.CalledProcessError:
        # A partial clone can lack a tree needed even to enumerate the changed paths.
        return None
    for path, status in changes:
        name = path.relative_to(target).as_posix()
        if not local or status == "D":
            committed[name] = f"{base if status == 'D' else head}:{name}"
        else:
            try:
                resolved = path.resolve(strict=True)
                if not resolved.is_relative_to(target):
                    continue
                with resolved.open("rb") as stream:
                    binary = _stream_is_binary(stream, os.fstat(stream.fileno()).st_size)
            except (OSError, ValueError):
                continue
            if not binary:
                selected.append(name)
    for name, binary in zip(
        committed, git_blob_binary_flags(target, list(committed.values())), strict=True
    ):
        if binary is None:
            return None
        if not binary:
            selected.append(name)
    if any("\n" in name or "\r" in name for name in selected):
        return None
    return len(selected)


def candidate_source_lines(
    target: Path,
    diff_target: dict[str, str],
    paths: list[str],
    locations: list[str],
    case_insensitive: bool = False,
) -> dict[str, dict[str, Any]]:
    """Resolve candidate sources in the same selected view as the diff inventory."""
    base, head = diff_target["baseRevision"], diff_target["headRevision"]
    local = diff_target["kind"] == "working_tree"
    changed = {
        path.relative_to(target).as_posix(): status
        for path, status in git_changed_paths(
            target, base, head, "local-patch" if local else "revisions"
        )
    }
    selected_names = set(changed)
    aliases: dict[str, str | None] = {}
    if case_insensitive:
        if not local:
            tree = git_command(target, "ls-tree", "-r", "-t", "-z", "--name-only", head, text=False)
            tree.check_returncode()
            selected_names.update(os.fsdecode(name) for name in tree.stdout.split(b"\0") if name)
        for name in selected_names:
            key = name.lower()
            aliases[key] = None if key in aliases and aliases[key] != name else name
    location_set = set(locations)
    result: dict[str, dict[str, Any]] = {}
    counts: dict[str, int] = {}
    for raw in dict.fromkeys([*paths, *locations]):
        path = PurePosixPath(raw)
        if not raw or path.is_absolute() or ".." in path.parts or "\0" in raw:
            raise ValueError("path: expected a repository-relative path without traversal")
        name = path.as_posix()
        if case_insensitive and name not in selected_names:
            selected = aliases.get(name.lower(), name)
            if selected is None:
                result[raw] = {"error": "missing"}
                continue
            name = selected
        deleted = changed.get(name) == "D"
        if local and not deleted:
            continue
        revision = base if deleted else head
        if name not in changed:
            entry = git_command(target, "ls-tree", "-z", revision, "--", name, text=False)
            entry.check_returncode()
            metadata = next(
                (
                    row.partition(b"\t")[0].split()
                    for row in entry.stdout.split(b"\0")
                    if row.partition(b"\t")[2] == os.fsencode(name)
                ),
                [],
            )
            if not metadata or not metadata[0].startswith(b"100"):
                result[raw] = {"error": "not_file" if metadata else "missing"}
                continue
        source: dict[str, Any] = {"path": name}
        if raw in location_set:
            if name not in counts:
                blob = git_command(
                    target,
                    "cat-file",
                    "blob",
                    f"{revision}:{name}",
                    text=False,
                    offline=True,
                )
                blob.check_returncode()
                data = blob.stdout
                counts[name] = len(re.split(rb"\r\n|[\r\n]", data)) - int(
                    not data or data.endswith((b"\r", b"\n"))
                )
            source["lineCount"] = counts[name]
        result[raw] = source
    return result


def _update_digest_field_header(digest: Any, label: bytes, value_size: int) -> None:
    digest.update(len(label).to_bytes(4, "big"))
    digest.update(label)
    digest.update(value_size.to_bytes(8, "big"))


def update_digest_field(digest: Any, label: bytes, value: bytes) -> None:
    _update_digest_field_header(digest, label, len(value))
    digest.update(value)


def _update_regular_file_digest(digest: Any, path: Path, prefix: bytes = b"") -> None:
    """Record the file kind, byte count, and SHA-256 in the snapshot digest."""
    content = hashlib.sha256()
    size = 0
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            content.update(chunk)
            size += len(chunk)
    update_digest_field(digest, prefix + b"kind", b"file")
    update_digest_field(digest, prefix + b"size", str(size).encode())
    update_digest_field(digest, prefix + b"content-sha256", content.digest())


def _visible_git_character(char: str) -> str:
    if char in "\n\t" or unicodedata.category(char) not in {"Cc", "Cf"}:
        return char
    if ord(char) <= 0xFF:
        return f"\\x{ord(char):02x}"
    return ascii(char)[1:-1]


def _canonical_patch_chunks(output: BinaryIO) -> Iterator[bytes]:
    """Drop Git's optional function label while preserving hunk coordinates and content."""
    line_start = True
    # Limit each read even when source lines are arbitrarily large.
    for part in iter(lambda: output.readline(1024 * 1024), b""):
        next_line_start = part.endswith(b"\n")
        if line_start and part.startswith(b"@@ "):
            coordinates, end, _ = part.partition(b" @@")
            if end:
                part = coordinates + end + b"\n"
        yield part
        line_start = next_line_start


@contextmanager
def _diff_driver_config(
    target: Path, git_dir: Path | None, work_tree: Path | None
) -> Iterator[tuple[str, ...]]:
    names = git_command(
        target,
        "config",
        "--name-only",
        "--null",
        "--get-regexp",
        r"^diff\..+\.binary$",
        text=False,
        git_dir=git_dir,
        work_tree=work_tree,
        environment_overrides={"LC_ALL": "C"},
    )
    if names.returncode == 1:  # Git returns 1 when there are no matching keys.
        yield ()
        return
    if names.returncode:
        raise SystemExit(
            os.fsdecode(names.stderr) or "Could not inspect Git diff-driver configuration."
        )
    # A private command-scope include preserves case and arbitrary driver-name bytes
    # without putting an unbounded number of keys on the command line.
    with tempfile.TemporaryDirectory(prefix="codex-security-diff-") as directory:
        config = Path(directory) / "drivers"
        with config.open("wb") as stream:
            for key in names.stdout.split(b"\0"):
                if key:
                    driver = key.removeprefix(b"diff.").removesuffix(b".binary")
                    escaped = driver.replace(b"\\", b"\\\\").replace(b'"', b'\\"')
                    stream.write(b'[diff "' + escaped + b'"]\n\tbinary = auto\n')
        yield "-c", f"include.path={config}"


def _update_digest_field_from_git(
    digest: Any,
    label: bytes,
    target: Path,
    *args: str,
    git_dir: Path | None = None,
    work_tree: Path | None = None,
    environment_overrides: dict[str, str] | None = None,
    stable_display: bool = False,
) -> None:
    with tempfile.TemporaryFile() as output, ExitStack() as stack:
        driver_config = (
            stack.enter_context(_diff_driver_config(target, git_dir, work_tree))
            if stable_display
            else ()
        )
        completed = git_command(
            target,
            *driver_config,
            *args,
            text=False,
            git_dir=git_dir,
            work_tree=work_tree,
            stdout_file=output,
            environment_overrides=environment_overrides,
        )
        if completed.returncode != 0:
            detail = completed.stderr.decode("utf-8", errors="backslashreplace").replace(
                "\r\n", "\n"
            )
            detail = "".join(map(_visible_git_character, detail))
            raise SystemExit(
                f"Could not snapshot the selected working-tree changes.\n{detail}".rstrip("\n")
            )
        if stable_display:
            output.seek(0)
            value_size = sum(len(part) for part in _canonical_patch_chunks(output))
        else:
            value_size = output.seek(0, os.SEEK_END)
        _update_digest_field_header(digest, label, value_size)
        output.seek(0)
        chunks = (
            _canonical_patch_chunks(output)
            if stable_display
            else iter(lambda: output.read(1024 * 1024), b"")
        )
        for chunk in chunks:
            digest.update(chunk)


def worktree_content_digest(target: Path, *, expected_digest: str | None = None) -> str:
    """Return the worktree digest for the selected path after checking the state of its submodules."""
    require_clean_submodule_worktrees(target)
    repository, pathspec = git_worktree_context(target)
    return worktree_content_digest_for_context(
        repository, pathspec, expected_digest=expected_digest
    )


def remediation_checkout_snapshot(
    scan: sqlite3.Row,
    *,
    expected_revision: str | None = None,
    expected_digest: str | None = None,
    head_changed_message: str = (
        "Repository HEAD changed. Regenerate the remediation patch against the current checkout."
    ),
) -> tuple[str, str | None]:
    """Return the current revision and content digest after verifying the recorded checkout identity and required revision."""
    with checked_scan_target(scan) as target:
        revision = git_revision(target)
        required_revision = expected_revision or scan["target_revision"]
        if revision != required_revision:
            raise SystemExit(head_changed_message)
        content_digest = (
            worktree_content_digest(target, expected_digest=expected_digest)
            if revision != "unversioned"
            else directory_content_digest(target, excluded=(Path(scan["scan_dir"]),))
        )
        return revision, content_digest


def require_scan_target_unchanged(scan: sqlite3.Row) -> None:
    head_changed_message = "Repository HEAD changed. Run a new scan before validating its findings."
    if (
        scan["diff_target_kind"] not in {"working_tree", "commit", "range"}
        and scan["target_snapshot_digest"] is None
        and scan["mode"] != "diff"
        and scan["target_revision"] != "unversioned"
    ):
        # Legacy Git records bind only the revision, not working-tree contents.
        with checked_scan_target(scan) as target:
            if git_revision(target) != scan["target_revision"]:
                raise SystemExit(head_changed_message)
            require_clean_submodule_worktrees(target)
        return
    if scan["diff_target_kind"] == "working_tree":
        expected_digest = scan["diff_content_digest"]
    elif scan["diff_target_kind"] in {"commit", "range"}:
        expected_digest = clean_worktree_content_digest()
    else:
        expected_digest = scan["target_snapshot_digest"]
    _, current_digest = remediation_checkout_snapshot(
        scan, expected_digest=expected_digest, head_changed_message=head_changed_message
    )
    if scan["diff_target_kind"] in {"commit", "range"}:
        target = Path(scan["target_path"])
        tracked = git_bytes(target, "ls-files", "-v", "-z")
        if tracked is None:
            raise SystemExit("Could not inspect tracked files in the scan target.")
        entries = tracked.split(b"\0")
        if any(entry.startswith((b"S ", b"s ")) for entry in entries):
            raise SystemExit(
                "Committed-diff scans require a full repository checkout. "
                "Sparse checkouts are not supported; materialize skipped tracked files and retry."
            )
        if any(entry.startswith(b"h ") for entry in entries):
            verify_assumed_unchanged_files(target)
    if current_digest != expected_digest:
        raise SystemExit(
            "Scan target contents changed since the scan. "
            "Run a new scan before validating its findings."
        )


def verify_assumed_unchanged_files(target: Path) -> None:
    index = git_output(target, "rev-parse", "--path-format=absolute", "--git-path", "index")
    if index is None:
        raise SystemExit("Could not locate the Git index for the scan target.")
    with tempfile.TemporaryDirectory(prefix="codex-security-git-index-") as directory:
        # Refresh a private index without running checkout hooks or updating its shared index.
        index_copy = Path(directory) / "index"
        shutil.copyfile(index, index_copy)
        result = git_command(
            target,
            "-c",
            f"core.hooksPath={directory}",
            "-c",
            "core.splitIndex=false",
            "update-index",
            "--really-refresh",
            text=False,
            environment_overrides={"GIT_INDEX_FILE": str(index_copy)},
            # A repository's clean filter can run while Git compares working-tree bytes.
            inherit_git_environment=False,
            offline=True,
        )
    if result.returncode == 1:
        raise SystemExit(
            "A tracked file marked assume-unchanged changed since the scan. "
            "Run a new scan before validating its findings."
        )
    if result.returncode != 0:
        raise SystemExit(
            os.fsdecode(result.stderr) or "Could not refresh the scan target's Git index."
        )


def worktree_content_digest_for_context(
    repository: Path,
    pathspec: str,
    *,
    git_dir: Path | None = None,
    work_tree: Path | None = None,
    expected_digest: str | None = None,
) -> str:
    def calculate(stable_display: bool) -> str:
        return _git_content_digest(repository, pathspec, git_dir, work_tree, stable_display)

    current = calculate(True)
    # Older sealed snapshots may have included the user's Git display settings.
    if (
        expected_digest is not None
        and current != expected_digest
        and calculate(False) == expected_digest
    ):
        return expected_digest
    return current


def _git_content_digest(
    repository: Path,
    pathspec: str,
    git_dir: Path | None,
    work_tree: Path | None,
    stable_display: bool,
) -> str:
    digest = hashlib.sha256()
    update_digest_field(digest, b"format", b"codex-security-snapshot/v1")
    source_pathspecs = [
        f":(literal){pathspec}",
        ":(top,glob,exclude)**/.svn",
        ":(top,glob,exclude)**/.svn/**",
    ]
    config = (
        (
            "-c",
            "core.quotePath=true",
            "-c",
            "diff.suppressBlankEmpty=false",
            "-c",
            "core.compression=1",  # Git uses the fastest zlib level for binary patches by default.
        )
        if stable_display
        else ()
    )
    display = (
        (
            "--no-color",
            "--src-prefix=a/",
            "--dst-prefix=b/",
            "--unified=3",
            "--diff-algorithm=myers",
            "--indent-heuristic",
            "--inter-hunk-context=0",
            "--find-renames=50%",
            "-l1000",  # Git's default inexact rename limit.
            "--submodule=short",
            "-O",
            os.devnull,
        )
        if stable_display
        else ()
    )
    _update_digest_field_from_git(
        digest,
        b"tracked-diff",
        repository,
        *config,
        "--no-literal-pathspecs",
        "diff",
        *display,
        "--binary",
        "--full-index",
        "--no-ext-diff",
        "--no-textconv",
        "--ignore-submodules=none",
        "HEAD",
        "--",
        *source_pathspecs,
        git_dir=git_dir,
        work_tree=work_tree,
        # GIT_DIFF_OPTS overrides even an explicit --unified option.
        environment_overrides={"GIT_DIFF_OPTS": ""} if stable_display else None,
        stable_display=stable_display,
    )
    untracked = git_bytes(
        repository,
        "--no-literal-pathspecs",
        "ls-files",
        "--others",
        "--exclude-standard",
        "-z",
        "--",
        *source_pathspecs,
        git_dir=git_dir,
        work_tree=work_tree,
    )
    if untracked is None:
        raise SystemExit("Could not snapshot the selected working-tree changes.")
    for raw_path in sorted(path for path in untracked.split(b"\0") if path):
        relative_path = os.fsdecode(raw_path)
        path = (work_tree or repository) / relative_path
        try:
            metadata = path.lstat()
        except OSError as exc:
            raise SystemExit(f"Could not read untracked file: {relative_path}") from exc
        update_digest_field(digest, b"untracked-path", raw_path)
        update_digest_field(
            digest,
            b"untracked-mode",
            str(stat.S_IMODE(metadata.st_mode)).encode(),
        )
        if stat.S_ISLNK(metadata.st_mode):
            update_digest_field(digest, b"untracked-kind", b"symlink")
            update_digest_field(
                digest,
                b"untracked-content",
                os.fsencode(os.readlink(path)),
            )
        elif stat.S_ISDIR(metadata.st_mode):
            update_digest_field(digest, b"untracked-kind", b"directory")
            update_digest_field(
                digest,
                b"untracked-content",
                directory_content_digest(path.resolve()).encode(),
            )
        elif stat.S_ISREG(metadata.st_mode):
            try:
                _update_regular_file_digest(digest, path, prefix=b"untracked-")
            except OSError as exc:
                raise SystemExit(f"Could not read untracked file: {relative_path}") from exc
        else:
            raise SystemExit(f"Unsupported untracked file type: {relative_path}")
    return f"codex-security-snapshot/v1:sha256:{digest.hexdigest()}"


def git_worktree_context(target: Path) -> tuple[Path, str]:
    root = git_output(target, "rev-parse", "--show-toplevel")
    if root is None:
        raise SystemExit("Could not inspect the selected Git working tree.")
    repository = Path(root).resolve()
    prefix = git_bytes(target, "rev-parse", "--show-prefix")
    if prefix is None:
        raise SystemExit("Could not inspect the selected Git working tree.")
    pathspec = os.fsdecode(prefix.removesuffix(b"\n")).removesuffix("/") or "."
    scoped = (repository / pathspec).resolve()
    try:
        if not scoped.is_relative_to(repository) or not scoped.samefile(target):
            raise ValueError("Git working tree does not contain the selected target")
    except (OSError, ValueError) as exc:
        raise SystemExit("Scan target must stay inside its Git working tree.") from exc
    return repository, pathspec


def git_submodule_entries(target: Path) -> tuple[tuple[Path, str], ...]:
    repository, pathspec = git_worktree_context(target)
    staged = git_bytes(repository, "ls-files", "--stage", "-z", "--", pathspec)
    if staged is None:
        raise SystemExit("Could not inspect Git submodules in the selected working tree.")
    entries = []
    for record in (item for item in staged.split(b"\0") if item):
        try:
            metadata, raw_path = record.split(b"\t", 1)
            mode, object_id, _ = metadata.split(b" ", 2)
        except ValueError as exc:
            raise SystemExit(
                "Could not inspect Git submodules in the selected working tree."
            ) from exc
        if mode != b"160000":
            continue
        relative_path = Path(os.fsdecode(raw_path)).relative_to(pathspec)
        entries.append((target / relative_path, object_id.decode("ascii")))
    return tuple(entries)


def require_clean_submodule_worktrees(target: Path) -> None:
    for submodule, expected_revision in git_submodule_entries(target):
        relative_path = str(submodule.relative_to(target))
        if not submodule.exists():
            continue
        try:
            (submodule / ".git").lstat()
        except FileNotFoundError:
            continue
        root = git_output(submodule, "rev-parse", "--show-toplevel")
        try:
            is_initialized = root is not None and Path(root).samefile(submodule)
        except OSError:
            is_initialized = False
        if not is_initialized:
            raise SystemExit(
                f"Could not inspect initialized Git submodule contents: {relative_path}"
            )
        if git_output(submodule, "rev-parse", "HEAD") != expected_revision:
            raise SystemExit(
                "Initialized Git submodules must be checked out at the revision recorded "
                f"by the parent repository: {relative_path}"
            )
        status = git_bytes(
            submodule,
            "status",
            "--porcelain=v1",
            "-z",
            "--untracked-files=all",
            "--ignore-submodules=none",
        )
        if status is None:
            raise SystemExit(f"Could not inspect Git submodule contents: {relative_path}")
        if status:
            raise SystemExit(
                f"Dirty Git submodules are not supported for remediation integrity checks: {relative_path}"
            )
        require_clean_submodule_worktrees(submodule)


def clean_worktree_content_digest() -> str:
    digest = hashlib.sha256()
    update_digest_field(digest, b"format", b"codex-security-snapshot/v1")
    update_digest_field(digest, b"tracked-diff", b"")
    return f"codex-security-snapshot/v1:sha256:{digest.hexdigest()}"


def _directory_link_boundary(target: Path, path: Path, linked_prefixes: dict[str, bool]) -> Path:
    # The index can retain descendants of a directory replaced by a link.
    # Keep the link's identity in snapshots without following its contents.
    prefix = target
    for component in path.relative_to(target).parts[:-1]:
        prefix /= component
        key = str(prefix)
        if key not in linked_prefixes:
            metadata = prefix.lstat()
            linked_prefixes[key] = bool(
                stat.S_ISLNK(metadata.st_mode)
                or getattr(metadata, "st_reparse_tag", 0) & 0x20000000
            )
        if linked_prefixes[key]:
            return prefix
    return path


def _windows_inventory_query(
    target: Path,
    *args: str,
    git_dir: Path,
    work_tree: Path,
    input_data: bytes | None = None,
    environment_overrides: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[bytes]:
    """Retry an inventory's metadata length error with its verified worktree marker."""

    def query(
        directory: Path, environment: dict[str, str] | None
    ) -> subprocess.CompletedProcess[bytes]:
        return cast(
            subprocess.CompletedProcess[bytes],
            git_command(
                target,
                *args,
                text=False,
                git_dir=directory,
                work_tree=work_tree,
                input_data=input_data,
                environment_overrides=environment,
            ),
        )

    result = query(git_dir, environment_overrides)
    if (
        result.returncode != 128
        or result.stdout
        or not target.is_relative_to(work_tree)
        or b"GIT_DIR" not in result.stderr
    ):
        return result
    diagnostic = b"fatal: '$GIT_DIR' too big"
    if diagnostic not in result.stderr.splitlines():
        # Confirm translated diagnostics without changing the actual inventory's environment.
        probe = query(git_dir, {**(environment_overrides or {}), "LC_ALL": "C", "LANGUAGE": "C"})
        if probe.returncode != 128 or probe.stdout or diagnostic not in probe.stderr.splitlines():
            return result
    with pinned_root_git_marker(target, git_dir, work_tree=work_tree) as marker:
        if marker is not None:
            retry = query(marker, environment_overrides)
            if retry.returncode == 0 or (retry.returncode == 1 and "check-ignore" in args):
                return retry
    return result


def git_directory_snapshot_paths(
    target: Path, *, replay_git_dir: Path | None = None
) -> list[Path] | None:
    if replay_git_dir is None:
        if git_output(target, "rev-parse", "--show-toplevel") is None:
            return None
        repository, pathspec = git_worktree_context(target)
    else:
        # The temporary copy of an unborn repository uses the selected Git config and index.
        repository, pathspec = target, "."
    scope = repository / pathspec
    scope_depth = len(Path(pathspec).parts)
    matching_prefixes: dict[str, bool] = {}
    linked_prefixes: dict[str, bool] = {}
    listing_args: list[str] = []
    inventory_pathspec = pathspec
    if scope_depth:
        if any(
            not character.isascii() and character.lower() != character.upper()
            for character in pathspec
        ):
            # Git's icase pathspecs do not cover Unicode case aliases.
            inventory_pathspec = "."
        else:
            listing_args.append("--no-literal-pathspecs")
            inventory_pathspec = f":(icase,literal){pathspec}"
    listed = git_bytes(
        repository,
        *listing_args,
        "ls-files",
        "--cached",
        "--others",
        "--exclude-standard",
        "-t",
        "-z",
        "--",
        inventory_pathspec,
        git_dir=replay_git_dir,
        work_tree=repository if replay_git_dir else None,
    )
    if listed is None:
        raise SystemExit("Could not inspect files in the selected Git working tree.")
    paths: list[Path] = []
    junctions: dict[tuple[int, int], Path] = {}
    nested_worktrees: set[tuple[int, int]] = set()
    for entry in (entry for entry in listed.split(b"\0") if entry):
        relative = Path(os.fsdecode(entry[2:]))
        if not SOURCE_METADATA_DIRECTORIES.isdisjoint(relative.parts):
            continue
        if scope_depth:
            if len(relative.parts) <= scope_depth:
                continue
            # Git's index spelling can differ after a case-only directory rename.
            # Compare each scope-depth prefix once, without following symlink leaves.
            prefix = repository.joinpath(*relative.parts[:scope_depth])
            key = str(prefix)
            if key not in matching_prefixes:
                try:
                    matching_prefixes[key] = prefix.samefile(scope)
                except (FileNotFoundError, NotADirectoryError):
                    matching_prefixes[key] = False
            # realpath spelling is not a filesystem identity on case-insensitive
            # POSIX volumes; WindowsPath equality also folds distinct names.
            if not matching_prefixes[key]:
                continue
        path = target.joinpath(*relative.parts[scope_depth:])
        try:
            path = _directory_link_boundary(target, path, linked_prefixes)
            metadata = path.lstat()
        except (FileNotFoundError, NotADirectoryError):
            # The index can retain deleted paths, including directory-to-file replacements.
            continue
        if getattr(metadata, "st_reparse_tag", 0) & 0x20000000:
            # Case aliases share the link's identity. Prefer the stable index
            # spelling over untracked descendants added in its external target.
            identity = metadata.st_dev, metadata.st_ino
            if entry[:1] != b"?" or identity not in junctions:
                junctions[identity] = path
            continue
        paths.append(path)
        if (
            not stat.S_ISDIR(metadata.st_mode)
            or getattr(metadata, "st_reparse_tag", 0) & 0x20000000
        ):
            continue
        nested_repository_root = git_output(path, "rev-parse", "--show-toplevel")
        if nested_repository_root is not None and Path(nested_repository_root).samefile(path):
            nested_paths = git_directory_snapshot_paths(path)
            if nested_paths is not None:
                nested_worktrees.add((metadata.st_dev, metadata.st_ino))
                paths.extend(nested_paths)
                continue
        paths.extend(source_directory_snapshot_paths(path))

    if _WINDOWS:
        # Git omits empty untracked directories from its file listing. Inventory
        # junction identities independently of whether their targets contain files.
        git_directory = replay_git_dir or git_output(target, "rev-parse", "--absolute-git-dir")
        if git_directory is None:
            raise SystemExit("Could not inspect the selected Git working tree.")
        directories = _windows_inventory_query(
            target,
            "--no-literal-pathspecs",
            "ls-files",
            "--others",
            "--directory",
            "--exclude-standard",
            "-z",
            "--",
            # Seed only eligible descendants, never the selected directory itself.
            ":(glob)**/*/",
            git_dir=Path(git_directory),
            work_tree=repository,
        )
        if directories.returncode != 0:
            raise SystemExit("Could not inspect directories in the selected Git working tree.")
        pending = [target / os.fsdecode(path) for path in directories.stdout.split(b"\0") if path]
        while pending:
            children: list[Path] = []
            for path in pending:
                if not SOURCE_METADATA_DIRECTORIES.isdisjoint(path.relative_to(target).parts):
                    continue
                try:
                    path = _directory_link_boundary(target, path, linked_prefixes)
                    metadata = path.lstat()
                except (FileNotFoundError, NotADirectoryError):
                    continue
                if getattr(metadata, "st_reparse_tag", 0) & 0x20000000:
                    junctions.setdefault((metadata.st_dev, metadata.st_ino), path)
                elif stat.S_ISLNK(metadata.st_mode):
                    paths.append(path)
                elif stat.S_ISDIR(metadata.st_mode):
                    if (metadata.st_dev, metadata.st_ino) in nested_worktrees:
                        # Its own inventory already applied its repository exclusions.
                        continue
                    try:
                        children.extend(path.iterdir())
                    except PermissionError:
                        # Match Git's treatment of unreadable descendants.
                        continue
            candidates: dict[bytes, Path] = {}
            for path in children:
                if os.path.normcase(path.name) in SOURCE_METADATA_DIRECTORIES:
                    continue
                try:
                    metadata = path.lstat()
                except (FileNotFoundError, NotADirectoryError, PermissionError):
                    continue
                if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode)):
                    continue
                relative = (Path(pathspec) / path.relative_to(target)).as_posix()
                candidates[os.fsencode(relative)] = path
            if not candidates:
                break
            # Filter a directory level at once, retaining the outer repository context.
            ignored = _windows_inventory_query(
                repository,
                "--no-literal-pathspecs",
                "check-ignore",
                "-z",
                "--stdin",
                input_data=b"\0".join(candidates) + b"\0",
                git_dir=Path(git_directory),
                work_tree=repository,
                environment_overrides={
                    "GIT_NOGLOB_PATHSPECS": "0",
                },
            )
            if ignored.returncode not in (0, 1):
                raise SystemExit("Could not inspect directories in the selected Git working tree.")
            excluded = set(ignored.stdout.split(b"\0"))
            pending = [path for raw, path in candidates.items() if raw not in excluded]
    paths.extend(junctions.values())
    return sorted({str(path): path for path in paths}.values(), key=str)


def source_directory_snapshot_paths(
    target: Path,
    excluded: tuple[Path, ...] = (),
    *,
    include_git_metadata: bool = False,
    onerror: Callable[[OSError], None] | None = None,
) -> list[Path]:
    paths: list[Path] = []
    for directory, directories, files in os.walk(
        target, topdown=True, followlinks=False, onerror=onerror
    ):
        parent = Path(directory)
        for name in directories[:]:
            path = parent / name
            if (
                name in SOURCE_METADATA_DIRECTORIES and not include_git_metadata
            ) or path in excluded:
                directories.remove(name)
                continue
            paths.append(path)
            # Name-surrogate reparse points include Windows directory junctions.
            if getattr(path.lstat(), "st_reparse_tag", 0) & 0x20000000:
                directories.remove(name)
        paths.extend(
            parent / name
            for name in files
            if (name not in SOURCE_METADATA_DIRECTORIES or include_git_metadata)
            and parent / name not in excluded
        )
    return sorted(paths)


def directory_content_digest(
    target: Path,
    *,
    excluded: tuple[Path, ...] = (),
    include_ignored: bool = False,
    include_git_metadata: bool = False,
    replay_git_dir: Path | None = None,
) -> str:
    def raise_walk_error(error: OSError) -> None:
        raise error

    excluded_relative = [
        path.relative_to(target) for path in excluded if path.is_relative_to(target)
    ]
    paths = (
        source_directory_snapshot_paths(
            target, excluded, include_git_metadata=include_git_metadata, onerror=raise_walk_error
        )
        if include_ignored
        else git_directory_snapshot_paths(target, replay_git_dir=replay_git_dir)
    )
    if paths is None:
        paths = source_directory_snapshot_paths(target, excluded)
    digest = hashlib.sha256()
    update_digest_field(digest, b"format", b"codex-security-directory/v1")
    for path in paths:
        relative_path = path.relative_to(target)
        if any(relative_path.is_relative_to(path) for path in excluded_relative):
            continue
        try:
            metadata = path.lstat()
        except OSError as exc:
            raise UnreadableLocalFile(f"Could not read local file: {relative_path}") from exc
        mode = metadata.st_mode
        link_target = (
            os.readlink(path)
            if stat.S_ISLNK(mode) or getattr(metadata, "st_reparse_tag", 0) & 0x20000000
            else None
        )
        raw_path = os.fsencode(relative_path.as_posix())
        update_digest_field(digest, b"path", raw_path)
        update_digest_field(digest, b"mode", str(stat.S_IMODE(mode)).encode())
        if link_target is not None:
            update_digest_field(digest, b"kind", b"symlink")
            update_digest_field(digest, b"content", os.fsencode(link_target))
        elif stat.S_ISDIR(mode):
            update_digest_field(digest, b"kind", b"directory")
        elif stat.S_ISREG(mode):
            try:
                _update_regular_file_digest(digest, path)
            except OSError as exc:
                raise UnreadableLocalFile(f"Could not read local file: {relative_path}") from exc
        else:
            raise UnsupportedLocalFileType(f"Unsupported local file type: {relative_path}")
    return f"codex-security-snapshot/v1:sha256:{digest.hexdigest()}"


def directory_snapshot_regular_files(target: Path) -> Iterator[Path]:
    paths = git_directory_snapshot_paths(target)
    if paths is None:
        paths = source_directory_snapshot_paths(target)
    for path in paths:
        try:
            metadata = path.lstat()
        except OSError as exc:
            raise SystemExit(f"Could not inspect local file: {path.relative_to(target)}") from exc
        if stat.S_ISREG(metadata.st_mode):
            yield path


def directory_snapshot_regular_file_count(target: Path) -> int:
    return sum(1 for _ in directory_snapshot_regular_files(target))


def scoped_regular_file_count(repository: Path, scopes: list[str]) -> int:
    # Count directory entries once while retaining explicitly requested ignored files.
    names: set[str] = set()
    for scope in scopes:
        selected = (repository / scope).resolve(strict=True)
        if not selected.is_relative_to(repository):
            raise SystemExit("Requested scope must be inside the repository.")
        if not SOURCE_METADATA_DIRECTORIES.isdisjoint(selected.relative_to(repository).parts):
            continue
        if selected.is_file():
            names.add(selected.as_posix())
        elif selected.is_dir():
            names.update(path.as_posix() for path in directory_snapshot_regular_files(selected))
    return len(names)


def copy_directory_excluding(
    source: Path, destination: Path, excluded: tuple[Path, ...]
) -> list[Path]:
    excluded_relative = [
        path.relative_to(source) for path in excluded if path.is_relative_to(source)
    ]

    junctions: list[Path] = []

    def ignored(directory: str, names: list[str]) -> list[str]:
        relative = Path(directory).relative_to(source)
        skipped = [
            path.name
            for path in excluded_relative
            if path.parent == relative and path.name in names
        ]
        for name in names:
            if name in skipped:
                continue
            path = Path(directory) / name
            metadata = path.lstat()
            if (
                stat.S_ISDIR(metadata.st_mode)
                and getattr(metadata, "st_reparse_tag", 0) & 0x20000000
            ):
                junctions.append(relative / name)
                skipped.append(name)
        return skipped

    shutil.copytree(source, destination, symlinks=True, ignore=ignored)

    # Empty placeholders retain parent directories while a patch is reversed.
    for path in junctions:
        (destination / path).mkdir()
    return junctions


def restore_directory_junctions(source: Path, destination: Path, junctions: list[Path]) -> None:
    # Recreate links only after patch application can no longer write through them.
    destination = destination.resolve()
    for path in junctions:
        placeholder = require_remediation_target(str(destination / path))
        os.chmod(placeholder, stat.S_IMODE((source / path).lstat().st_mode))
        copy_directory_junction(source / path, placeholder)


def copy_git_worktree_files(
    source: Path, destination: Path, excluded: tuple[Path, ...]
) -> tuple[Path, list[Path]]:
    repository, pathspec = git_worktree_context(source)
    listed = git_bytes(
        repository,
        "ls-files",
        "--cached",
        "--others",
        "--exclude-standard",
        "-z",
        "--",
        pathspec,
    )
    if listed is None:
        raise SystemExit("Could not inspect files in the selected Git working tree.")
    excluded_relative = []
    for path in excluded:
        try:
            relative_path = path.relative_to(repository)
        except ValueError:
            try:
                relative_path = Path(pathspec) / path.relative_to(source)
            except ValueError:
                continue
        excluded_relative.append(relative_path)
    destination.mkdir()
    junctions: set[Path] = set()
    nested_worktrees: list[Path] = []
    linked_prefixes: dict[str, bool] = {}
    copied: set[Path] = set()
    for raw_path in sorted(path for path in listed.split(b"\0") if path):
        relative = Path(os.fsdecode(raw_path))
        if any(relative.is_relative_to(path) for path in excluded_relative):
            continue
        source_path = repository / relative
        try:
            source_path = _directory_link_boundary(repository, source_path, linked_prefixes)
            relative = source_path.relative_to(repository)
            metadata = source_path.lstat()
        except (FileNotFoundError, NotADirectoryError):
            continue
        if relative in copied:
            continue
        copied.add(relative)
        if stat.S_ISDIR(metadata.st_mode) and getattr(metadata, "st_reparse_tag", 0) & 0x20000000:
            junctions.add(relative)
            continue
        destination_path = destination / relative
        destination_path.parent.mkdir(parents=True, exist_ok=True)
        if stat.S_ISLNK(metadata.st_mode):
            directory_link = bool(
                getattr(metadata, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_DIRECTORY
            )
            destination_path.symlink_to(
                os.readlink(source_path), target_is_directory=directory_link
            )
        elif stat.S_ISREG(metadata.st_mode):
            shutil.copy2(source_path, destination_path, follow_symlinks=False)
        elif stat.S_ISDIR(metadata.st_mode):
            nested_git_dir = git_output(source_path, "rev-parse", "--absolute-git-dir")
            if nested_git_dir is None:
                raise SystemExit(f"Could not inspect nested Git working tree: {relative}")
            _, nested_junctions = copy_git_worktree_files(source_path, destination_path, excluded)
            junctions.update(relative / path for path in nested_junctions)
            nested_worktrees.append(relative)
            (destination_path / ".git").write_text(f"gitdir: {nested_git_dir}\n", encoding="utf-8")
        else:
            raise SystemExit(f"Unsupported Git working-tree file type: {relative}")
    if _WINDOWS:
        for path in git_directory_snapshot_paths(source) or []:
            relative = Path(pathspec) / path.relative_to(source)
            if any(
                relative.is_relative_to(root) for root in [*excluded_relative, *nested_worktrees]
            ):
                continue
            metadata = path.lstat()
            if (
                stat.S_ISDIR(metadata.st_mode)
                and getattr(metadata, "st_reparse_tag", 0) & 0x20000000
            ):
                junctions.add(relative)
    for path in junctions:
        (destination / path).mkdir(parents=True, exist_ok=True)
    copied_target = destination if pathspec == "." else destination / pathspec
    copied_target.mkdir(parents=True, exist_ok=True)
    return copied_target, sorted(junctions)


def git_revision(target: Path) -> str:
    return git_output(target, "rev-parse", "HEAD") or "unversioned"


def git_target_metadata(target: Path) -> dict[str, Any]:
    is_git = git_output(target, "rev-parse", "--git-dir") is not None
    is_worktree = git_output(target, "rev-parse", "--is-inside-work-tree") == "true"
    revision = git_output(target, "rev-parse", "--verify", "HEAD")
    repository_root = git_output(target, "rev-parse", "--show-toplevel") if is_worktree else None
    supported = (
        is_git
        and is_worktree
        and revision is not None
        and repository_root is not None
        and Path(repository_root).samefile(target)
    )
    metadata: dict[str, Any] = {
        "hasHead": revision is not None,
        "isGit": is_git,
        "isWorktree": is_worktree,
        "reviewChangesSupported": supported,
    }
    if not is_git:
        return metadata
    branch = git_output(target, "symbolic-ref", "--quiet", "--short", "HEAD")
    metadata.update({"branch": branch, "detachedHead": revision is not None and branch is None})
    if revision is not None:
        subject = git_bytes(
            target,
            "log",
            "-1",
            "--no-patch",
            "--no-show-signature",
            "--format=%s",
            "HEAD",
            offline=True,
        )
        metadata.update(
            {
                "commitSubject": (subject or b"").decode("utf-8", errors="replace").strip() or None,
                "revision": revision,
                "shortRevision": revision[:7],
            }
        )
    return metadata


def require_remediation_target(value: str) -> Path:
    stored = Path(value).expanduser()
    if not stored.is_absolute():
        raise SystemExit("Remediation target must be an absolute local directory path.")
    try:
        resolved = stored.resolve(strict=True)
    except NotADirectoryError:
        # A component of the recorded checkout path now names a non-directory.
        resolved = None
    except OSError as exc:
        raise SystemExit(
            "Remediation is unavailable because the selected checkout is no longer accessible."
        ) from exc
    if resolved != stored or not stored.is_dir():
        raise SystemExit(
            "Remediation is unavailable because the selected checkout path was replaced. Start a new scan."
        )
    return stored


@contextmanager
def verified_windows_checkout(
    scan: sqlite3.Row, target: Path, *, replaced_message: str
) -> Iterator[None]:
    """Bind a Windows Deep checkout for the full operation, including legacy stat-width changes."""
    from windows_scan_local_files import pinned_resume_checkout

    binding = scan["windows_resume_target_identity"]
    stored = (scan["target_device"], scan["target_inode"])
    if binding is None:

        def stat_identity() -> tuple[int | str, int | str]:
            try:
                metadata = target.stat()
            except OSError as exc:
                raise SystemExit(f"Cannot verify the original Windows checkout: {exc}") from exc
            return serialize_filesystem_identity(metadata.st_dev), serialize_filesystem_identity(
                metadata.st_ino
            )

        if stat_identity() == stored:
            yield
            if stat_identity() != stored:
                raise SystemExit(replaced_message)
            return

    with pinned_resume_checkout(target) as native:
        if binding is not None:
            if native is None:
                raise SystemExit("Cannot verify the original Windows checkout identity.")
            if list(native) != json.loads(binding):
                raise SystemExit(replaced_message)
        # Legacy stat returned at most a 32-bit volume and 64-bit file index.
        elif (
            native is None
            or (native[0] < 1 << 32 and native[1] < 1 << 64)
            or tuple(map(serialize_filesystem_identity, native)) != stored
        ):
            raise SystemExit(
                "Cannot verify the saved Windows checkout identity with this Python runtime. "
                "Use its original Python runtime or start a new scan with "
                f"'codex-security scans rerun {scan['id']}'."
            )
        yield


@contextmanager
def checked_scan_target(scan: sqlite3.Row) -> Iterator[Path]:
    """Keep any recorded Windows checkout binding intact while a caller reads the target."""
    target = require_remediation_target(scan["target_path"])
    replaced = "Remediation is unavailable because the selected checkout path was replaced. Start a new scan."
    if (
        os.name == "nt"
        and "windows_resume_target_identity" in scan.keys()
        and (
            scan["windows_resume_target_identity"] is not None
            or (
                scan["mode"] == "deep"
                and scan["launch_kind"] == "scan"
                and scan["recipe_json"] is not None
            )
        )
    ):
        with ExitStack() as pins:
            try:
                pins.enter_context(
                    verified_windows_checkout(scan, target, replaced_message=replaced)
                )
            except OSError as exc:
                raise SystemExit(f"Cannot verify the original Windows checkout: {exc}") from exc
            yield target
        return
    expected_inode = scan["target_inode"]
    if expected_inode is None:
        raise SystemExit(
            "Remediation is unavailable because this scan does not record checkout identity. "
            "Start a new scan."
        )
    try:
        metadata = target.stat()
    except OSError as exc:
        raise SystemExit(
            "Remediation is unavailable because the selected checkout is no longer accessible."
        ) from exc
    if not stored_filesystem_identity_matches(expected_inode, metadata.st_ino):
        raise SystemExit(replaced)
    yield target


def require_scan_target_identity(scan: sqlite3.Row) -> Path:
    """Return the recorded checkout path after checking its filesystem identity."""
    with checked_scan_target(scan) as target:
        return target


def require_git_worktree_head(target: Path) -> str:
    metadata = git_target_metadata(target)
    if not metadata["isGit"] or not metadata["isWorktree"] or not metadata["hasHead"]:
        raise SystemExit("Review changes requires a non-bare Git worktree with a resolvable HEAD.")
    return str(metadata["revision"])


def scan_target_warning(scan: sqlite3.Row) -> str | None:
    if scan["diff_target_kind"] != "working_tree" and not scan["target_snapshot_digest"]:
        return None
    try:
        with checked_scan_target(scan) as target:
            if scan["target_revision"] == "unversioned":
                if (
                    directory_content_digest(target, excluded=(Path(scan["scan_dir"]),))
                    != scan["target_snapshot_digest"]
                ):
                    return (
                        "Directory contents changed while the scan was running; "
                        "results were saved for the original snapshot."
                    )
                return None
            if git_revision(target) == "unversioned":
                return (
                    "The scanned Git repository became unavailable while the scan was running; "
                    "results were saved for the original revision."
                )
            working_tree = scan["diff_target_kind"] == "working_tree"
            expected_head = scan["diff_head_revision"] if working_tree else scan["target_revision"]
            if require_git_worktree_head(target) != expected_head:
                return (
                    "Repository HEAD changed while the scan was running; "
                    "results were saved for the original revision."
                )
            expected_digest = (
                scan["diff_content_digest"] if working_tree else scan["target_snapshot_digest"]
            )
            if worktree_content_digest(target, expected_digest=expected_digest) != expected_digest:
                return (
                    "Working-tree contents changed while the scan was running; "
                    "results were saved for the original snapshot."
                )
    except (OSError, SystemExit) as error:
        return (
            f"Could not verify the scan target after scanning: {error}; "
            "results were saved for the original revision or snapshot."
        )
    return None


if __name__ == "__main__":
    argparse.ArgumentParser(description=__doc__).parse_args()

SHA-256: ccefc18e546174426276f99f9ea09e1f55eaa533a77e652185391bf1bffa3a1c