kwik-e-gate 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,451 @@
1
+ """Self-contained deterministic repository runner; copied byte-for-byte by init."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import json
7
+ import os
8
+ import signal
9
+ import subprocess
10
+ import sys
11
+ import threading
12
+ import time
13
+ from pathlib import Path
14
+
15
+ # The copied runner has the same minimum runtime as the installed CLI. This guard is a
16
+ # runtime check on whatever interpreter actually invokes the standalone copied file
17
+ # (which can be an older system python3, not the pinned venv), so it is not dead code
18
+ # even though pyproject.toml's target-version is already >=3.11.
19
+ if sys.version_info < (3, 11): # noqa: UP036
20
+ raise SystemExit("Hermes Gate runner requires Python 3.11 or newer; use that interpreter to run this file.")
21
+
22
+ import tomllib
23
+
24
+ RUNNER_VERSION = "0.4.0"
25
+ OUTPUT_CAP = 65536
26
+ # Git's canonical empty tree: diffing it against HEAD reviews every committed byte.
27
+ EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
28
+ # Child stages read the resolved review range so nested `diff-check` runs review the
29
+ # same bytes the parent selected. Empty means the default worktree/index/untracked scope.
30
+ RANGE_ENV = "HERMES_GATE_RANGE"
31
+ BASE_ENV = "HERMES_GATE_BASE"
32
+
33
+
34
+ class RangeError(RuntimeError):
35
+ """The requested review range could not be resolved against this checkout."""
36
+
37
+
38
+ def _root() -> Path:
39
+ result = subprocess.run(
40
+ ["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=False
41
+ )
42
+ if result.returncode:
43
+ raise RuntimeError("not a Git repository")
44
+ return Path(result.stdout.strip()).resolve()
45
+
46
+
47
+ def _changed(root: Path) -> list[str]:
48
+ values: set[str] = set()
49
+ for args in (
50
+ ("diff", "--name-only", "-z"),
51
+ ("diff", "--cached", "--name-only", "-z"),
52
+ ("ls-files", "--others", "--exclude-standard", "-z"),
53
+ ):
54
+ proc = subprocess.run(["git", "-C", str(root), *args], capture_output=True, check=False)
55
+ values.update(x.decode("utf-8", "surrogateescape") for x in proc.stdout.split(b"\0") if x)
56
+ return sorted(values)
57
+
58
+
59
+ def _range_spec(root: Path, base: str | None, whole_tree: bool) -> str:
60
+ """Resolve the requested review range into a single Git diff revision argument."""
61
+ if whole_tree:
62
+ return f"{EMPTY_TREE}..HEAD"
63
+ if base is None:
64
+ # Only an omitted base selects the local worktree, index and untracked scope.
65
+ return ""
66
+ if not base.strip():
67
+ # An explicitly empty base is a misconfiguration, not a request for the local
68
+ # scope: a hosted rail whose base expression resolved to nothing would otherwise
69
+ # review a pristine checkout and report a pass over zero bytes.
70
+ raise RangeError(
71
+ "base revision is empty; omit --base and HERMES_GATE_BASE for the local "
72
+ "worktree scope, or name a revision"
73
+ )
74
+ resolved = subprocess.run(
75
+ ["git", "-C", str(root), "rev-parse", "--verify", "--quiet", f"{base}^{{commit}}"],
76
+ capture_output=True,
77
+ text=True,
78
+ check=False,
79
+ )
80
+ revision = resolved.stdout.strip()
81
+ if resolved.returncode or not revision:
82
+ raise RangeError(
83
+ f"base revision {base!r} is not present in this checkout; "
84
+ "fetch it (actions/checkout fetch-depth: 0) before running the gate"
85
+ )
86
+ # Three dots compares the merge base with HEAD, so the range holds only the
87
+ # changes this head introduced, whether HEAD is the head or the merge commit.
88
+ return f"{revision}...HEAD"
89
+
90
+
91
+ def _range_changed(root: Path, spec: str) -> list[str]:
92
+ proc = subprocess.run(
93
+ ["git", "-C", str(root), "diff", "--name-only", "-z", spec],
94
+ capture_output=True,
95
+ check=False,
96
+ )
97
+ if proc.returncode:
98
+ detail = proc.stderr.decode("utf-8", "replace").strip() or "git diff failed"
99
+ raise RangeError(f"cannot compare {spec!r}: {detail}")
100
+ return sorted(x.decode("utf-8", "surrogateescape") for x in proc.stdout.split(b"\0") if x)
101
+
102
+
103
+ def _match(path: str, pattern: str) -> bool:
104
+ return fnmatch.fnmatch(path, pattern) or (
105
+ pattern.startswith("**/") and fnmatch.fnmatch(path, pattern[3:])
106
+ )
107
+
108
+
109
+ def run(
110
+ mode: str,
111
+ *,
112
+ root: Path | None = None,
113
+ files: list[str] | None = None,
114
+ base: str | None = None,
115
+ whole_tree: bool = False,
116
+ ) -> dict[str, object]:
117
+ started = time.monotonic()
118
+ root = (root or _root()).resolve()
119
+ config_path = root / ".hermes" / "gate.toml"
120
+ if not config_path.is_file():
121
+ return _result(mode, "NOT_CONFIGURED", started, [], "run kwik-e-gate init")
122
+ try:
123
+ config = tomllib.loads(config_path.read_text(encoding="utf-8"))
124
+ except (OSError, tomllib.TOMLDecodeError) as exc:
125
+ return _result(mode, "ERROR", started, [], f"invalid profile: {exc}")
126
+ spec = ""
127
+ try:
128
+ spec = _range_spec(root, base, whole_tree)
129
+ if files is not None:
130
+ paths = list(files)
131
+ elif spec:
132
+ paths = _range_changed(root, spec)
133
+ else:
134
+ # Default, and the only local behaviour: worktree, index and untracked bytes.
135
+ paths = _changed(root)
136
+ except RangeError as exc:
137
+ return _result(mode, "ERROR", started, [], str(exc), range_spec=spec)
138
+ paths = [path for path in paths if os.path.lexists(root / path)]
139
+ exclusions = config.get("gate", {}).get("exclusions", [])
140
+ paths = [path for path in paths if not any(_match(path, pattern) for pattern in exclusions)]
141
+ if mode == "fast" and not paths:
142
+ return _result(mode, "NOT_APPLICABLE", started, [], "no changed files")
143
+ commands = list(config.get(mode, []))
144
+ if not commands:
145
+ return _result(mode, "NOT_CONFIGURED", started, [], f"no [[{mode}]] commands")
146
+ budget = (
147
+ float(config.get("gate", {}).get("fast_budget_seconds", 8.0)) if mode == "fast" else None
148
+ )
149
+ environment = {**os.environ, RANGE_ENV: spec}
150
+ checks: list[dict[str, object]] = []
151
+ executed = 0
152
+ failed: list[str] = []
153
+ invalid: list[str] = []
154
+ for index, command in enumerate(commands):
155
+ globs = command.get("globs", ["**/*"])
156
+ selected = [path for path in paths if any(_match(path, pattern) for pattern in globs)]
157
+ if mode == "fast" and not selected:
158
+ # Fast keeps its original selection guard: a stage whose globs match nothing
159
+ # is skipped outright, whether or not its argv reads {files}, so a narrow
160
+ # fast stage never runs against an unrelated edit or eats the budget.
161
+ continue
162
+ raw_argv = command.get("argv", [])
163
+ # Validate the container before converting it: a scalar argv must be reported as
164
+ # this stage's error, not raise out of the loop and deny the caller a receipt.
165
+ declared = list(raw_argv) if isinstance(raw_argv, list) else []
166
+ name = str(command.get("name", declared[0] if declared else f"{mode}[{index}]"))
167
+ if (
168
+ not isinstance(raw_argv, list)
169
+ or not declared
170
+ or any(not isinstance(part, str) for part in declared)
171
+ ):
172
+ reason = "argv must be a non-empty string array"
173
+ # One unusable declaration is that stage's error; the remaining declared
174
+ # stages still owe the caller a result.
175
+ if mode == "fast":
176
+ return _result(mode, "ERROR", started, checks, reason, range_spec=spec)
177
+ checks.append(
178
+ {"name": name, "argv": declared, "status": "ERROR", "reason": reason}
179
+ )
180
+ invalid.append(name)
181
+ continue
182
+ if not selected and "{files}" in declared:
183
+ # A file-driven stage with nothing to read checks no bytes; recording it as a
184
+ # pass is how a hosted checkout used to report a green gate over nothing.
185
+ checks.append({
186
+ "name": name,
187
+ "argv": declared,
188
+ "status": "NOT_APPLICABLE",
189
+ "reason": "no selected files for this stage",
190
+ })
191
+ continue
192
+ argv: list[str] = []
193
+ for part in declared:
194
+ argv.extend(selected if part == "{files}" else [part])
195
+ if not argv:
196
+ reason = "argv must be a non-empty string array"
197
+ if mode == "fast":
198
+ return _result(mode, "ERROR", started, checks, reason, range_spec=spec)
199
+ checks.append({"name": name, "argv": declared, "status": "ERROR", "reason": reason})
200
+ invalid.append(name)
201
+ continue
202
+ elapsed = time.monotonic() - started
203
+ timeout = float(command.get("timeout_seconds", 8.0))
204
+ if budget is not None:
205
+ timeout = min(timeout, max(0.01, budget - elapsed))
206
+ check = _execute(argv, root, timeout, name, environment)
207
+ checks.append(check)
208
+ executed += 1
209
+ if check["status"] != "PASS":
210
+ # Fast keeps its first-failure exit so the local budget still holds; full owes
211
+ # the caller the result of every declared stage.
212
+ if mode == "fast":
213
+ return _result(
214
+ mode, "FAIL", started, checks, str(check.get("reason", "check failed")),
215
+ range_spec=spec,
216
+ )
217
+ failed.append(name)
218
+ if budget is not None and time.monotonic() - started >= budget:
219
+ return _result(mode, "FAIL", started, checks, "fast budget exhausted", range_spec=spec)
220
+ if invalid:
221
+ reason = "unusable stage declarations: " + ", ".join(invalid)
222
+ if failed:
223
+ reason += "; failed stages: " + ", ".join(failed)
224
+ return _result(mode, "ERROR", started, checks, reason, range_spec=spec)
225
+ if failed:
226
+ return _result(
227
+ mode, "FAIL", started, checks, "failed stages: " + ", ".join(failed), range_spec=spec
228
+ )
229
+ if not executed:
230
+ return _result(
231
+ mode, "NOT_APPLICABLE", started, checks, "no commands matched changed files",
232
+ range_spec=spec,
233
+ )
234
+ return _result(mode, "PASS", started, checks, "", range_spec=spec)
235
+
236
+
237
+ def _execute(
238
+ argv: list[str],
239
+ root: Path,
240
+ timeout: float,
241
+ name: str,
242
+ environment: dict[str, str] | None = None,
243
+ ) -> dict[str, object]:
244
+ started = time.monotonic()
245
+ try:
246
+ proc = subprocess.Popen(
247
+ argv,
248
+ cwd=root,
249
+ env=environment,
250
+ stdin=subprocess.DEVNULL,
251
+ stdout=subprocess.PIPE,
252
+ stderr=subprocess.PIPE,
253
+ start_new_session=True,
254
+ )
255
+ except OSError as exc:
256
+ # A command that cannot be launched at all - missing, not executable, or the
257
+ # wrong binary format - is this stage's failure, not the whole gate's.
258
+ detail = "executable unavailable" if isinstance(exc, FileNotFoundError) else str(exc)
259
+ return {"name": name, "argv": argv, "status": "FAIL", "reason": detail}
260
+
261
+ stdout_capture: dict[str, object] = {"data": b"", "total": 0}
262
+ stderr_capture: dict[str, object] = {"data": b"", "total": 0}
263
+ assert proc.stdout is not None
264
+ assert proc.stderr is not None
265
+ threads = [
266
+ threading.Thread(
267
+ target=_drain_bounded,
268
+ args=(proc.stdout, OUTPUT_CAP // 2, stdout_capture),
269
+ daemon=True,
270
+ ),
271
+ threading.Thread(
272
+ target=_drain_bounded,
273
+ args=(proc.stderr, OUTPUT_CAP // 2, stderr_capture),
274
+ daemon=True,
275
+ ),
276
+ ]
277
+ for thread in threads:
278
+ thread.start()
279
+
280
+ deadline = started + timeout
281
+ while proc.poll() is None or any(thread.is_alive() for thread in threads):
282
+ remaining = deadline - time.monotonic()
283
+ if remaining <= 0:
284
+ break
285
+ time.sleep(min(0.01, remaining))
286
+ timed_out = proc.poll() is None or any(thread.is_alive() for thread in threads)
287
+ if timed_out:
288
+ try:
289
+ os.killpg(proc.pid, signal.SIGTERM)
290
+ except ProcessLookupError:
291
+ pass
292
+ try:
293
+ proc.wait(timeout=0.25)
294
+ except subprocess.TimeoutExpired:
295
+ pass
296
+ try:
297
+ os.killpg(proc.pid, signal.SIGKILL)
298
+ except ProcessLookupError:
299
+ pass
300
+ if proc.poll() is None:
301
+ proc.wait()
302
+ for thread in threads:
303
+ thread.join(timeout=0.5)
304
+ return {"name": name, "argv": argv, "status": "FAIL", "reason": "timeout"}
305
+
306
+ for thread in threads:
307
+ thread.join()
308
+ stdout = bytes(stdout_capture["data"])
309
+ stderr = bytes(stderr_capture["data"])
310
+ total_output = int(stdout_capture["total"]) + int(stderr_capture["total"])
311
+ return {
312
+ "name": name,
313
+ "argv": argv,
314
+ "status": "PASS" if proc.returncode == 0 else "FAIL",
315
+ "returncode": proc.returncode,
316
+ "elapsed_ms": round((time.monotonic() - started) * 1000),
317
+ "stdout": stdout.decode("utf-8", "replace"),
318
+ "stderr": stderr.decode("utf-8", "replace"),
319
+ "output_truncated": total_output > len(stdout) + len(stderr),
320
+ }
321
+
322
+
323
+ def _drain_bounded(pipe, cap: int, capture: dict[str, object]) -> None:
324
+ kept = bytearray()
325
+ total = 0
326
+ try:
327
+ while chunk := pipe.read(65536):
328
+ total += len(chunk)
329
+ remaining = cap - len(kept)
330
+ if remaining > 0:
331
+ kept.extend(chunk[:remaining])
332
+ finally:
333
+ pipe.close()
334
+ capture["data"] = bytes(kept)
335
+ capture["total"] = total
336
+
337
+
338
+ def _diff_check(root: Path, paths: list[str]) -> int:
339
+ """Check selected worktree, index and untracked bytes using Git's whitespace rules."""
340
+ if not paths:
341
+ return 0
342
+ git = ["git", "--literal-pathspecs", "-C", str(root)]
343
+ review_range = os.environ.get(RANGE_ENV, "")
344
+ if review_range:
345
+ # A hosted checkout has no worktree or index changes, so the committed range is
346
+ # the only thing worth checking; the parent resolved it once for every stage.
347
+ result = subprocess.run(
348
+ [*git, "diff", "--check", review_range, "--", *paths], check=False
349
+ )
350
+ return result.returncode
351
+ for flags in ([], ["--cached"]):
352
+ result = subprocess.run([*git, "diff", *flags, "--check", "--", *paths], check=False)
353
+ if result.returncode:
354
+ return result.returncode
355
+ untracked = subprocess.run(
356
+ [*git, "ls-files", "--others", "--exclude-standard", "-z", "--", *paths],
357
+ capture_output=True, check=False,
358
+ )
359
+ if untracked.returncode:
360
+ sys.stderr.buffer.write(untracked.stderr)
361
+ return untracked.returncode
362
+ for raw in untracked.stdout.split(b"\0"):
363
+ if not raw:
364
+ continue
365
+ path = root / os.fsdecode(raw)
366
+ # Git stores a symlink target, not the contents of its destination.
367
+ if path.is_symlink() or not path.is_file():
368
+ continue
369
+ result = subprocess.run(
370
+ [*git, "diff", "--no-index", "--check", "--", os.devnull, str(path)],
371
+ check=False,
372
+ )
373
+ # --no-index implies --exit-code: 1 means a clean new-file diff;
374
+ # --check reports whitespace errors with bit 2 set.
375
+ if result.returncode not in (0, 1):
376
+ return result.returncode
377
+ return 0
378
+
379
+
380
+ def _result(
381
+ mode: str,
382
+ status: str,
383
+ started: float,
384
+ checks: list[dict[str, object]],
385
+ reason: str,
386
+ *,
387
+ range_spec: str = "",
388
+ ) -> dict[str, object]:
389
+ return {
390
+ "schema": "hermes-gate/runner-v1",
391
+ "runner_version": RUNNER_VERSION,
392
+ "command": mode,
393
+ "status": status,
394
+ "elapsed_ms": round((time.monotonic() - started) * 1000),
395
+ "checks": checks,
396
+ "range": range_spec,
397
+ "reason": reason,
398
+ }
399
+
400
+
401
+ USAGE = "usage: runner.py fast|full [--base REV | --all]"
402
+
403
+
404
+ def main(argv: list[str] | None = None) -> int:
405
+ args = list(argv if argv is not None else sys.argv[1:])
406
+ if args and args[0] == "diff-check":
407
+ return _diff_check(_root(), args[1:])
408
+ if not args or args[0] not in {"fast", "full"}:
409
+ print(json.dumps({"status": "ERROR", "reason": USAGE}))
410
+ return 2
411
+ mode, rest = args[0], args[1:]
412
+ # Absent and empty are different requests: absent selects the local scope, while a
413
+ # variable that is set but blank is kept so it fails clearly below instead of being
414
+ # mistaken for "no base". An explicit --base still overrides the environment.
415
+ environment_base = os.environ.get(BASE_ENV)
416
+ base = environment_base.strip() if environment_base is not None else None
417
+ base_source = BASE_ENV
418
+ whole_tree = False
419
+ while rest:
420
+ option = rest.pop(0)
421
+ if option == "--all":
422
+ whole_tree = True
423
+ elif option == "--base":
424
+ if not rest:
425
+ print(json.dumps({"status": "ERROR", "reason": "--base needs a revision"}))
426
+ return 2
427
+ base = rest.pop(0)
428
+ base_source = "--base"
429
+ elif option.startswith("--base="):
430
+ base = option.split("=", 1)[1]
431
+ base_source = "--base"
432
+ else:
433
+ print(json.dumps({"status": "ERROR", "reason": f"unknown option {option!r}; {USAGE}"}))
434
+ return 2
435
+ if base is not None and not base.strip():
436
+ print(json.dumps({
437
+ "status": "ERROR",
438
+ "reason": f"{base_source} is set but empty; omit it for the local worktree scope "
439
+ "or name a revision",
440
+ }))
441
+ return 2
442
+ if whole_tree and base is not None:
443
+ print(json.dumps({"status": "ERROR", "reason": "--all and --base are exclusive"}))
444
+ return 2
445
+ result = run(mode, base=base, whole_tree=whole_tree)
446
+ print(json.dumps(result, sort_keys=True))
447
+ return 0 if result["status"] in {"PASS", "NOT_APPLICABLE"} else 1
448
+
449
+
450
+ if __name__ == "__main__":
451
+ raise SystemExit(main())
kwik_e_gate/routing.py ADDED
@@ -0,0 +1,77 @@
1
+ """Explainable local gate selection. No subprocesses, file reads or model calls.
2
+
3
+ Interpret change paths against the repository's declared contract. The policy can
4
+ broaden checks; it never invents commands, installs tools, or claims semantic review.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import PurePosixPath
10
+ from typing import Any
11
+
12
+ from .config import GateConfig, _matches
13
+
14
+ _CONTRACTS = {
15
+ "pyproject.toml", "setup.py", "setup.cfg", "tox.ini", "pytest.ini",
16
+ "package.json", "package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml",
17
+ "yarn.lock", "bun.lock", "bun.lockb", "uv.lock", "poetry.lock", "Pipfile",
18
+ "Pipfile.lock", "Cargo.toml", "Cargo.lock", "go.mod", "go.sum", "Gemfile",
19
+ "Gemfile.lock", "Makefile", "Justfile", "Dockerfile", "tsconfig.json",
20
+ "pyrightconfig.json", "ruff.toml", ".ruff.toml", "pygate.toml",
21
+ "quick-gate.config.json", "conftest.py",
22
+ }
23
+ _SENSITIVE = (
24
+ "**/auth/**", "**/security/**", "**/migrations/**", "**/schema/**",
25
+ "**/schemas/**", "**/*auth*.*", "**/*permission*.*", "**/*crypto*.*",
26
+ )
27
+
28
+
29
+ def select(config: GateConfig, paths: list[str], *, requested: str = "auto") -> dict[str, Any]:
30
+ """Pure, deterministic routing; repository globs extend conservative defaults."""
31
+ if requested not in {"auto", "fast", "full"}:
32
+ raise ValueError("mode must be auto, fast or full")
33
+ evidence: dict[str, list[str]] = {}
34
+ review_paths: list[str] = []
35
+ for path in sorted(set(paths)):
36
+ item = PurePosixPath(path)
37
+ name = item.name
38
+ sensitive = any(_matches(path, pattern) for pattern in _SENSITIVE)
39
+ category = ""
40
+ if path.startswith((".hermes/", ".github/workflows/", ".github/actions/")):
41
+ category = "gate-or-ci-contract"
42
+ elif name in _CONTRACTS or name.startswith("requirements") or ".config." in name:
43
+ category = "project-or-dependency-contract"
44
+ elif (any(part in {"test", "tests", "__tests__"} for part in item.parts)
45
+ or name.startswith("test_") or ".test." in name or ".spec." in name):
46
+ category = "tests"
47
+ elif sensitive:
48
+ category = "sensitive-change"
49
+ elif any(_matches(path, pattern) for pattern in config.routing_full_globs):
50
+ category = "repository-full-policy"
51
+ if category:
52
+ evidence.setdefault(category, []).append(path)
53
+ if (sensitive or name in {"AGENTS.md", "CLAUDE.md"}
54
+ or any(_matches(path, p) for p in config.routing_review_globs)):
55
+ review_paths.append(path)
56
+ mode = "full" if requested == "auto" and evidence else (
57
+ "fast" if requested == "auto" else requested
58
+ )
59
+ reason = ("broader impact requires the full declared contract" if evidence
60
+ else "ordinary change uses applicable fast stages")
61
+ if requested != "auto":
62
+ reason = f"explicit {requested} mode"
63
+ included = [path for path in sorted(set(paths)) if config.included(path)]
64
+ stages = config.fast if mode == "fast" else config.full
65
+ selected = [s.name for s in stages if mode == "full" or s.applies(included)]
66
+ skipped = [s.name for s in stages if s.name not in selected]
67
+ return {
68
+ "schema": "kwik-gate/routing-v1", "requested_mode": requested, "mode": mode,
69
+ "reason": reason, "evidence": evidence,
70
+ "adapter": config.adapter.name if config.adapter.enabled else "native",
71
+ "selected_stages": [] if config.adapter.enabled else selected,
72
+ "skipped_stages": [] if config.adapter.enabled else skipped,
73
+ "stage_scope": "all included inputs" if mode == "full" else "selected changed paths",
74
+ "review_recommended": bool(review_paths), "review_paths": review_paths,
75
+ "review_required_at_boundary": config.review_required,
76
+ "review_executed": False,
77
+ }
@@ -0,0 +1 @@
1
+