Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

41.8 KB
Raw Blame
"""Declarative merge-gate policy: loader, resolver, and prompt sanitizer.

The engine's deny/allow/size/tier data lives in the shipped `defaults/policy.yml`,
the repository's own `.stamphog/policy.yml` merged onto it (global, trusted), and
optional per-folder `AGENT_APPROVALS.md` overrides (untrusted, positive
allow-list). This module merges and validates the global policy, resolves the
effective policy for a given set of changed files, and owns the untrusted-text
sanitizer shared with the reviewer prompt.

Security posture (see .stamphog/README.md):
- All files are read from the checked-out working tree - the repo root is
  resolved from this module's own location, never from cwd. In CI the workflow
  checks out `ref: master`, so the working tree IS the trusted ref.
- A malformed global policy hard-fails at load (fail closed - the tool crashes
  rather than approving with a half-loaded policy).
- Folder overrides are a positive allow-list: only explicitly delegated keys
  are read, within contract ceilings. Every AGENT_APPROVALS.md at or above a
  changed file governs it - guidance accumulates and a child file refines its
  ancestors rather than replacing them. An invalid folder file contributes
  nothing itself (frontmatter and prose ignored) but does not cancel its
  ancestors; files with no valid grant on their chain fall to the global pool.
- Folder prose is untrusted advisory text: sanitized and length-capped before
  it reaches the reviewer prompt, where it sits inside the untrusted region.
"""

import os
import re
import functools
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from typing import Any

import yaml

# ── Untrusted-text sanitizer (shared with reviewer.py) ───────────

# Strip only invisible characters - the prompt-smuggling vectors: C0/C1
# controls, bidi overrides, zero-width chars, and the Unicode tags block
# (invisible ASCII). Visible unicode must survive: reviewer bots express
# verdicts as 👍/👀 in review bodies, and stripping emoji garbles those
# into text that reads like tampering on the next run. ZWJ is stripped
# with the other zero-width chars (it interleaves invisibly into words);
# composite emoji degrade to their visible components, which stays readable.
_INVISIBLE_CHARS_RE = re.compile(
    "[\x00-\x08\x0b-\x1f\x7f-\x9f"  # C0/C1 controls and DEL (keep \t \n)
    "\u061c"  # Arabic letter mark (bidi)
    "\u200b-\u200f"  # zero-width space/joiners, LRM/RLM
    "\u2028\u2029"  # line/paragraph separators
    "\u202a-\u202e\u2066-\u2069"  # bidi embedding/override/isolate controls
    "\u2060\ufeff"  # word joiner, BOM
    "\U000e0000-\U000e007f]"  # tags block - invisible ASCII smuggling
)


def _sanitize_untrusted(text: str, max_len: int = 200) -> str:
    """Strip invisible/control chars and cap length; visible unicode passes through."""
    return _INVISIBLE_CHARS_RE.sub("", text)[:max_len]


# ── Repo-root resolution ─────────────────────────────────────────


@functools.lru_cache(maxsize=1)
def repo_root() -> Path:
    """Locate the repo root by walking up from this module's own location.

    Deterministic and cwd-independent: the policy files must be read from the
    same checked-out tree as this script, never from wherever the process runs.
    The single resolver for the whole tool; cached, the tree never moves
    mid-process.

    A hosted run names the checkout in STAMPHOG_REPO_ROOT. The checkout is the
    untrusted PR head, so a `.stamphog/` that the PR adds between the checkout
    root and the engine would otherwise become the root.
    """
    explicit_root = os.environ.get("STAMPHOG_REPO_ROOT")
    if explicit_root:
        return Path(explicit_root).resolve()
    here = Path(__file__).resolve().parent
    for parent in [here, *here.parents]:
        if (parent / ".stamphog").is_dir() or (parent / ".git").exists():
            return parent
    raise RuntimeError("Cannot locate repo root (no .stamphog/ or .git found above policy.py)")


def bundled_defaults_dir() -> Path:
    """The shipped defaults beside this module, which the server copies into the sandbox with the engine."""
    return Path(__file__).resolve().parent / "defaults"


def repo_policy_path() -> Path:
    return repo_root() / ".stamphog" / "policy.yml"


def review_guidance_path() -> Path:
    """The repository's own guidance, which replaces the shipped default whole, or the shipped default."""
    repo_guidance = repo_root() / ".stamphog" / "review-guidance.md"
    return repo_guidance if repo_guidance.is_file() else bundled_defaults_dir() / "review-guidance.md"


def steering_path() -> Path:
    return repo_root() / ".stamphog" / "steering.md"


# ── Policy data structures ───────────────────────────────────────


@dataclass(frozen=True)
class DenyCategory:
    description: str
    rationale: str
    # Only the scopes present in the policy file, preserving pattern order.
    # Scope keys are a subset of {"any", "titles", "paths"}.
    match: dict[str, tuple[str, ...]]
    exempt_author_teams: tuple[str, ...] = ()


@dataclass(frozen=True, kw_only=True)
class DenyException:
    keyword: str | None
    path_prefixes: tuple[str, ...]
    extensions: tuple[str, ...]


@dataclass(frozen=True)
class SizeGate:
    max_lines: int
    max_files: int


