From c6dbc3bab5bfdabfd27ce7a8be54eccf9ab4f82d Mon Sep 17 00:00:00 2001 From: Jothi Mani Rajendran <250249270+jothimani-rajendran@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:19:58 +0000 Subject: [PATCH 1/2] Pin README install to engine 1.2.0 (5088f2f1) Move the chock install pin from 2f3be6d04349 to the 1.2.0 engine commit 5088f2f17df0c10b3269a68685a3500ffea6516a. Signed-off-by: Jothi Mani Rajendran <250249270+jothimani-rajendran@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d165049..3fdbac3 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Tiers: `commit` is a git hook or CI gate that exits non-zero. `in-agent` is the chock is on PyPI, but the release there (0.15.2, 30 Sep 2026) is older than the engine this page describes. Install the frozen engine from its commit (Python 3.11 or newer): ```bash -pip install "chock @ git+https://github.com/open-coder-ai/chock@2f3be6d04349a7ec433657e16a294efc62b51d4f" +pip install "chock @ git+https://github.com/open-coder-ai/chock@5088f2f17df0c10b3269a68685a3500ffea6516a" ``` ### Two ways to adopt it From d442f4ca9866c60a47d06482c90744890d63c04c Mon Sep 17 00:00:00 2001 From: Jothi Mani Rajendran <250249270+jothimani-rajendran@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:25:24 -0500 Subject: [PATCH 2/2] release: sync the compiled policies for chock at 5088f2f17df0 Signed-off-by: Jothi Mani Rajendran <250249270+jothimani-rajendran@users.noreply.github.com> --- .chock/bin/_chock_runtime.py | 31 +++++++-- .chock/bin/claude_code.py | 3 +- .chock/bin/gate.py | 121 ++++++++++++++++++++++++++++++----- .chock/bin/launch.sh | 9 ++- chock.lock | 2 +- 5 files changed, 140 insertions(+), 26 deletions(-) diff --git a/.chock/bin/_chock_runtime.py b/.chock/bin/_chock_runtime.py index 3692629..233ffb4 100644 --- a/.chock/bin/_chock_runtime.py +++ b/.chock/bin/_chock_runtime.py @@ -32,6 +32,8 @@ BYTECODE_OFF = {'PYTHONDONTWRITEBYTECODE': '1'} +ISOLATED_START = "import os, runpy, sys\nsys.argv = sys.argv[1:]\nsys.path.insert(0, os.path.dirname(os.path.abspath(sys.argv[0])))\nrunpy.run_path(sys.argv[0], run_name='__main__')\n" + PATTERN_SECONDS = 10 PATTERN_START_SECONDS = 10 @@ -111,6 +113,17 @@ def run_tree(argv, *, timeout=None, **options): untrack_tree(proc) return _chock_subprocess.CompletedProcess(argv, proc.returncode, out, err) +def python_free_env(env=None): + """`env` (this process's by default) without any `PYTHON*` variable, plus bytecode off for grandchildren.""" + base = _chock_os.environ if env is None else env + return {**{k: v for k, v in base.items() if not k.upper().startswith('PYTHON')}, **BYTECODE_OFF} + +def isolated_child(argv, env=None): + """(argv, env) that run the Python child `[interpreter, script, *args]` isolated: no PYTHON* variable, + user site or current folder can change what it imports; its own folder is put on sys.path explicitly.""" + interpreter, script, *args = argv + return ([interpreter, '-I', '-B', '-X', 'utf8', '-c', ISOLATED_START, str(script), *args], python_free_env(env)) + def engine_remaining(deadline): """Seconds left before `deadline`, never negative.""" return max(deadline - _chock_time.monotonic(), 0.0) @@ -803,7 +816,7 @@ def bash_candidates() -> list[str]: def interpreter_env(interpreter: str) -> dict[str, str]: """The environment a guard runs in: on Windows, Git's usr/bin ahead on PATH for sed and grep.""" - env = {**_chock_os.environ, **BYTECODE_OFF} + env = python_free_env() env.pop(CAN_ASK_ENV, None) if _chock_os.name != _WINDOWS: return env @@ -861,6 +874,11 @@ def split_command(command: str) -> tuple[list[str], bool]: except ValueError: return (command.split(), True) +def _guard_start(interpreter: str, guard: _chock_Path, args: list[str], env: dict[str, str]): + """(argv, env) for the guard: a Python guard starts isolated, a shell guard as given.""" + argv = [interpreter, str(guard), *args] + return isolated_child(argv, env) if guard.suffix == PYTHON_SUFFIX else (argv, env) + def run_guard(guard: _chock_Path, command: str, tool: str='') -> str: """`GUARD_BLOCKED` / `GUARD_ASKED` / `GUARD_CLEAN` when the guard ran, otherwise why it did not.""" return run_guard_detailed(guard, command, tool)[0] @@ -888,7 +906,8 @@ def run_guard_detailed(guard: _chock_Path, command: str, tool: str='', *, can_as if fallback: env[ARGV_FALLBACK_ENV] = '1' env.update({} if can_ask is None else {CAN_ASK_ENV: '1' if can_ask else '0'}) - proc = run_tree([interpreter, str(guard), *args], capture_output=True, text=True, encoding='utf-8', errors='replace', env=env, timeout=time_left(deadline, [interpreter, str(guard)]), check=False) + argv, env = _guard_start(interpreter, guard, args, env) + proc = run_tree(argv, capture_output=True, text=True, encoding='utf-8', errors='replace', env=env, timeout=time_left(deadline, [interpreter, str(guard)]), check=False) except _chock_subprocess.TimeoutExpired: print(f'chock: guard timed out after {ENGINE_BUDGET_SECONDS}s, not checked', file=sys.stderr) return (GUARD_ERRORED, '') @@ -2624,9 +2643,9 @@ def run_gate(gate, writes, event, run_in, deadline): runner = runner_for(gate) if runner is None: return (GATE_ERRORED, 'the vendored gate runner is not installed beside this gate') - argv = [sys.executable, str(runner), 'run', '--gate', str(gate), '--event', event] + argv, env = isolated_child([sys.executable, str(runner), 'run', '--gate', str(gate), '--event', event]) try: - proc = run_tree(argv, input=json.dumps({'writes': writes, **(extra or {})}), capture_output=True, text=True, encoding=_UTF8, errors='replace', timeout=time_left(deadline, argv), check=False, cwd=str(root) if root is not None else None) + proc = run_tree(argv, env=env, input=json.dumps({'writes': writes, **(extra or {})}), capture_output=True, text=True, encoding=_UTF8, errors='replace', timeout=time_left(deadline, argv), check=False, cwd=str(root) if root is not None else None) except _chock_subprocess.TimeoutExpired as exc: return (GATE_ERRORED, f'the gate runner gave no verdict within {allowed_seconds(exc)}') except (OSError, _chock_subprocess.SubprocessError) as exc: @@ -2767,9 +2786,9 @@ def _tool_call_script(spec, root, payload, deadline=None): if not script.is_file(): return ('deny', f'script gate: {named!r} is not installed{_TOOL_CALL_UNDECIDED}') deadline = engine_deadline() if deadline is None else deadline - argv = [sys.executable, str(script)] + argv, env = isolated_child([sys.executable, str(script)]) try: - proc = run_tree(argv, input=json.dumps(payload), capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=str(root), env={**_chock_os.environ, **BYTECODE_OFF}, timeout=time_left(deadline, argv), check=False) + proc = run_tree(argv, input=json.dumps(payload), capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=str(root), env=env, timeout=time_left(deadline, argv), check=False) except _chock_subprocess.TimeoutExpired as exc: budget = f'gave no verdict within {allowed_seconds(exc)}' return ('deny', f'script gate: {script.name} {budget}{_TOOL_CALL_UNDECIDED}') diff --git a/.chock/bin/claude_code.py b/.chock/bin/claude_code.py index 30f363a..86885f6 100755 --- a/.chock/bin/claude_code.py +++ b/.chock/bin/claude_code.py @@ -23,6 +23,7 @@ _chock_start_os.write(9, b"chock-python") _chock_start_os.close(9) except OSError: + # No launcher listening on fd 9 is not an error: the marker is only a hint, so run on. pass import contextlib @@ -854,7 +855,7 @@ def degrade(decision, event): # Not self-contained: chock's guard logic lives in the sibling _chock_runtime.py, loaded from this # file's own folder and pinned to the sha256 of that file's bytes (CRLF read as LF), hashed before they are executed. # Missing, unreadable, another version, or failing to import: every call refuses (_CHOCK_RUNTIME_FAULT), never allows. -_CHOCK_RUNTIME_PIN = '8e3b4b73f866de5887946c8afe0dee895548a5d67146470d63350fa84b08b5f2' +_CHOCK_RUNTIME_PIN = '791b92ce3802e2b71819589bced3f7c5fd079bf535cf469a785480a3a31c91f7' def _chock_load_runtime(): diff --git a/.chock/bin/gate.py b/.chock/bin/gate.py index 41abf26..8d5ab99 100644 --- a/.chock/bin/gate.py +++ b/.chock/bin/gate.py @@ -34,6 +34,14 @@ BYTECODE_OFF = {"PYTHONDONTWRITEBYTECODE": "1"} +ISOLATED_START = ( + "import os, runpy, sys\n" + "sys.argv = sys.argv[1:]\n" + "sys.path.insert(0, os.path.dirname(os.path.abspath(sys.argv[0])))\n" + "runpy.run_path(sys.argv[0], run_name='__main__')\n" +) + + PATTERN_SECONDS = 10 @@ -137,6 +145,19 @@ def run_tree(argv, *, timeout=None, **options): return subprocess.CompletedProcess(argv, proc.returncode, out, err) +def python_free_env(env=None): + """`env` (this process's by default) without any `PYTHON*` variable, plus bytecode off for grandchildren.""" + base = os.environ if env is None else env + return {**{k: v for k, v in base.items() if not k.upper().startswith("PYTHON")}, **BYTECODE_OFF} + + +def isolated_child(argv, env=None): + """(argv, env) that run the Python child `[interpreter, script, *args]` isolated: no PYTHON* variable, + user site or current folder can change what it imports; its own folder is put on sys.path explicitly.""" + interpreter, script, *args = argv + return [interpreter, "-I", "-B", "-X", "utf8", "-c", ISOLATED_START, str(script), *args], python_free_env(env) + + def engine_remaining(deadline): """Seconds left before `deadline`, never negative.""" return max(deadline - time.monotonic(), 0.0) @@ -298,6 +319,7 @@ def __init__( self.scope = tuple(scope or ()) #: Path prefixes this gate never judges: its own policy's source and compiled folders. self.own = tuple(own) + self._rename_map: dict[str, str] | None = None def is_own(self, path: str) -> bool: """Whether `path` is in this policy's own source or compiled folder.""" @@ -364,9 +386,28 @@ def staged_paths(self, diff_filter: str = "ACMRT", *, judge_own: bool = False) - paths = self._listing("diff", *self._range(), "--name-only", f"--diff-filter={diff_filter}") return [path for path in paths if self.in_scope(path, judge_own=judge_own)] + def _rename_range(self) -> list[str] | None: + """The git-diff scope whose renames the baseline follows; None when this context has none.""" + return self._range() + + def _renames(self) -> dict[str, str]: + """{new path: old path} for what git itself reports as renamed (`-M`, default similarity); never a guess. + + A listing that fails or does not parse says no rename, which leaves the baseline at the path (stricter). + """ + if self._rename_map is None: + scope, tokens = self._rename_range(), [] + if scope is not None: + with contextlib.suppress(ListingError): + tokens = self._listing("diff", *scope, "-M", "--relative", "--name-status", "--diff-filter=R") + self._rename_map = {tokens[i + 2]: tokens[i + 1] for i in range(0, len(tokens) - 2, 3)} + return self._rename_map + def _diff_text(self, path: str) -> str: """`path`'s `-U0` diff as git writes it, unconverted; raises DiffError when git fails.""" - args = ("diff", *self._range(), "-U0", "--no-color", "--no-ext-diff", "--no-textconv", "--", path) + old = self._renames().get(path) + paths = (path, old) if old else (path,) + args = ("diff", *self._range(), "-M", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", "--", *paths) try: proc = subprocess.run( # noqa: S603 -- reading repo facts via git is this class's whole job [_GIT, "--literal-pathspecs", *args], @@ -394,16 +435,19 @@ def staged_blob(self, path: str) -> str: """The proposed content: staged in index mode, committed at HEAD in range mode.""" return self._git("show", f"HEAD:{path}" if self.base else f":{path}") + def renamed_from(self, path: str) -> str: # the old path git reports, else `path` + return self._renames().get(path, path) + def head_blob(self, path: str) -> str: - """Content before the change, or "" when the path is new in it.""" - return self._git("show", f"{self.base or 'HEAD'}:{path}") + """Content before the change ("" when new); a renamed path reads its old path.""" + return self._git("show", f"{self.base or 'HEAD'}:{self.renamed_from(path)}") def committed_blob(self, path: str) -> str: """The file as HEAD has it, or "" when HEAD does not.""" return self._git("show", f"HEAD:{path}") def net_added_lines(self, path: str) -> list[str]: - """The lines this change introduces; at a commit that is what `added_lines` already says.""" + """The lines this change introduces: at a commit, `added_lines`.""" return self.added_lines(path) def current_branch(self) -> str: @@ -465,6 +509,10 @@ def __init__( self._added = dict(added or {}) self._stop = stop + def _rename_range(self) -> list[str] | None: + """At the turn's end, HEAD against the index and tree; a write before the tool runs has no rename.""" + return ["HEAD"] if self._stop else None + def staged_paths(self, diff_filter: str = "ACMRT", *, judge_own: bool = False) -> list[str]: """Every write is a present file, so a filter asking only for deletions finds none.""" if not set(diff_filter) & set("ACMRT"): @@ -496,7 +544,7 @@ def committed_blob(self, path: str) -> str: def head_blob(self, path: str) -> str: """The baseline: HEAD at the turn's end, else what is on disk now, which this write would replace.""" if self._stop: - return self.committed_blob(path) + return self.committed_blob(self.renamed_from(path)) try: return (self.repo_root / path).read_text(encoding="utf-8") except (OSError, UnicodeDecodeError): @@ -550,8 +598,12 @@ def head_blob(self, path: str) -> str: #: adds is not honoured. Coverage (`on: [commit]`) is still decided by the name `commit`. AGENT_COMMIT_EVENT = "agent-commit" +#: The event `chock check --floor` judges at: the change under judgement may be the refused party's, so a +#: waiver counts only when the base already has that line (the floor's `committed_blob` reads the base). +FLOOR_EVENT = "ci-floor" + #: Events where the actor may be the refused agent: a waiver counts only when HEAD already has that line. -HEAD_WAIVER_EVENTS = frozenset({AGENT_COMMIT_EVENT, TOOL_USE_EVENT}) +HEAD_WAIVER_EVENTS = frozenset({AGENT_COMMIT_EVENT, TOOL_USE_EVENT, FLOOR_EVENT}) _HUMAN_ENV = frozenset({"0", "false", "no", "off"}) @@ -959,6 +1011,15 @@ def _kind_test_integrity(ctx: GateContext, params: dict, event: str) -> GateResu _FINDINGS_KEY = "findings" +#: All a script gate's environment holds at the floor: no token, secret or runner variable reaches it. +_FLOOR_ENV_KEYS = ("PATH", "HOME", "SYSTEMROOT") + + +def _env(event: object) -> dict[str, str]: + if event == FLOOR_EVENT: + return {key: os.environ[key] for key in _FLOOR_ENV_KEYS if key in os.environ} | _BYTECODE_OFF + return {**os.environ, **_BYTECODE_OFF} + def _spawn(script: Path, ctx: GateContext, payload: dict, timeout: float) -> subprocess.CompletedProcess[str]: return run_tree( @@ -969,7 +1030,7 @@ def _spawn(script: Path, ctx: GateContext, payload: dict, timeout: float) -> sub encoding="utf-8", errors="replace", cwd=ctx.repo_root, - env={**os.environ, **_BYTECODE_OFF}, + env=_env(payload.get("event")), timeout=timeout, check=False, ) @@ -1024,13 +1085,35 @@ def _new_findings(found: list[dict], baseline: list[dict]) -> list[dict]: return fresh +#: A finding's optional `tier`, ranked; a verdict is the highest among the findings the change adds. +_TIER_RANK = {"warn": 1, "ask": 2, "block": 3} + + +def _tier_verdict(fresh: list[dict]) -> str | None: + """The verdict word ("" blocks) when every kept finding carries a known tier, else None: the exit code decides.""" + tiers = [item.get("tier") for item in fresh] + if not all(isinstance(tier, str) and tier in _TIER_RANK for tier in tiers): + return None + top = max(tiers, key=_TIER_RANK.__getitem__) + return "" if top == "block" else top + + def _baseline_findings(ctx: GateContext, script: Path, material: dict, started: float) -> list[dict]: """What the script finds in the baseline text of the change's files; empty when it cannot say. - A new file has no baseline and is left out. A run that fails, times out, prints no findings - document, or has no budget left contributes nothing, which errs toward blocking. + A new file has no baseline and is left out. A renamed file is judged as it was before the change: + its old content at its OLD path, so a finding that exists because of the new name is not in the + baseline; findings are mapped back to the new path, where a content finding is the same one. + A run that fails, times out, prints no findings document, or has no budget left contributes + nothing, which errs toward blocking. """ - texts = {path: text for path in material["writes"] if (text := ctx.head_blob(path))} + writes, texts, back = material["writes"], {}, {} + for path in writes: + if not (text := ctx.head_blob(path)): + continue + old = ctx.renamed_from(path) + old = path if old in writes or old in texts else old # never shadow another file in the same run + texts[old], back[old] = text, path remaining = _SCRIPT_TIMEOUT_SECONDS - (time.monotonic() - started) if not texts or remaining <= 0: return [] @@ -1038,7 +1121,9 @@ def _baseline_findings(ctx: GateContext, script: Path, material: dict, started: proc = _spawn(script, ctx, {**material, "writes": texts, "baseline": True}, remaining) except (subprocess.TimeoutExpired, OSError): return [] - return _findings_document(proc.stdout or "") or [] + return [ + {**item, "path": back.get(item["path"], item["path"])} for item in _findings_document(proc.stdout or "") or [] + ] def _exit_verdict(script: Path, proc: subprocess.CompletedProcess[str]) -> GateResult: @@ -1062,7 +1147,7 @@ def _exit_verdict(script: Path, proc: subprocess.CompletedProcess[str]) -> GateR def _judge_findings( ctx: GateContext, script: Path, material: dict, proc: subprocess.CompletedProcess[str], started: float ) -> GateResult: - """Judge only the findings the change introduces; the change-run's exit code is the verdict for them.""" + """Judge only the findings the change introduces: the highest tier among them, else the change-run's exit code.""" if proc.returncode not in (_SCRIPT_ALLOW, _SCRIPT_BLOCK, _SCRIPT_ASK, _SCRIPT_WARN): # A document followed by a crash or an unknown exit is undecided, never a clean pass. return _exit_verdict(script, proc) @@ -1075,7 +1160,9 @@ def _judge_findings( if not fresh or proc.returncode == _SCRIPT_ALLOW: return GateResult(allowed=True, detail=counts) lines = [f"{item['path']}:{item['line']}: {item['message']}" for item in fresh] - verdict = {_SCRIPT_ASK: "ask", _SCRIPT_WARN: "warn"}.get(proc.returncode, "") + verdict = _tier_verdict(fresh) + if verdict is None: + verdict = {_SCRIPT_ASK: "ask", _SCRIPT_WARN: "warn"}.get(proc.returncode, "") return GateResult( allowed=False, matches=lines, verdict=verdict, detail=counts, rules=_rule_ids(fresh), findings=fresh ) @@ -1084,7 +1171,7 @@ def _judge_findings( def _kind_script(ctx: GateContext, params: dict, event: str) -> GateResult: """Hand the material to the policy's own script and carry back its verdict. - The script reads `{"event", "repo_root", "writes": {path: text}}` on stdin -- the staged + The script reads `{"event", "repo_root", "writes": {path: text}}` on stdin (plus `deleted` at the floor) -- the staged blobs at commit and push, the write itself at tool use and at the turn's end -- so one script serves every surface the declarative kinds do, and reads them the same way. It answers with an exit code: 0 allows; 1 refuses, 3 asks, 4 warns, with its own words on stderr. @@ -1100,9 +1187,13 @@ def _kind_script(ctx: GateContext, params: dict, event: str) -> GateResult: if not script.is_file(): return GateResult(allowed=False, message=f"script gate: {named!r} is not installed{_UNDECIDED}") writes = {path: ctx.staged_blob(path) for path in ctx.staged_paths()} - if not writes: + # Only the floor hands a script the deleted paths: the contract every other event has is unchanged. + deleted = sorted(ctx.staged_paths("D")) if event == FLOOR_EVENT else [] + if not writes and not deleted: return GateResult(allowed=True) material = {"event": event, "repo_root": str(ctx.repo_root), "writes": writes} + if event == FLOOR_EVENT: + material["deleted"] = deleted if ctx.session: material["session"] = ctx.session started = time.monotonic() diff --git a/.chock/bin/launch.sh b/.chock/bin/launch.sh index 0b9fb10..2298183 100644 --- a/.chock/bin/launch.sh +++ b/.chock/bin/launch.sh @@ -21,17 +21,20 @@ configured="$(git config --get chock.python 2>/dev/null)" legacy= case "${OS:-}|${MSYSTEM:-}" in *Windows_NT*|*"|"?*) legacy=1 ;; esac [ "$runtime" = "-m" ] && legacy=1 +# A script starts with -E -s (-I less -P): no PYTHON* variable or user site changes it; its own folder stays on the path. +isolate=-Es +[ "$runtime" = "-m" ] && isolate= # Only the marker path sets it (to 9); everywhere else an inherited value is cleared, so it never names an fd. [ -n "$legacy" ] && { CHOCK_START_FD=; export CHOCK_START_FD; } for candidate in "$configured" python3 python py; do [ -n "$candidate" ] || continue if [ -n "$legacy" ]; then - if probed="$("$candidate" -c 'import sys; print("chock-python"); sys.exit(sys.version_info < (3, 11,))' /dev/null)" && [ "$probed" = "chock-python" ]; then - exec "$candidate" -X utf8 "$runtime" "$@" + if probed="$("$candidate" -I -c 'import sys; print("chock-python"); sys.exit(sys.version_info < (3, 11,))' /dev/null)" && [ "$probed" = "chock-python" ]; then + exec "$candidate" ${isolate:+"$isolate"} -X utf8 "$runtime" "$@" fi elif command -v "$candidate" >/dev/null 2>&1; then exec 3>&1 - marker="$(CHOCK_START_FD=9 "$candidate" -X utf8 "$runtime" "$@" 9>&1 1>&3 3>&-)" + marker="$(CHOCK_START_FD=9 "$candidate" ${isolate:+"$isolate"} -X utf8 "$runtime" "$@" 9>&1 1>&3 3>&-)" status=$? exec 3>&- [ "$marker" = "chock-python" ] && exit "$status" diff --git a/chock.lock b/chock.lock index ff486dd..c036436 100644 --- a/chock.lock +++ b/chock.lock @@ -1,5 +1,5 @@ { "lockfile_version": "2", - "engine": ">=0.1,<0.2", + "engine": ">=1.2,<2", "packs": [] }