Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
72 commits
Select commit Hold shift + click to select a range
3970386
feat(lock): derive and enforce chock.lock's engine constraint (IR-F71)
jothimani-rajendran Nov 12, 2026
f57be53
fix(lock): finish the legacy-constraint note's sentence
jothimani-rajendran Nov 12, 2026
7a5dccd
chock add: default to the catalog release tag (W1-B)
jothimani-rajendran Nov 12, 2026
47be857
test(lock): import chock once in the engine-constraint tests
jothimani-rajendran Nov 12, 2026
2f9fe91
chock add: import the engine version once (CodeQL py/import-and-impor…
jothimani-rajendran Nov 12, 2026
7e58a4e
doctor: --live runs each installed pre-tool hook on a canary and a ha…
jothimani-rajendran Nov 12, 2026
180213a
fix: say each defaulted manifest field once, with its path; ASCII sym…
jothimani-rajendran Nov 12, 2026
17a5e61
refactor(lock): move the engine constraint to lock_engine.py
jothimani-rajendran Nov 12, 2026
80849b7
pin: keep pin.py within the 300-line budget; match tag refs exactly
jothimani-rajendran Nov 12, 2026
9d4a7d0
doctor --live: run only chock's own hook commands, and only on this e…
jothimani-rajendran Nov 12, 2026
3f29710
Merge W1-A: derive and enforce chock.lock's engine constraint (IR-F71)
jothimani-rajendran Nov 12, 2026
9f8e902
Merge W1-B: chock add defaults to the catalog release tag
jothimani-rajendran Nov 12, 2026
85d0034
feat(check): chock check --floor judges a pull request with its base'…
jothimani-rajendran Nov 12, 2026
7ce40e6
Merge W1-D: chock doctor --live runs chock's own hooks on a canary
jothimani-rajendran Nov 12, 2026
1a60f55
refactor: keep the warn/error print lines identical to main
jothimani-rajendran Nov 12, 2026
ff2e9ab
test(floor): refresh plugin goldens and fit gate-dsl.md in its budget
jothimani-rajendran Nov 12, 2026
26d4a89
Merge W1-C: each defaulted field said once with its path; ASCII symbo…
jothimani-rajendran Nov 12, 2026
b064d6b
feat: chock emit --managed claude_code writes a managed drop-in and i…
jothimani-rajendran Nov 12, 2026
f40081c
fix(floor): close the review's bypasses in chock check --floor (W2-A1r)
jothimani-rajendran Nov 12, 2026
25a1b07
fix: managed emit takes its interpreter and failure choice from the a…
jothimani-rajendran Nov 12, 2026
66c6777
feat(floor): control-plane rule replaces tamper rules; judge base..he…
jothimani-rajendran Nov 12, 2026
2c98067
test: split the managed emit tests and keep the docs within their bud…
jothimani-rajendran Nov 12, 2026
365f7ed
test(floor): split the floor attack tests to fit the 300-line budget
jothimani-rajendran Nov 12, 2026
ee4ccc2
fix: isolate every child interpreter the hook runtime starts; deploy.…
jothimani-rajendran Nov 13, 2026
0cf04b3
fix: the hook launcher starts its runtime with -E -s
jothimani-rajendran Nov 13, 2026
8e28891
fix(floor): whole agent folders, symlink-aware matching, undecided re…
jothimani-rajendran Nov 13, 2026
b965412
Merge W2-B1: chock emit --managed claude_code; isolated child interpr…
jothimani-rajendran Nov 13, 2026
e66db5c
test(cli): refresh the help golden for the --floor caveat
jothimani-rajendran Nov 13, 2026
c4af05a
Merge W2-A1: chock check --floor (preview), a control-plane rule and …
jothimani-rajendran Nov 13, 2026
7a29d71
refactor(floor): move Outcome into floor_outcome to break the import …
jothimani-rajendran Nov 13, 2026
43def03
Merge W2-A1 fix: Outcome moves to floor_outcome.py, ending the import…
jothimani-rajendran Nov 13, 2026
4a60c43
chore: sync the compiled runtime, goldens, lockfile and hook configs …
jothimani-rajendran Nov 14, 2026
02c713f
fix(floor): close the control plane under links; history, attributes,…
jothimani-rajendran Nov 14, 2026
15c2907
test(floor): drop unused imports and a world-readable chmod in the pa…
jothimani-rajendran Nov 14, 2026
7d8947e
Merge W2-A1v2.2: the floor's control plane is closed under links, or …
jothimani-rajendran Nov 14, 2026
d232603
Floor gate G1, GT-1: regression tests for links, history and attributes
jothimani-rajendran Nov 14, 2026
de7cfa7
Floor gate GT-2: pattern, config, exit, ordinary and docs tests
jothimani-rajendran Nov 14, 2026
eaa9a77
Floor: a link above the plane carries on when it opens only plane paths
jothimani-rajendran Nov 14, 2026
b1a1426
Merge GT-1: floor gate tests for links, history and attributes; a lin…
jothimani-rajendran Nov 14, 2026
39d73df
Merge w2a1-gate-patterns-exits into w2a1-gate-integrate
jothimani-rajendran Nov 14, 2026
b849879
test(floor): repair the gate docs map after GT-1 and GT-2 merge
jothimani-rajendran Nov 14, 2026
cc127e4
Merge GT-2 and GT-3: floor gate tests for patterns, config, SARIF, ex…
jothimani-rajendran Nov 14, 2026
30a5136
docs: 1.2.0 release docs and evidence (REL-D1)
jothimani-rajendran Nov 14, 2026
1e09bac
docs: witness ledger row for Cursor repo hooks (REL-D1)
jothimani-rajendran Nov 14, 2026
ec13f28
docs: keep the README inside its word and line budgets (REL-D1)
jothimani-rajendran Nov 14, 2026
6a39e58
docs: keep the comparison link in the README (REL-D1)
jothimani-rajendran Nov 14, 2026
67ca416
docs: Codex repo-hook witness row; the README sentence joins the ledg…
jothimani-rajendran Nov 15, 2026
65a4c17
docs: shorten the derived repo-hook sentence to fit the README word b…
jothimani-rajendran Nov 15, 2026
323ceb5
docs: group the derived repo-hook clients by the platform the ledger …
jothimani-rajendran Nov 15, 2026
cef2f2f
docs: restore the six FAQ entries and shrink the new README section (…
jothimani-rajendran Nov 15, 2026
692d56a
Merge REL-D1: 1.2.0 release docs and evidence (quick start without ha…
jothimani-rajendran Nov 15, 2026
2bd9893
gate: follow a git-reported rename for the baseline (E-1)
jothimani-rajendran Nov 15, 2026
f9abf6f
gate: keep context.py inside the 300-line review budget (E-1)
jothimani-rajendran Nov 15, 2026
bd4c1cd
gate: a script gate's verdict comes from the findings the change adds…
jothimani-rajendran Nov 15, 2026
f98263c
spec: keep gate-dsl.md inside the 300-line budget after the tier fiel…
jothimani-rajendran Nov 15, 2026
ca942f2
Merge E-1: the gate baseline follows a git-reported rename
jothimani-rajendran Nov 15, 2026
0637595
Merge E-2: a script gate verdict comes from the findings the change adds
jothimani-rajendran Nov 15, 2026
2fd4c1b
sync the compiled runtime, goldens, lockfile and hook configs
jothimani-rajendran Nov 15, 2026
876dfef
README: a figure of where Chock sits, under "How it works" (RD-7)
jothimani-rajendran Nov 16, 2026
5bf2cdb
README figure: say what dockerfile-compose-security flags
jothimani-rajendran Nov 16, 2026
c207c35
README figure: a layered sketch of the agent and where Chock meets it
jothimani-rajendran Nov 16, 2026
1cfa49b
README figure: draw every point where Chock meets the agent and the repo
jothimani-rajendran Nov 16, 2026
2a119d4
README: move the CI/MCP paragraph to architecture.md; git push box in…
jothimani-rajendran Nov 16, 2026
ffb87ca
README figure: markers on the drawing instead of a legend
jothimani-rajendran Nov 16, 2026
a161e0e
README figure: every agentseam event is a marker; filled where Chock …
jothimani-rajendran Nov 16, 2026
3e1fc56
README figure: a sixth chip for your own policy; heading says for exa…
jothimani-rajendran Nov 16, 2026
b39685c
README figure: the session as an ordered path with checkpoints
jothimani-rajendran Nov 16, 2026
a473e09
README figure: name each hook, loop after post-tool, join the MCP tag
jothimani-rajendran Nov 16, 2026
f15c861
README figure: a harness of component cards with hook badges on each
jothimani-rajendran Nov 16, 2026
1b10cf8
README figure: tighter harness, session and repo arrows, one-line badges
jothimani-rajendran Nov 16, 2026
a9fba49
Merge RD-7: a picture of a coding agent's harness and where Chock plu…
jothimani-rajendran Nov 16, 2026
8ecd63c
gate: a rename into a refused name is new, even when the content is o…
jothimani-rajendran Nov 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions .chock/bin/_chock_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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, '')
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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}')
Expand Down
2 changes: 1 addition & 1 deletion .chock/bin/claude_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -855,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():
Expand Down
2 changes: 1 addition & 1 deletion .chock/bin/codex_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -823,7 +823,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():
Expand Down
2 changes: 1 addition & 1 deletion .chock/bin/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,7 +721,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():
Expand Down
2 changes: 1 addition & 1 deletion .chock/bin/devin.py
Original file line number Diff line number Diff line change
Expand Up @@ -826,7 +826,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():
Expand Down
97 changes: 87 additions & 10 deletions .chock/bin/gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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],
Expand Down Expand Up @@ -395,8 +436,8 @@ def staged_blob(self, path: str) -> str:
return self._git("show", f"HEAD:{path}" if self.base else f":{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, or "" when the path is new in it; a renamed path reads its old path."""
return self._git("show", f"{self.base or 'HEAD'}:{self._renames().get(path, path)}")

def committed_blob(self, path: str) -> str:
"""The file as HEAD has it, or "" when HEAD does not."""
Expand Down Expand Up @@ -465,6 +506,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"):
Expand Down Expand Up @@ -496,7 +541,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._renames().get(path, path))
try:
return (self.repo_root / path).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
Expand Down Expand Up @@ -550,8 +595,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"})

Expand Down Expand Up @@ -959,6 +1008,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(
Expand All @@ -969,7 +1027,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,
)
Expand Down Expand Up @@ -1024,6 +1082,19 @@ 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.

Expand Down Expand Up @@ -1062,7 +1133,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)
Expand All @@ -1075,7 +1146,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
)
Expand All @@ -1084,7 +1157,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.
Expand All @@ -1100,9 +1173,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()
Expand Down
2 changes: 1 addition & 1 deletion .chock/bin/gemini_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -826,7 +826,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():
Expand Down
2 changes: 1 addition & 1 deletion .chock/bin/grok.py
Original file line number Diff line number Diff line change
Expand Up @@ -826,7 +826,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():
Expand Down
Loading
Loading