@dataclass(frozen=True)
class T1Subclass:
    max_lines: int
    max_files: int
    # "single-area" (exact match) or "not-cross-cutting" (anything but cross-cutting).
    breadth: str


@dataclass(frozen=True)
class OverrideContract:
    ceiling: int


@dataclass(frozen=True)
class FamiliarityStrong:
    # STRONG = blame overlap ≥ threshold. Deliberately the only criterion: the
    # Jul 2026 backtest found blame overlap the sole monotonic predictor of
    # human rubber-stamps; composite path/recency rules measured nothing.
    min_blame_overlap_pct: float


@dataclass(frozen=True)
class FamiliarityModerate:
    # MODERATE = both satisfied.
    min_prior_prs: int
    max_days_since_touch: int


@dataclass(frozen=True)
class FamiliarityPolicy:
    """Band thresholds for the author-familiarity signal (judgment layer only).

    Non-delegable by construction - absent from the `overrides` contract, so a
    folder file can never grant or tune it.
    """

    strong: FamiliarityStrong
    moderate: FamiliarityModerate


@dataclass(frozen=True)
class OwnershipSource:
    """One ownership-context source: a format plus exactly one locator.

    `format` names an entry in gates.OWNERSHIP_FORMATS; exactly one of `path`
    (a single file) or `glob` (a repo-root glob) is set, dictated by that
    entry's declared locator. Both locators stay repo-relative - the loader
    rejects absolute paths and any `..` escape.
    """

    format: str
    path: str | None = None
    glob: str | None = None


@dataclass(frozen=True)
class Policy:
    version: int
    deny: dict[str, DenyCategory]
    allow_path_patterns: tuple[str, ...]
    allow_extensions: frozenset[str]
    size_gate: SizeGate
    t1_subclasses: dict[str, T1Subclass]
    overrides: dict[str, OverrideContract]
    familiarity: FamiliarityPolicy
    ownership: tuple[OwnershipSource, ...]
    deny_exceptions: dict[str, tuple[DenyException, ...]] = field(default_factory=dict)

    def deny_pattern_defs(self) -> dict[str, dict[str, list[str]]]:
        """Reconstruct the raw scope→patterns mapping the compiler consumes."""
        return {
            category: {scope: list(pats) for scope, pats in cat.match.items()} for category, cat in self.deny.items()
        }


@dataclass(frozen=True)
class ScopeBudget:
    """One size-gate ceiling and the files it governs.

    `path` is the nearest AGENT_APPROVALS.md granting that ceiling (repo-relative);
    None is the global pool, which absorbs every file whose chain grants that
    ceiling nowhere, so splitting files across pseudo-scopes can never inflate
    the allowance.
    """

    path: str | None
    ceiling: int
    files: tuple[str, ...]


@dataclass(frozen=True)
class EffectivePolicy:
    """Per-PR resolved policy: per-scope size budgets plus advisory prose.

    Mixed PRs get mixed leniency: every AGENT_APPROVALS.md at or above a changed
    file governs it, and each ceiling resolves on its own - a file is budgeted by
    the nearest folder on its chain granting that ceiling, and by the global pool
    when no folder on the chain grants it. Lines and files therefore partition
    independently, so a folder that raises one ceiling never opens a second
    budget for the other. No file ever gets more leniency than its own chain
    grants.

    Per-scope budgets alone would let a PR's total grow with the number of
    scopes it touches, so each ceiling also carries a roof over the whole PR.
    """

    file_scopes: tuple[ScopeBudget, ...]
    line_scopes: tuple[ScopeBudget, ...]
    folder_prose: str | None = None
    invalid_folder_files: tuple[str, ...] = ()

    @property
    def line_roof(self) -> int:
        """Whole-PR substantive line ceiling: the most generous one in play.

        Every grant is validated at or under the delegation ceiling, the global
        pool is always a scope, and the loader rejects a ceiling under its own
        global default, so the roof stays between the global default and that
        ceiling. With no grant in play it equals the global default, which is
        the single global total the gate had before ceilings became delegable.
        """
        return max(scope.ceiling for scope in self.line_scopes)

    @property
    def file_roof(self) -> int:
        """Whole-PR substantive file ceiling. See `line_roof`."""
        return max(scope.ceiling for scope in self.file_scopes)

    def governed_file_counts(self) -> tuple[tuple[str, int], ...]:
        """Changed files each granting AGENT_APPROVALS.md governs, path-sorted.

        A folder can govern a file's line ceiling, its file ceiling, or both, so
        each file counts once per folder.
        """
        governed: dict[str, set[str]] = {}
        for scope in (*self.file_scopes, *self.line_scopes):
            if scope.path is not None:
                governed.setdefault(scope.path, set()).update(scope.files)
        return tuple((path, len(files)) for path, files in sorted(governed.items()))


class PolicyError(ValueError):
    """Raised when the global policy is malformed - fail closed at load time."""


# ── Global policy loading + validation ───────────────────────────

_TOP_LEVEL_KEYS = {"version", "deny", "allow", "size_gate", "tiers", "overrides", "familiarity", "ownership"}
# Keys that the hosted server owns and parses itself, and that the engine does not. The top level
# allows them, so a repo that declares one does not hard-fail every review. They are never required,
# and the engine never reads their contents. `digest` is read by logic/digest_config.py. `dismiss`
# is tolerated for policies that still declare it, and nothing reads it: the server decides whether
# a push may retain a standing approval (logic/approval_retention.py). A repo that could widen those
# rules could keep an approval standing across arbitrary code pushes.
_SERVER_ONLY_TOP_LEVEL_KEYS = {"digest", "dismiss"}
_OPTIONAL_TOP_LEVEL_KEYS = {"deny_exceptions"}
_DENY_SCOPES = {"any", "titles", "paths"}
_BREADTH_RULES = {"single-area", "not-cross-cutting"}

# The delegation contract's delegable keys. Everything else (deny, allow, tiers)
# is non-delegable by construction.
_DELEGABLE_KEYS = {"size_gate.max_files", "size_gate.max_lines"}
_SIZE_GATE_DELEGATIONS = {"max_files": "size_gate.max_files", "max_lines": "size_gate.max_lines"}

# Invariant 7: self-governance deny must cover these path families so a future
# policy edit cannot silently drop stamphog's protection of its own files.
# The engine token is location-agnostic on purpose: this repo keeps the engine under the stamphog
# product while vendored copies keep it under tools/, and both must stay self-governed.
_SELF_GOVERNANCE_REQUIRED = (".stamphog/", "AGENT_APPROVALS", "pr-approval-agent/")


def _require(condition: bool, message: str) -> None:
    if not condition:
        raise PolicyError(message)


def _compile_or_raise(pattern: str, context: str) -> None:
    try:
        re.compile(pattern)
    except re.error as exc:
        raise PolicyError(f"{context}: pattern {pattern!r} does not compile: {exc}") from exc


_TEAM_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
_DENY_EXCEPTION_KEYS = {"keyword", "path_prefixes", "extensions"}
_LITERAL_KEYWORD_RE = re.compile(r"[A-Za-z0-9_-]+")
_DENY_EXCEPTION_METACHARS_RE = re.compile(r"[\\*?\[\]{}()+|^$\x00-\x1f\x7f-\x9f]")


def _parse_exempt_author_teams(category: str, raw: Any) -> tuple[str, ...]:
    context = f"deny.{category}.exempt_author_teams"
    _require(isinstance(raw, list), f"{context}: must be a list")
    # A team that may approve edits to the policy could widen its own exemption.
    _require(not (raw and category == "stamphog_policy"), f"{context}: the self-governance category exempts nobody")
    for team in raw:
        # Membership is matched against bare slugs, so `@PostHog/team-x` would exempt nobody without an error.
        _require(
            isinstance(team, str) and bool(_TEAM_SLUG_RE.match(team)),
            f"{context}: {team!r} is not a bare GitHub team slug like 'team-workflows'",
        )
    return tuple(raw)


def _parse_deny(raw: Any, lockfile_names: Iterable[str]) -> dict[str, DenyCategory]:
    _require(isinstance(raw, dict) and bool(raw), "deny: must be a non-empty mapping")
    lockfile_patterns = [re.escape(name) for name in sorted(lockfile_names)]

    deny: dict[str, DenyCategory] = {}
    for category, spec in raw.items():
        _require(isinstance(spec, dict), f"deny.{category}: must be a mapping")
        match_raw = spec.get("match")
        _require(isinstance(match_raw, dict) and bool(match_raw), f"deny.{category}.match: must be a non-empty mapping")

        match: dict[str, tuple[str, ...]] = {}
        for scope, patterns in match_raw.items():
            _require(scope in _DENY_SCOPES, f"deny.{category}.match.{scope}: unknown scope")
            _require(
                isinstance(patterns, list) and bool(patterns),
                f"deny.{category}.match.{scope}: must be a non-empty list",
            )
            values = list(patterns)
            # Splice the code-derived lockfile names ahead of the literal
            # patterns - they stay code-sourced (see DEPENDENCY_ECOSYSTEMS).
            if category == "deps_toolchain" and scope == "paths":
                values = lockfile_patterns + values
            for pattern in values:
                _require(isinstance(pattern, str), f"deny.{category}.match.{scope}: patterns must be strings")
                _compile_or_raise(pattern, f"deny.{category}.match.{scope}")
            match[scope] = tuple(values)

        _require(
            "exempt_path_prefixes" not in spec,
            f"deny.{category}.exempt_path_prefixes: removed, declare deny_exceptions.{category} with path_prefixes instead",
        )
        deny[category] = DenyCategory(
            description=str(spec.get("description", "")),
            rationale=str(spec.get("rationale", "")),
            match=match,
            exempt_author_teams=_parse_exempt_author_teams(category, spec.get("exempt_author_teams", [])),
        )

    _assert_self_governance(deny)
    if lockfile_patterns:
        # Same fail-closed posture as self-governance: renaming or splitting
        # the category must break loudly, not silently drop lockfile coverage.
        _require(
            "deps_toolchain" in deny,
            "deny: missing 'deps_toolchain' category (the code-derived lockfile patterns splice into it)",
        )
    return deny


def _parse_deny_exception_prefixes(raw: object, context: str) -> tuple[str, ...]:
    if not isinstance(raw, list) or not raw:
        raise PolicyError(f"{context}: must be a non-empty list")
    prefixes: list[str] = []
    for prefix in raw:
        if not isinstance(prefix, str):
            raise PolicyError(f"{context}: prefixes must be strings")
        _require(
            prefix.endswith("/")
            and all(segment not in {"", ".", ".."} for segment in prefix[:-1].split("/"))
            and not any(character.isspace() for character in prefix)
            and not _DENY_EXCEPTION_METACHARS_RE.search(prefix),
            f"{context}: {prefix!r} must be a literal relative POSIX directory prefix with a trailing slash",
        )
        prefixes.append(prefix.lower())
    return tuple(prefixes)


def _parse_deny_exception_extensions(raw: object, context: str) -> tuple[str, ...]:
    if not isinstance(raw, list) or not raw:
        raise PolicyError(f"{context}: must be a non-empty list")
    extensions: list[str] = []
    for extension in raw:
        if not isinstance(extension, str):
            raise PolicyError(f"{context}: extensions must be strings")
        _require(
            extension.startswith(".")
            and all(extension[1:].split("."))
            and "/" not in extension
            and not any(character.isspace() for character in extension)
            and not _DENY_EXCEPTION_METACHARS_RE.search(extension),
            f"{context}: {extension!r} must be a literal dot-prefixed suffix",
        )
        extensions.append(extension.lower())
    return tuple(extensions)


def _parse_deny_exceptions(raw: object, deny: dict[str, DenyCategory]) -> dict[str, tuple[DenyException, ...]]:
    if not isinstance(raw, dict):
        raise PolicyError("deny_exceptions: must be a mapping")
    exceptions: dict[str, tuple[DenyException, ...]] = {}
    for category, rules in raw.items():
        context = f"deny_exceptions.{category}"
        if not isinstance(category, str) or category not in deny:
            raise PolicyError(f"{context}: unknown deny category")
        _require(category != "stamphog_policy", f"{context}: the self-governance category exempts nobody")
        if not isinstance(rules, list) or not rules:
            raise PolicyError(f"{context}: must be a non-empty list")
        parsed: list[DenyException] = []
        for index, rule in enumerate(rules):
            rule_context = f"{context}[{index}]"
            if not isinstance(rule, dict):
                raise PolicyError(f"{rule_context}: must be a mapping")
            unknown = set(rule) - _DENY_EXCEPTION_KEYS
            _require(not unknown, f"{rule_context}: unknown keys {sorted(unknown, key=str)}")
            prefixes = _parse_deny_exception_prefixes(rule.get("path_prefixes"), f"{rule_context}.path_prefixes")
            extensions = (
                _parse_deny_exception_extensions(rule["extensions"], f"{rule_context}.extensions")
                if "extensions" in rule
                else ()
            )
            keyword = None
            if "keyword" in rule:
                requested = rule["keyword"]
                if not isinstance(requested, str) or not _LITERAL_KEYWORD_RE.fullmatch(requested):
                    raise PolicyError(f"{rule_context}.keyword: must be a non-empty literal ASCII token")
                keyword = next(
                    (
                        pattern
                        for scope in ("any", "paths")
                        for pattern in deny[category].match.get(scope, ())
                        if _LITERAL_KEYWORD_RE.fullmatch(pattern) and pattern.lower() == requested.lower()
                    ),
                    None,
                )
                _require(
                    keyword is not None,
                    f"{rule_context}.keyword: {requested!r} is not a path-capable literal pattern in this deny category",
                )
            parsed.append(DenyException(keyword=keyword, path_prefixes=prefixes, extensions=extensions))
        exceptions[category] = tuple(parsed)
    return exceptions


def _assert_self_governance(deny: dict[str, DenyCategory]) -> None:
    _require("stamphog_policy" in deny, "deny: missing required 'stamphog_policy' self-governance category")
    paths = " ".join(deny["stamphog_policy"].match.get("paths", ()))
    for token in _SELF_GOVERNANCE_REQUIRED:
        _require(token in paths, f"deny.stamphog_policy: self-governance must cover {token!r}")


def _parse_allow(raw: Any) -> tuple[tuple[str, ...], frozenset[str]]:
    _require(isinstance(raw, dict), "allow: must be a mapping")
    path_patterns = raw.get("path_patterns")
    extensions = raw.get("extensions_only")
    _require(isinstance(path_patterns, list) and bool(path_patterns), "allow.path_patterns: must be a non-empty list")
    _require(isinstance(extensions, list) and bool(extensions), "allow.extensions_only: must be a non-empty list")
    return tuple(str(p) for p in path_patterns), frozenset(str(e) for e in extensions)


def _parse_size_gate(raw: Any) -> SizeGate:
    _require(isinstance(raw, dict), "size_gate: must be a mapping")
    max_lines = raw.get("max_lines")
    max_files = raw.get("max_files")
    _require(isinstance(max_lines, int) and not isinstance(max_lines, bool), "size_gate.max_lines: must be an integer")
    _require(isinstance(max_files, int) and not isinstance(max_files, bool), "size_gate.max_files: must be an integer")
    return SizeGate(max_lines=max_lines, max_files=max_files)


def _parse_tiers(raw: Any) -> dict[str, T1Subclass]:
    _require(isinstance(raw, dict), "tiers: must be a mapping")
    subclasses_raw = raw.get("t1_subclasses")
    _require(
        isinstance(subclasses_raw, dict) and bool(subclasses_raw),
        "tiers.t1_subclasses: must be a non-empty mapping",
    )
    subclasses: dict[str, T1Subclass] = {}
    for name, spec in subclasses_raw.items():
        _require(isinstance(spec, dict), f"tiers.t1_subclasses.{name}: must be a mapping")
        max_lines = spec.get("max_lines")
        max_files = spec.get("max_files")
        breadth = spec.get("breadth")
        _require(
            isinstance(max_lines, int) and not isinstance(max_lines, bool), f"{name}.max_lines: must be an integer"
        )
        _require(
            isinstance(max_files, int) and not isinstance(max_files, bool), f"{name}.max_files: must be an integer"
        )
        _require(breadth in _BREADTH_RULES, f"{name}.breadth: must be one of {sorted(_BREADTH_RULES)}")
        subclasses[name] = T1Subclass(max_lines=max_lines, max_files=max_files, breadth=breadth)
    return subclasses


def _parse_overrides(raw: Any) -> dict[str, OverrideContract]:
    _require(isinstance(raw, dict), "overrides: must be a mapping")
    overrides: dict[str, OverrideContract] = {}
    for key, spec in raw.items():
        _require(key in _DELEGABLE_KEYS, f"overrides.{key}: not a delegable key (allowed: {sorted(_DELEGABLE_KEYS)})")
        _require(isinstance(spec, dict), f"overrides.{key}: must be a mapping")
        ceiling = spec.get("ceiling")
        _require(
            isinstance(ceiling, int) and not isinstance(ceiling, bool), f"overrides.{key}.ceiling: must be an integer"
        )
        overrides[key] = OverrideContract(ceiling=ceiling)
    return overrides


def _require_ceilings_cover_globals(size_gate: SizeGate, overrides: dict[str, OverrideContract]) -> None:
    """A delegation ceiling under its own global default is incoherent - fail closed.

    The ceiling is what bounds a PR's whole-PR roof. Under the global default it
    would bound nothing, because the always-present global pool already carries
    the roof past it, and delegation could then only ever lower a folder's
    allowance.
    """
    globals_by_key = {"size_gate.max_lines": size_gate.max_lines, "size_gate.max_files": size_gate.max_files}
    for key, contract in overrides.items():
        global_value = globals_by_key.get(key)
        if global_value is None:
            continue
        _require(
            contract.ceiling >= global_value,
            f"overrides.{key}.ceiling: {contract.ceiling} is under the global {key} ({global_value})",
        )


_FAMILIARITY_STRONG_KEYS = {"min_blame_overlap_pct"}
_FAMILIARITY_MODERATE_KEYS = {"min_prior_prs", "max_days_since_touch"}


def _require_percentage(value: Any, context: str) -> float:
    _require(isinstance(value, (int, float)) and not isinstance(value, bool), f"{context}: must be a number")
    _require(0 <= value <= 100, f"{context}: must be between 0 and 100")
    return float(value)


def _require_positive_int(value: Any, context: str) -> int:
    _require(isinstance(value, int) and not isinstance(value, bool), f"{context}: must be an integer")
    _require(value > 0, f"{context}: must be positive")
    return value


def _require_exact_keys(raw: dict, expected: set[str], context: str) -> None:
    unknown = set(raw) - expected
    _require(not unknown, f"{context}: unknown keys {sorted(unknown)}")
    missing = expected - set(raw)
    _require(not missing, f"{context}: missing keys {sorted(missing)}")


def _parse_familiarity(raw: Any) -> FamiliarityPolicy:
    _require(isinstance(raw, dict), "familiarity: must be a mapping")
    _require_exact_keys(raw, {"strong", "moderate"}, "familiarity")

    strong_raw = raw["strong"]
    moderate_raw = raw["moderate"]
    _require(isinstance(strong_raw, dict), "familiarity.strong: must be a mapping")
    _require(isinstance(moderate_raw, dict), "familiarity.moderate: must be a mapping")
    _require_exact_keys(strong_raw, _FAMILIARITY_STRONG_KEYS, "familiarity.strong")
    _require_exact_keys(moderate_raw, _FAMILIARITY_MODERATE_KEYS, "familiarity.moderate")

    strong = FamiliarityStrong(
        min_blame_overlap_pct=_require_percentage(
            strong_raw["min_blame_overlap_pct"], "familiarity.strong.min_blame_overlap_pct"
        ),
    )
    moderate = FamiliarityModerate(
        min_prior_prs=_require_positive_int(moderate_raw["min_prior_prs"], "familiarity.moderate.min_prior_prs"),
        max_days_since_touch=_require_positive_int(
            moderate_raw["max_days_since_touch"], "familiarity.moderate.max_days_since_touch"
        ),
    )
    return FamiliarityPolicy(strong=strong, moderate=moderate)


def _require_repo_relative(value: str, context: str) -> None:
    """A source locator must stay inside the checked-out tree - no absolute path, no `..`.

    The workflow pins `ref: master`, so sources are read from the trusted
    checkout; an absolute or escaping locator could reach outside it.
    """
    parts = PurePosixPath(value).parts
    _require(not PurePosixPath(value).is_absolute(), f"{context}: must be repo-relative, not absolute")
    _require(".." not in parts, f"{context}: must not escape the repo (no '..')")


def _parse_ownership(raw: Any, known_formats: Mapping[str, str]) -> tuple[OwnershipSource, ...]:
    _require(isinstance(raw, dict), "ownership: must be a mapping")
    _require_exact_keys(raw, {"sources"}, "ownership")
    sources_raw = raw["sources"]
    _require(isinstance(sources_raw, list) and bool(sources_raw), "ownership.sources: must be a non-empty list")

    formats = dict(known_formats)
    sources: list[OwnershipSource] = []
    for index, entry in enumerate(sources_raw):
        context = f"ownership.sources[{index}]"
        _require(isinstance(entry, dict), f"{context}: must be a mapping")
        _require(
            not set(entry) - {"format", "path", "glob"},
            f"{context}: unknown keys {sorted(set(entry) - {'format', 'path', 'glob'})}",
        )

        fmt = entry.get("format")
        _require(isinstance(fmt, str) and fmt in formats, f"{context}.format: must be one of {sorted(formats)}")

        key = formats[fmt]
        locator_keys = {"path", "glob"} & set(entry)
        _require(locator_keys == {key}, f"{context}: format {fmt!r} takes exactly one locator, {key!r}")
        value = entry[key]
        _require(isinstance(value, str) and bool(value), f"{context}.{key}: must be a non-empty string")
        _require_repo_relative(value, f"{context}.{key}")
        sources.append(OwnershipSource(format=fmt, **{key: value}))
    return tuple(sources)


_EXTEND_PREFIX = "extend_"


def _merge_mapping(base: Mapping[str, Any], overlay: Mapping[str, Any], context: str) -> dict[str, Any]:
    merged = dict(base)
    for key, value in overlay.items():
        key_context = f"{context}{key}"
        if isinstance(key, str) and key.startswith(_EXTEND_PREFIX):
            target = key.removeprefix(_EXTEND_PREFIX)
            _require(target not in overlay, f"{key_context}: cannot both replace and extend {context}{target}")
            inherited = base.get(target)
            _require(isinstance(inherited, list), f"{key_context}: no inherited list {context}{target} to extend")
            _require(isinstance(value, list), f"{key_context}: must be a list")
            merged[target] = inherited + [item for item in value if item not in inherited]
        elif isinstance(value, dict) and isinstance(base.get(key), dict):
            merged[key] = _merge_mapping(base[key], value, f"{key_context}.")
        else:
            merged[key] = value
    return merged


def merge_policy(default: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]:
    """A repository's policy.yml merged onto the shipped default.

    Mappings merge key by key, so a repository declares only what it changes: one deny category,
    one field of a category, one threshold. A list the repository declares replaces the default's
    list, and an `extend_<name>` key appends to the default's `<name>` list instead. Lists never
    merge silently, because a repository could then not drop an inherited entry.
    """
    _require(isinstance(overlay, dict), "policy root: must be a mapping")
    return _merge_mapping(default, overlay, "")


def _assert_self_governance_floor(default: dict[str, Any], merged: dict[str, Any]) -> None:
    """A repository may extend the self-governance deny, but never drop a shipped pattern from it."""
    shipped = default["deny"]["stamphog_policy"]["match"]["paths"]
    effective = ((merged.get("deny") or {}).get("stamphog_policy") or {}).get("match") or {}
    missing = [pattern for pattern in shipped if pattern not in (effective.get("paths") or [])]
    _require(not missing, f"deny.stamphog_policy.match.paths: drops the shipped self-governance patterns {missing}")


def _read_policy_yaml(path: Path) -> Any:
    try:
        return yaml.safe_load(path.read_text())
    except (OSError, yaml.YAMLError) as exc:
        raise PolicyError(f"could not read/parse {path}: {exc}") from exc


def _parse_policy(raw: Any, *, lockfile_names: Iterable[str], ownership_formats: Mapping[str, str]) -> Policy:
    _require(isinstance(raw, dict), "policy root: must be a mapping")
    unknown = set(raw) - _TOP_LEVEL_KEYS - _OPTIONAL_TOP_LEVEL_KEYS - _SERVER_ONLY_TOP_LEVEL_KEYS
    _require(not unknown, f"policy root: unknown top-level keys {sorted(unknown)}")
    for required in _TOP_LEVEL_KEYS:
        _require(required in raw, f"policy root: missing required section {required!r}")
    _require(raw["version"] == 1, f"policy version: unsupported version {raw['version']!r}")

    path_patterns, extensions = _parse_allow(raw["allow"])
    size_gate = _parse_size_gate(raw["size_gate"])
    overrides = _parse_overrides(raw["overrides"])
    _require_ceilings_cover_globals(size_gate, overrides)
    deny = _parse_deny(raw["deny"], lockfile_names)
    return Policy(
        version=1,
        deny=deny,
        allow_path_patterns=path_patterns,
        allow_extensions=extensions,
        size_gate=size_gate,
        t1_subclasses=_parse_tiers(raw["tiers"]),
        overrides=overrides,
        familiarity=_parse_familiarity(raw["familiarity"]),
        ownership=_parse_ownership(raw["ownership"], ownership_formats),
        deny_exceptions=_parse_deny_exceptions(raw.get("deny_exceptions", {}), deny),
    )


def load_policy(path: Path, *, lockfile_names: Iterable[str], ownership_formats: Mapping[str, str]) -> Policy:
    """Parse and validate one complete policy document, splicing code-derived data.

    `lockfile_names` are the deps_toolchain lockfile filenames owned by
    gates.py's DEPENDENCY_ECOSYSTEMS table; the loader re.escapes them and
    splices them into the deps_toolchain deny paths (they stay code-sourced,
    never copied into the YAML). `ownership_formats` maps each source-format
    name gates.py's OWNERSHIP_FORMATS registry knows how to build to its
    required locator key ("path" or "glob"); the loader validates every
    `ownership.sources[*]` format and locator pairing against it (same
    code-sourced pattern as lockfile_names). Raises PolicyError on any
    malformed input.
    """
    return _parse_policy(_read_policy_yaml(path), lockfile_names=lockfile_names, ownership_formats=ownership_formats)


def load_effective_policy(*, lockfile_names: Iterable[str], ownership_formats: Mapping[str, str]) -> Policy:
    """The shipped default with the repository's `.stamphog/policy.yml` merged onto it, validated as one document.

    Hosted runs, the server's pre-check and local runs all resolve the policy here. The server
    copies the repository's default-branch file into the tree as it is, so the merge happens once.
    """
    default = _read_policy_yaml(bundled_defaults_dir() / "policy.yml")
    _require(isinstance(default, dict), "shipped default policy: must be a mapping")
    overlay_path = repo_policy_path()
    merged = merge_policy(default, _read_policy_yaml(overlay_path)) if overlay_path.is_file() else default
    _assert_self_governance_floor(default, merged)
    return _parse_policy(merged, lockfile_names=lockfile_names, ownership_formats=ownership_formats)


# ── Per-folder override resolution ───────────────────────────────

FOLDER_PROSE_MAX_LEN = 2000
_PROSE_TRUNCATION_MARKER = "\n[... folder policy guidance truncated ...]"
_FOLDER_POLICY_FILENAME = "AGENT_APPROVALS.md"
_FRONTMATTER_RE = re.compile(r"^---\n(.*?)\n---\n?(.*)\Z", re.DOTALL)


@dataclass(frozen=True)
class _FolderOverride:
    """Result of parsing a folder AGENT_APPROVALS.md."""

    max_files: int | None = None
    max_lines: int | None = None
    prose: str | None = None
    invalid: bool = False


def _scope_chain_for(
    file_path: str, root: Path, cache: dict[PurePosixPath, tuple[PurePosixPath, ...]]
) -> tuple[PurePosixPath, ...]:
    """Directories carrying an AGENT_APPROVALS.md at or above `file_path`, nearest first.

    A child folder file refines its ancestors rather than replacing them, so the
    whole ancestor chain governs the file, not just the nearest folder. Empty
    when no folder file governs the path (the file belongs to the global pool).
    Per-directory cache keeps this one stat per distinct directory: it maps a
    directory to the full chain of policy-bearing directories at or above it.
    """
    start = PurePosixPath(file_path).parent
    if start in cache:
        return cache[start]

    # Walk up until a directory already resolved (or the root), remembering the
    # directories we still have to stat.
    pending: list[PurePosixPath] = []
    tail: tuple[PurePosixPath, ...] = ()
    for rel in [start, *start.parents]:
        if rel in cache:
            tail = cache[rel]
            break
        pending.append(rel)

    # Fill the cache outermost-first so each directory builds on its parent's
    # chain; prepending keeps the whole chain nearest-first.
    for rel in reversed(pending):
        if (root / rel / _FOLDER_POLICY_FILENAME).is_file():
            tail = (rel, *tail)
        cache[rel] = tail
    return cache[start]


def _sanitize_folder_prose(raw: str) -> str:
    """Strip invisibles and cap folder prose, appending a marker when truncated."""
    cleaned = _INVISIBLE_CHARS_RE.sub("", raw).strip()
    if len(cleaned) > FOLDER_PROSE_MAX_LEN:
        return cleaned[:FOLDER_PROSE_MAX_LEN] + _PROSE_TRUNCATION_MARKER
    return cleaned


def _parse_folder_policy(path: Path, contract: dict[str, OverrideContract]) -> _FolderOverride:
    """Positive allow-list parse of a folder AGENT_APPROVALS.md.

    Reads ONLY the delegated keys from the `stamphog:` frontmatter block within
    contract ceilings; any bad frontmatter, undelegated key, or out-of-bounds
    value invalidates the whole file (frontmatter AND prose), never crashing.
    """
    try:
        text = path.read_text()
    except OSError:
        return _FolderOverride(invalid=True)

    frontmatter_match = _FRONTMATTER_RE.match(text)
    if frontmatter_match is None:
        return _FolderOverride(invalid=True)

    try:
        frontmatter = yaml.safe_load(frontmatter_match.group(1))
    except yaml.YAMLError:
        return _FolderOverride(invalid=True)
    if not isinstance(frontmatter, dict):
        return _FolderOverride(invalid=True)

    prose = _sanitize_folder_prose(frontmatter_match.group(2))

    stamphog = frontmatter.get("stamphog")
    if stamphog is None:
        # Advisory-only file: no delegated override, prose still applies.
        return _FolderOverride(prose=prose or None)
    if not isinstance(stamphog, dict):
        return _FolderOverride(invalid=True)

    # Positive allow-list: the only delegated paths are the size_gate ceilings.
    grants = _read_delegated_size_gate(stamphog, contract)
    if grants is None:
        return _FolderOverride(invalid=True)
    return _FolderOverride(max_files=grants.get("max_files"), max_lines=grants.get("max_lines"), prose=prose or None)


def _read_delegated_size_gate(stamphog: dict[str, Any], contract: dict[str, OverrideContract]) -> dict[str, int] | None:
    if set(stamphog) - {"size_gate"}:
        return None
    size_gate = stamphog.get("size_gate")
    if not isinstance(size_gate, dict) or not size_gate:
        return None
    grants: dict[str, int] = {}
    for key, value in size_gate.items():
        contract_key = _SIZE_GATE_DELEGATIONS.get(key) if isinstance(key, str) else None
        if contract_key is None or contract_key not in contract:
            return None
        if not isinstance(value, int) or isinstance(value, bool):
            return None
        if value < 1 or value > contract[contract_key].ceiling:
            return None
        grants[key] = value
    return grants


def resolve(policy: Policy, changed_files: list[str]) -> EffectivePolicy:
    """Resolve the per-scope size budgets for a PR's changed files.

    Every AGENT_APPROVALS.md at or above a changed file governs it. Each ceiling
    resolves on its own: a file counts against the nearest folder on its chain
    granting that ceiling, and against the global pool when the chain grants it
    nowhere (no folder file, prose-only, or only invalid grants). Lines and files
    therefore partition independently, so a folder raising one ceiling leaves its
    files in the global pool for the other. Advisory prose accumulates from
    every valid folder file on the chain of at least one changed file, outermost
    first so general guidance precedes specific. An invalid folder file is
    treated as absent - it grants nothing and adds no prose, but its ancestors
    still apply - and is reported in invalid_folder_files.
    """
    root = repo_root()
    dir_cache: dict[PurePosixPath, tuple[PurePosixPath, ...]] = {}
    parse_cache: dict[PurePosixPath, tuple[str, _FolderOverride]] = {}

    def parsed_for(scope_dir: PurePosixPath) -> tuple[str, _FolderOverride]:
        if scope_dir not in parse_cache:
            rel_path = (scope_dir / _FOLDER_POLICY_FILENAME).as_posix()
            parse_cache[scope_dir] = (rel_path, _parse_folder_policy(root / rel_path, policy.overrides))
        return parse_cache[scope_dir]

    # Files sharing a granting AGENT_APPROVALS.md pool into one budget, per
    # ceiling; a None bucket key is the global pool. The folder files touched by
    # any chain feed the prose and invalid-file reporting.
    file_buckets: dict[str | None, list[str]] = {}
    line_buckets: dict[str | None, list[str]] = {}
    file_ceilings: dict[str, int] = {}
    line_ceilings: dict[str, int] = {}
    on_chain: dict[str, _FolderOverride] = {}  # rel path -> parse, each file once
    for file_path in changed_files:
        file_scope: str | None = None
        line_scope: str | None = None
        for scope_dir in _scope_chain_for(file_path, root, dir_cache):
            rel_path, parsed = parsed_for(scope_dir)
            on_chain[rel_path] = parsed
            if parsed.invalid:
                continue
            if file_scope is None and parsed.max_files is not None:
                file_scope = rel_path
                file_ceilings[rel_path] = parsed.max_files
            if line_scope is None and parsed.max_lines is not None:
                line_scope = rel_path
                line_ceilings[rel_path] = parsed.max_lines
        file_buckets.setdefault(file_scope, []).append(file_path)
        line_buckets.setdefault(line_scope, []).append(file_path)

    prose_parts: list[tuple[str, str]] = []
    invalid_files: list[str] = []
    for rel_path, parsed in on_chain.items():
        if parsed.invalid:
            invalid_files.append(rel_path)
        elif parsed.prose:
            prose_parts.append((rel_path, parsed.prose))
    # Outermost first: shallower path depth wins, ties broken lexicographically.
    prose_parts.sort(key=lambda item: (item[0].count("/"), item[0]))
    invalid_files.sort()

    if len(prose_parts) == 1:
        folder_prose = prose_parts[0][1]
    elif prose_parts:
        folder_prose = "\n\n".join(f"[{path}]\n{prose}" for path, prose in prose_parts)
    else:
        folder_prose = None

    return EffectivePolicy(
        file_scopes=_scope_budgets(file_buckets, file_ceilings, policy.size_gate.max_files),
        line_scopes=_scope_budgets(line_buckets, line_ceilings, policy.size_gate.max_lines),
        folder_prose=folder_prose,
        invalid_folder_files=tuple(invalid_files),
    )


def _scope_budgets(
    buckets: dict[str | None, list[str]], ceilings: dict[str, int], global_ceiling: int
) -> tuple[ScopeBudget, ...]:
    """Folder budgets sorted by path, then the global pool - present even when empty."""
    overrides = [
        ScopeBudget(path=path, ceiling=ceilings[path], files=tuple(buckets[path]))
        for path in sorted(path for path in buckets if path is not None)
    ]
    return (*overrides, ScopeBudget(path=None, ceiling=global_ceiling, files=tuple(buckets.get(None, ()))))