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.
- kwik_e_gate/__init__.py +3 -0
- kwik_e_gate/adapters.py +325 -0
- kwik_e_gate/binding.py +112 -0
- kwik_e_gate/classification.py +36 -0
- kwik_e_gate/claude_review.py +149 -0
- kwik_e_gate/cli.py +179 -0
- kwik_e_gate/codex_install.py +212 -0
- kwik_e_gate/command_detection.py +208 -0
- kwik_e_gate/config.py +231 -0
- kwik_e_gate/delegate_judge.py +211 -0
- kwik_e_gate/doctor.py +147 -0
- kwik_e_gate/engine.py +807 -0
- kwik_e_gate/execution.py +101 -0
- kwik_e_gate/gate_result.py +141 -0
- kwik_e_gate/gitstate.py +244 -0
- kwik_e_gate/hooks.py +207 -0
- kwik_e_gate/init_repo.py +646 -0
- kwik_e_gate/providers.py +194 -0
- kwik_e_gate/receipts.py +115 -0
- kwik_e_gate/repo_runner.py +451 -0
- kwik_e_gate/routing.py +77 -0
- kwik_e_gate/schemas/__init__.py +1 -0
- kwik_e_gate/schemas/gate-result-v1.schema.json +184 -0
- kwik_e_gate/status.py +24 -0
- kwik_e_gate/workflow.py +183 -0
- kwik_e_gate-0.4.0.dist-info/METADATA +163 -0
- kwik_e_gate-0.4.0.dist-info/RECORD +31 -0
- kwik_e_gate-0.4.0.dist-info/WHEEL +5 -0
- kwik_e_gate-0.4.0.dist-info/entry_points.txt +4 -0
- kwik_e_gate-0.4.0.dist-info/licenses/LICENSE +190 -0
- kwik_e_gate-0.4.0.dist-info/top_level.txt +1 -0
kwik_e_gate/execution.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import signal
|
|
5
|
+
import subprocess
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
MAX_OUTPUT_BYTES = 64 * 1024
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Execution:
|
|
16
|
+
argv: tuple[str, ...]
|
|
17
|
+
returncode: int | None
|
|
18
|
+
elapsed_ms: int
|
|
19
|
+
stdout: str
|
|
20
|
+
stderr: str
|
|
21
|
+
timed_out: bool = False
|
|
22
|
+
unavailable: bool = False
|
|
23
|
+
output_truncated: bool = False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def run_argv(
|
|
27
|
+
argv: Sequence[str],
|
|
28
|
+
*,
|
|
29
|
+
cwd: Path,
|
|
30
|
+
timeout_seconds: float,
|
|
31
|
+
output_cap: int = MAX_OUTPUT_BYTES,
|
|
32
|
+
env: dict[str, str] | None = None,
|
|
33
|
+
) -> Execution:
|
|
34
|
+
started = time.monotonic()
|
|
35
|
+
merged_env = os.environ.copy()
|
|
36
|
+
if env:
|
|
37
|
+
merged_env.update(env)
|
|
38
|
+
try:
|
|
39
|
+
proc = subprocess.Popen(
|
|
40
|
+
list(argv),
|
|
41
|
+
cwd=cwd,
|
|
42
|
+
stdin=subprocess.DEVNULL,
|
|
43
|
+
stdout=subprocess.PIPE,
|
|
44
|
+
stderr=subprocess.PIPE,
|
|
45
|
+
start_new_session=True,
|
|
46
|
+
env=merged_env,
|
|
47
|
+
)
|
|
48
|
+
except FileNotFoundError:
|
|
49
|
+
return Execution(
|
|
50
|
+
tuple(argv), None, _elapsed(started), "", "executable not found", unavailable=True
|
|
51
|
+
)
|
|
52
|
+
try:
|
|
53
|
+
stdout, stderr = proc.communicate(timeout=timeout_seconds)
|
|
54
|
+
except subprocess.TimeoutExpired:
|
|
55
|
+
try:
|
|
56
|
+
os.killpg(proc.pid, signal.SIGTERM)
|
|
57
|
+
except ProcessLookupError:
|
|
58
|
+
pass
|
|
59
|
+
try:
|
|
60
|
+
stdout, stderr = proc.communicate(timeout=0.25)
|
|
61
|
+
except subprocess.TimeoutExpired:
|
|
62
|
+
stdout = stderr = b""
|
|
63
|
+
try:
|
|
64
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
65
|
+
except ProcessLookupError:
|
|
66
|
+
pass
|
|
67
|
+
if proc.poll() is None:
|
|
68
|
+
stdout, stderr = proc.communicate()
|
|
69
|
+
return _result(argv, None, started, stdout, stderr, output_cap, timed_out=True)
|
|
70
|
+
return _result(argv, proc.returncode, started, stdout, stderr, output_cap)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _elapsed(started: float) -> int:
|
|
74
|
+
return round((time.monotonic() - started) * 1000)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _result(
|
|
78
|
+
argv: Sequence[str],
|
|
79
|
+
returncode: int | None,
|
|
80
|
+
started: float,
|
|
81
|
+
stdout: bytes,
|
|
82
|
+
stderr: bytes,
|
|
83
|
+
cap: int,
|
|
84
|
+
*,
|
|
85
|
+
timed_out: bool = False,
|
|
86
|
+
) -> Execution:
|
|
87
|
+
combined = len(stdout) + len(stderr)
|
|
88
|
+
if combined > cap:
|
|
89
|
+
stdout_cap = min(len(stdout), cap // 2)
|
|
90
|
+
stderr_cap = max(0, cap - stdout_cap)
|
|
91
|
+
stdout = stdout[:stdout_cap]
|
|
92
|
+
stderr = stderr[:stderr_cap]
|
|
93
|
+
return Execution(
|
|
94
|
+
tuple(argv),
|
|
95
|
+
returncode,
|
|
96
|
+
_elapsed(started),
|
|
97
|
+
stdout.decode("utf-8", "replace"),
|
|
98
|
+
stderr.decode("utf-8", "replace"),
|
|
99
|
+
timed_out=timed_out,
|
|
100
|
+
output_truncated=combined > cap,
|
|
101
|
+
)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from importlib import resources
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
RESULT_STATUSES = frozenset({"pass", "fail", "timeout", "error"})
|
|
8
|
+
CHECK_STATUSES = frozenset({"pass", "fail", "timeout", "missing", "error", "skipped"})
|
|
9
|
+
REQUIRED_FIELDS = (
|
|
10
|
+
"schema",
|
|
11
|
+
"status",
|
|
12
|
+
"snapshot_digest",
|
|
13
|
+
"checked_paths",
|
|
14
|
+
"checks",
|
|
15
|
+
"findings",
|
|
16
|
+
"command_versions",
|
|
17
|
+
"elapsed_ms",
|
|
18
|
+
"output_truncated",
|
|
19
|
+
"errors",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_schema() -> dict[str, Any]:
|
|
24
|
+
"""Load the packaged canonical gate-result/v1 schema using stdlib only."""
|
|
25
|
+
|
|
26
|
+
schema_resource = resources.files("kwik_e_gate").joinpath("schemas/gate-result-v1.schema.json")
|
|
27
|
+
value = json.loads(schema_resource.read_text(encoding="utf-8"))
|
|
28
|
+
if not isinstance(value, dict):
|
|
29
|
+
raise TypeError("packaged gate-result/v1 schema is not an object")
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def validate_gate_result(value: object) -> list[str]:
|
|
34
|
+
"""Return deterministic contract errors for the supported v1 schema."""
|
|
35
|
+
|
|
36
|
+
if not isinstance(value, dict):
|
|
37
|
+
return ["result must be an object"]
|
|
38
|
+
errors: list[str] = []
|
|
39
|
+
for field in REQUIRED_FIELDS:
|
|
40
|
+
if field not in value:
|
|
41
|
+
errors.append(f"missing required field: {field}")
|
|
42
|
+
if value.get("schema") != "gate-result/v1":
|
|
43
|
+
errors.append("schema must equal gate-result/v1")
|
|
44
|
+
if "version" in value and value["version"] != "gate-result/v1":
|
|
45
|
+
errors.append("deprecated version must equal gate-result/v1 when present")
|
|
46
|
+
if value.get("status") not in RESULT_STATUSES:
|
|
47
|
+
errors.append("status is not a gate-result/v1 status")
|
|
48
|
+
if not isinstance(value.get("snapshot_digest"), str) or not value.get("snapshot_digest"):
|
|
49
|
+
errors.append("snapshot_digest must be a non-empty string")
|
|
50
|
+
if "snapshot_digest_after" in value and not isinstance(
|
|
51
|
+
value["snapshot_digest_after"], (str, type(None))
|
|
52
|
+
):
|
|
53
|
+
errors.append("snapshot_digest_after must be a string or null when present")
|
|
54
|
+
if "snapshot_changed" in value and not isinstance(value["snapshot_changed"], bool):
|
|
55
|
+
errors.append("snapshot_changed must be a boolean when present")
|
|
56
|
+
if not isinstance(value.get("checked_paths"), list) or not all(
|
|
57
|
+
isinstance(item, str) for item in value.get("checked_paths", [])
|
|
58
|
+
):
|
|
59
|
+
errors.append("checked_paths must be an array of strings")
|
|
60
|
+
checks = value.get("checks")
|
|
61
|
+
if not isinstance(checks, list):
|
|
62
|
+
errors.append("checks must be an array")
|
|
63
|
+
else:
|
|
64
|
+
for index, check in enumerate(checks):
|
|
65
|
+
if not isinstance(check, dict):
|
|
66
|
+
errors.append(f"checks[{index}] must be an object")
|
|
67
|
+
continue
|
|
68
|
+
if not isinstance(check.get("name"), str) or not check.get("name"):
|
|
69
|
+
errors.append(f"checks[{index}].name must be a non-empty string")
|
|
70
|
+
if check.get("status") not in CHECK_STATUSES:
|
|
71
|
+
errors.append(f"checks[{index}].status is not a gate-result/v1 check status")
|
|
72
|
+
for field in ("argv", "elapsed_ms", "timed_out", "output_truncated"):
|
|
73
|
+
if field not in check:
|
|
74
|
+
errors.append(f"checks[{index}] is missing required field: {field}")
|
|
75
|
+
if "argv" in check and not (
|
|
76
|
+
isinstance(check["argv"], list)
|
|
77
|
+
and all(isinstance(item, str) for item in check["argv"])
|
|
78
|
+
):
|
|
79
|
+
errors.append(f"checks[{index}].argv must be an array of strings")
|
|
80
|
+
if "elapsed_ms" in check and not _non_negative_integer(check["elapsed_ms"]):
|
|
81
|
+
errors.append(f"checks[{index}].elapsed_ms must be a non-negative integer")
|
|
82
|
+
if "exit_code" in check and not _integer_or_null(check["exit_code"]):
|
|
83
|
+
errors.append(f"checks[{index}].exit_code must be an integer or null")
|
|
84
|
+
if "signal" in check and not (
|
|
85
|
+
check["signal"] is None
|
|
86
|
+
or isinstance(check["signal"], str)
|
|
87
|
+
or _integer(check["signal"])
|
|
88
|
+
):
|
|
89
|
+
errors.append(f"checks[{index}].signal must be an integer, string, or null")
|
|
90
|
+
for field in ("timed_out", "output_truncated"):
|
|
91
|
+
if field in check and not isinstance(check[field], bool):
|
|
92
|
+
errors.append(f"checks[{index}].{field} must be a boolean")
|
|
93
|
+
for field in ("findings", "errors"):
|
|
94
|
+
if not isinstance(value.get(field), list):
|
|
95
|
+
errors.append(f"{field} must be an array")
|
|
96
|
+
if isinstance(value.get("errors"), list) and not all(
|
|
97
|
+
isinstance(item, (str, dict)) for item in value["errors"]
|
|
98
|
+
):
|
|
99
|
+
errors.append("errors items must be strings or objects")
|
|
100
|
+
if not isinstance(value.get("command_versions"), dict):
|
|
101
|
+
errors.append("command_versions must be an object")
|
|
102
|
+
elif not all(
|
|
103
|
+
isinstance(name, str) and isinstance(version, (str, dict))
|
|
104
|
+
for name, version in value["command_versions"].items()
|
|
105
|
+
):
|
|
106
|
+
errors.append("command_versions values must be strings or objects")
|
|
107
|
+
elapsed = value.get("elapsed_ms")
|
|
108
|
+
if not _non_negative_integer(elapsed):
|
|
109
|
+
errors.append("elapsed_ms must be a non-negative integer")
|
|
110
|
+
if not isinstance(value.get("output_truncated"), bool):
|
|
111
|
+
errors.append("output_truncated must be a boolean")
|
|
112
|
+
if "diagnostics" in value and not isinstance(value["diagnostics"], list):
|
|
113
|
+
errors.append("diagnostics must be an array when present")
|
|
114
|
+
elif isinstance(value.get("diagnostics"), list) and not all(
|
|
115
|
+
isinstance(item, (str, dict)) for item in value["diagnostics"]
|
|
116
|
+
):
|
|
117
|
+
errors.append("diagnostics items must be strings or objects")
|
|
118
|
+
if "config_identity" in value and not isinstance(value["config_identity"], (str, dict)):
|
|
119
|
+
errors.append("config_identity must be a string or object when present")
|
|
120
|
+
for field in ("config_digest", "config_version", "package_version"):
|
|
121
|
+
if field in value and not isinstance(value[field], str):
|
|
122
|
+
errors.append(f"{field} must be a string when present")
|
|
123
|
+
if "state_dir" in value and not isinstance(value["state_dir"], (str, type(None))):
|
|
124
|
+
errors.append("state_dir must be a string or null when present")
|
|
125
|
+
return errors
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _integer(value: object) -> bool:
|
|
129
|
+
return (
|
|
130
|
+
isinstance(value, (int, float))
|
|
131
|
+
and not isinstance(value, bool)
|
|
132
|
+
and (not isinstance(value, float) or value.is_integer())
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _integer_or_null(value: object) -> bool:
|
|
137
|
+
return value is None or _integer(value)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _non_negative_integer(value: object) -> bool:
|
|
141
|
+
return _integer(value) and isinstance(value, (int, float)) and value >= 0
|
kwik_e_gate/gitstate.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import stat
|
|
7
|
+
import subprocess
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Iterable, Iterator
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from contextvars import ContextVar
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
GIT_TIMEOUT_SECONDS = 10.0
|
|
15
|
+
_GIT_DEADLINE: ContextVar[float | None] = ContextVar("hermes_gate_git_deadline", default=None)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GitError(RuntimeError):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ScopeError(GitError):
|
|
23
|
+
"""The committed scope cannot be selected without risking a false PASS."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ContentReadError(RuntimeError):
|
|
27
|
+
"""A path advertised bytes that could not be read faithfully."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@contextmanager
|
|
31
|
+
def git_query_budget(seconds: float) -> Iterator[None]:
|
|
32
|
+
"""Share a metadata-query deadline within a bounded hook transport."""
|
|
33
|
+
deadline = time.monotonic() + seconds
|
|
34
|
+
inherited = _GIT_DEADLINE.get()
|
|
35
|
+
token = _GIT_DEADLINE.set(min(deadline, inherited) if inherited is not None else deadline)
|
|
36
|
+
try:
|
|
37
|
+
yield
|
|
38
|
+
finally:
|
|
39
|
+
_GIT_DEADLINE.reset(token)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def git(root: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess[bytes]:
|
|
43
|
+
# Metadata queries need no optional monitor. A stalled daemon must not hang
|
|
44
|
+
# discovery before the workflow can issue its failure receipt.
|
|
45
|
+
argv = ["git", "-C", str(root), "-c", "core.fsmonitor=false", *args]
|
|
46
|
+
timeout = GIT_TIMEOUT_SECONDS
|
|
47
|
+
deadline = _GIT_DEADLINE.get()
|
|
48
|
+
if deadline is not None:
|
|
49
|
+
timeout = min(timeout, deadline - time.monotonic())
|
|
50
|
+
if timeout <= 0:
|
|
51
|
+
raise GitError("git metadata query budget exhausted")
|
|
52
|
+
try:
|
|
53
|
+
proc = subprocess.run(
|
|
54
|
+
argv, capture_output=True, check=False, timeout=timeout,
|
|
55
|
+
)
|
|
56
|
+
except subprocess.TimeoutExpired as exc:
|
|
57
|
+
# Timeout is an infrastructure failure even for expected nonzero queries
|
|
58
|
+
# such as an unborn HEAD or missing upstream. It cannot mean "no changes".
|
|
59
|
+
raise GitError(f"git metadata query timed out after {timeout:g}s") from exc
|
|
60
|
+
if check and proc.returncode:
|
|
61
|
+
raise GitError(proc.stderr.decode("utf-8", "replace").strip() or "git command failed")
|
|
62
|
+
return proc
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def repo_root(start: Path | str | None = None) -> Path | None:
|
|
66
|
+
cwd = Path(start or os.getcwd()).expanduser().resolve()
|
|
67
|
+
proc = git(cwd, "rev-parse", "--show-toplevel", check=False)
|
|
68
|
+
if proc.returncode:
|
|
69
|
+
return None
|
|
70
|
+
return Path(proc.stdout.decode().strip()).resolve()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def head(root: Path) -> str:
|
|
74
|
+
proc = git(root, "rev-parse", "HEAD", check=False)
|
|
75
|
+
return proc.stdout.decode().strip() if proc.returncode == 0 else "UNBORN"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def git_dir(root: Path) -> Path:
|
|
79
|
+
return Path(git(root, "rev-parse", "--absolute-git-dir").stdout.decode().strip()).resolve()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def changed_paths(root: Path) -> list[str]:
|
|
83
|
+
tracked = git(root, "diff", "--name-only", "-z", "--diff-filter=ACDMRTUXB", check=False)
|
|
84
|
+
staged = git(
|
|
85
|
+
root, "diff", "--cached", "--name-only", "-z", "--diff-filter=ACDMRTUXB", check=False
|
|
86
|
+
)
|
|
87
|
+
untracked = git(root, "ls-files", "--others", "--exclude-standard", "-z")
|
|
88
|
+
values: set[str] = set()
|
|
89
|
+
for payload in (tracked.stdout, staged.stdout, untracked.stdout):
|
|
90
|
+
values.update(
|
|
91
|
+
item.decode("utf-8", "surrogateescape") for item in payload.split(b"\0") if item
|
|
92
|
+
)
|
|
93
|
+
return sorted(values)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def staged_paths(root: Path) -> list[str]:
|
|
97
|
+
proc = git(
|
|
98
|
+
root, "diff", "--cached", "--name-only", "-z", "--diff-filter=ACDMRTUXB", check=False
|
|
99
|
+
)
|
|
100
|
+
return sorted(
|
|
101
|
+
item.decode("utf-8", "surrogateescape") for item in proc.stdout.split(b"\0") if item
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def scope(root: Path, *, base: str | None = None) -> tuple[list[str], str]:
|
|
106
|
+
"""Return changed paths and the exact commit that defines their comparison boundary."""
|
|
107
|
+
dirty = changed_paths(root)
|
|
108
|
+
if dirty:
|
|
109
|
+
if base is None:
|
|
110
|
+
upstream = git(
|
|
111
|
+
root, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}", check=False
|
|
112
|
+
)
|
|
113
|
+
parents = git(root, "rev-list", "--parents", "-n", "1", "HEAD", check=False)
|
|
114
|
+
if upstream.returncode and parents.returncode == 0 and len(parents.stdout.split()) > 2:
|
|
115
|
+
raise ScopeError("scope unresolved: HEAD is a merge commit with no upstream or --base")
|
|
116
|
+
return dirty, head(root)
|
|
117
|
+
resolved = _resolve_base(root, base)
|
|
118
|
+
committed = _diff_names(root, resolved, "HEAD")
|
|
119
|
+
return sorted(set(committed) | set(dirty)), resolved
|
|
120
|
+
if base is not None:
|
|
121
|
+
resolved = _resolve_base(root, base)
|
|
122
|
+
return _diff_names(root, resolved, "HEAD"), resolved
|
|
123
|
+
upstream = git(
|
|
124
|
+
root, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}", check=False
|
|
125
|
+
)
|
|
126
|
+
if upstream.returncode == 0:
|
|
127
|
+
base = git(root, "merge-base", "HEAD", upstream.stdout.decode().strip(), check=False)
|
|
128
|
+
if base.returncode == 0:
|
|
129
|
+
resolved = base.stdout.decode().strip()
|
|
130
|
+
return _diff_names(root, resolved, "HEAD"), resolved
|
|
131
|
+
parents = git(root, "rev-list", "--parents", "-n", "1", "HEAD", check=False)
|
|
132
|
+
if parents.returncode == 0 and len(parents.stdout.split()) > 2:
|
|
133
|
+
raise ScopeError("scope unresolved: HEAD is a merge commit with no upstream or --base")
|
|
134
|
+
parent = git(root, "rev-parse", "HEAD^", check=False)
|
|
135
|
+
if parent.returncode == 0:
|
|
136
|
+
resolved = parent.stdout.decode().strip()
|
|
137
|
+
return _diff_names(root, resolved, "HEAD"), resolved
|
|
138
|
+
tracked = git(root, "ls-files", "-z", check=False)
|
|
139
|
+
return (
|
|
140
|
+
sorted(item.decode("utf-8", "surrogateescape") for item in tracked.stdout.split(b"\0") if item),
|
|
141
|
+
head(root),
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def scope_paths(root: Path, *, base: str | None = None) -> list[str]:
|
|
146
|
+
"""Current dirty paths, otherwise committed paths since an explicit base, upstream, or parent."""
|
|
147
|
+
return scope(root, base=base)[0]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _resolve_base(root: Path, base: str) -> str:
|
|
151
|
+
resolved = git(root, "rev-parse", "--verify", "--quiet", f"{base}^{{commit}}", check=False)
|
|
152
|
+
if resolved.returncode:
|
|
153
|
+
raise ScopeError(f"scope unresolved: --base {base!r} is not a commit")
|
|
154
|
+
return resolved.stdout.decode().strip()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _diff_names(root: Path, base: str, target: str) -> list[str]:
|
|
158
|
+
proc = git(
|
|
159
|
+
root, "diff", "--name-only", "-z", "--diff-filter=ACDMRTUXB", base, target, check=False
|
|
160
|
+
)
|
|
161
|
+
return sorted(
|
|
162
|
+
item.decode("utf-8", "surrogateescape") for item in proc.stdout.split(b"\0") if item
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _path_digest(root: Path, relative: str) -> str:
|
|
167
|
+
path = root / relative
|
|
168
|
+
if not path.exists() and not path.is_symlink():
|
|
169
|
+
return "MISSING"
|
|
170
|
+
if path.is_symlink():
|
|
171
|
+
identity = "SYMLINK:" + os.readlink(path)
|
|
172
|
+
try:
|
|
173
|
+
target_stat = path.stat()
|
|
174
|
+
except FileNotFoundError:
|
|
175
|
+
return f"{identity}:MISSING"
|
|
176
|
+
except OSError as exc:
|
|
177
|
+
return f"{identity}:UNREADABLE:{type(exc).__name__}"
|
|
178
|
+
if not stat.S_ISREG(target_stat.st_mode):
|
|
179
|
+
target_type = "DIRECTORY" if stat.S_ISDIR(target_stat.st_mode) else "OTHER"
|
|
180
|
+
return f"{identity}:{target_type}"
|
|
181
|
+
try:
|
|
182
|
+
digest = _digest_exact(path, target_stat.st_size)
|
|
183
|
+
except OSError as exc:
|
|
184
|
+
return f"{identity}:UNREADABLE:{type(exc).__name__}"
|
|
185
|
+
return f"{identity}:FILE:{digest}"
|
|
186
|
+
if path.is_dir():
|
|
187
|
+
return "DIRECTORY"
|
|
188
|
+
try:
|
|
189
|
+
expected_size = path.stat().st_size
|
|
190
|
+
return _digest_exact(path, expected_size)
|
|
191
|
+
except OSError as exc:
|
|
192
|
+
raise ContentReadError(f"cannot read {relative}: {type(exc).__name__}") from exc
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _digest_exact(path: Path, expected_size: int) -> str:
|
|
196
|
+
digest = hashlib.sha256()
|
|
197
|
+
actual_size = 0
|
|
198
|
+
with path.open("rb") as handle:
|
|
199
|
+
while actual_size <= expected_size:
|
|
200
|
+
chunk = handle.read(min(1024 * 1024, expected_size - actual_size + 1))
|
|
201
|
+
if not chunk:
|
|
202
|
+
break
|
|
203
|
+
digest.update(chunk)
|
|
204
|
+
actual_size += len(chunk)
|
|
205
|
+
if actual_size != expected_size:
|
|
206
|
+
raise ContentReadError(
|
|
207
|
+
f"short read for {path}: expected {expected_size} bytes, got {actual_size}"
|
|
208
|
+
)
|
|
209
|
+
return digest.hexdigest()
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def snapshot(root: Path, paths: Iterable[str] | None = None) -> dict[str, str]:
|
|
213
|
+
selected = sorted(set(paths if paths is not None else changed_paths(root)))
|
|
214
|
+
return {path: _path_digest(root, path) for path in selected}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def session_changed_paths(root: Path, baseline: dict[str, str] | None) -> list[str]:
|
|
218
|
+
current_paths = changed_paths(root)
|
|
219
|
+
current = snapshot(root, current_paths)
|
|
220
|
+
if baseline is None:
|
|
221
|
+
return current_paths
|
|
222
|
+
return sorted(path for path, digest in current.items() if baseline.get(path) != digest)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def diff_digest(
|
|
226
|
+
root: Path, paths: Iterable[str] | None = None, *, base: str | None = None
|
|
227
|
+
) -> str:
|
|
228
|
+
if paths is None and base is None:
|
|
229
|
+
selected, base = scope(root)
|
|
230
|
+
else:
|
|
231
|
+
selected = list(paths) if paths is not None else scope_paths(root, base=base)
|
|
232
|
+
payload = {
|
|
233
|
+
"base": base,
|
|
234
|
+
"repo": str(root.resolve()),
|
|
235
|
+
"paths": snapshot(root, selected),
|
|
236
|
+
}
|
|
237
|
+
return hashlib.sha256(
|
|
238
|
+
json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
|
239
|
+
).hexdigest()
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def repo_identity(root: Path) -> dict[str, str]:
|
|
243
|
+
remote = git(root, "config", "--get", "remote.origin.url", check=False).stdout.decode().strip()
|
|
244
|
+
return {"root": str(root.resolve()), "head": head(root), "remote": remote or "NONE"}
|
kwik_e_gate/hooks.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .classification import is_code_path
|
|
11
|
+
from .command_detection import detect_boundary_command
|
|
12
|
+
from .engine import boundary, fast
|
|
13
|
+
from .gitstate import (
|
|
14
|
+
ContentReadError,
|
|
15
|
+
git,
|
|
16
|
+
git_query_budget,
|
|
17
|
+
repo_root,
|
|
18
|
+
session_changed_paths,
|
|
19
|
+
snapshot,
|
|
20
|
+
)
|
|
21
|
+
from .status import Status
|
|
22
|
+
|
|
23
|
+
_REPOSITORY_ENV = {"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_NAMESPACE"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def run_hook(event: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
27
|
+
if event == "session-start":
|
|
28
|
+
return session_start(payload)
|
|
29
|
+
if event == "stop":
|
|
30
|
+
return stop(payload)
|
|
31
|
+
if event == "pre-tool-use":
|
|
32
|
+
return pre_tool_use(payload)
|
|
33
|
+
return {"continue": True, "systemMessage": f"Hermes Gate: unknown hook event {event}"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def session_start(payload: dict[str, Any]) -> dict[str, Any]:
|
|
37
|
+
root = repo_root(payload.get("cwd"))
|
|
38
|
+
if root is None:
|
|
39
|
+
return {"continue": True}
|
|
40
|
+
session_id = str(payload.get("session_id") or "unknown")
|
|
41
|
+
path = _session_path(session_id, root)
|
|
42
|
+
source = str(payload.get("source") or "startup")
|
|
43
|
+
if source not in {"resume", "compact"} or not path.exists():
|
|
44
|
+
try:
|
|
45
|
+
baseline = snapshot(root)
|
|
46
|
+
except ContentReadError as exc:
|
|
47
|
+
return {
|
|
48
|
+
"continue": True,
|
|
49
|
+
"systemMessage": f"Hermes Gate cannot bind session state: {exc}",
|
|
50
|
+
}
|
|
51
|
+
_atomic_json(
|
|
52
|
+
path,
|
|
53
|
+
{
|
|
54
|
+
"schema": "hermes-gate/session-v1",
|
|
55
|
+
"session_id": session_id,
|
|
56
|
+
"repository": str(root),
|
|
57
|
+
"baseline": baseline,
|
|
58
|
+
},
|
|
59
|
+
)
|
|
60
|
+
return {
|
|
61
|
+
"continue": True,
|
|
62
|
+
"hookSpecificOutput": {
|
|
63
|
+
"hookEventName": "SessionStart",
|
|
64
|
+
"additionalContext": (
|
|
65
|
+
"Hermes Gate completion rail is active. Run fast before completion. "
|
|
66
|
+
"Review/full requirements follow the repository profile. "
|
|
67
|
+
"Commit/push/PR boundaries validate exact receipts. "
|
|
68
|
+
"Read-only, non-Git, unchanged, and non-code work is exempt."
|
|
69
|
+
),
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def stop(payload: dict[str, Any]) -> dict[str, Any]:
|
|
75
|
+
# This hook is intentionally advisory and never emits decision:block.
|
|
76
|
+
root = repo_root(payload.get("cwd"))
|
|
77
|
+
if root is None:
|
|
78
|
+
return {"continue": True}
|
|
79
|
+
session_id = str(payload.get("session_id") or "unknown")
|
|
80
|
+
state = _read_json(_session_path(session_id, root))
|
|
81
|
+
baseline = state.get("baseline") if state.get("repository") == str(root) else None
|
|
82
|
+
try:
|
|
83
|
+
files = session_changed_paths(root, baseline if isinstance(baseline, dict) else None)
|
|
84
|
+
except ContentReadError as exc:
|
|
85
|
+
return {"continue": True, "systemMessage": f"Hermes Gate cannot inspect session changes: {exc}"}
|
|
86
|
+
files = [path for path in files if is_code_path(path)]
|
|
87
|
+
if not files:
|
|
88
|
+
return {"continue": True}
|
|
89
|
+
outcome = fast(root, files=files)
|
|
90
|
+
if outcome["status"] == Status.PASS:
|
|
91
|
+
return {"continue": True}
|
|
92
|
+
reason = str(outcome.get("reason") or "fast gate did not pass")
|
|
93
|
+
return {
|
|
94
|
+
"continue": True,
|
|
95
|
+
"systemMessage": f"Hermes Gate {outcome['status']}: {reason}. Run kwik-e-gate fast after addressing it.",
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def pre_tool_use(payload: dict[str, Any]) -> dict[str, Any]:
|
|
100
|
+
if payload.get("tool_name") != "Bash":
|
|
101
|
+
return {}
|
|
102
|
+
tool_input = payload.get("tool_input")
|
|
103
|
+
if not isinstance(tool_input, dict):
|
|
104
|
+
return {}
|
|
105
|
+
command = tool_input.get("command") or tool_input.get("cmd")
|
|
106
|
+
if not isinstance(command, str):
|
|
107
|
+
return {}
|
|
108
|
+
detected = detect_boundary_command(command)
|
|
109
|
+
if detected is None:
|
|
110
|
+
return {}
|
|
111
|
+
if any(name in os.environ for name in _REPOSITORY_ENV) or any(
|
|
112
|
+
arg == "--namespace" or arg.startswith("--namespace=")
|
|
113
|
+
for arg in detected.git_global_args
|
|
114
|
+
):
|
|
115
|
+
return _boundary_deny(
|
|
116
|
+
"repository/index/namespace overrides require an explicit native Gate boundary"
|
|
117
|
+
)
|
|
118
|
+
try:
|
|
119
|
+
# Both native hosts allow five seconds. All metadata queries, including
|
|
120
|
+
# receipt validation, share this deadline so a stall returns denial.
|
|
121
|
+
with git_query_budget(3.0):
|
|
122
|
+
root = _boundary_root(payload.get("cwd"), detected.git_global_args)
|
|
123
|
+
if root is None:
|
|
124
|
+
if detected.git_global_args:
|
|
125
|
+
return _boundary_deny(
|
|
126
|
+
"could not determine a matching repository context selected by git -C or global options"
|
|
127
|
+
)
|
|
128
|
+
return {}
|
|
129
|
+
outcome = boundary(root, detected.action.value)
|
|
130
|
+
except (OSError, ValueError, RuntimeError):
|
|
131
|
+
return _boundary_deny("could not safely resolve or validate the Git repository context")
|
|
132
|
+
if outcome["status"] == Status.PASS:
|
|
133
|
+
return {}
|
|
134
|
+
reason = str(outcome.get("reason") or "required receipt is missing")
|
|
135
|
+
return _boundary_deny(reason)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _boundary_root(cwd: str | None, global_args: tuple[str, ...]) -> Path | None:
|
|
139
|
+
"""Let Git resolve literal options, then require a normal registered worktree.
|
|
140
|
+
|
|
141
|
+
The receipt engine reads the worktree's own index and refs. Accepting an
|
|
142
|
+
arbitrary pairing of another Git directory and this worktree would validate
|
|
143
|
+
different state from the commit/push that is about to execute.
|
|
144
|
+
"""
|
|
145
|
+
if not global_args:
|
|
146
|
+
return repo_root(cwd)
|
|
147
|
+
start = Path(cwd or os.getcwd()).expanduser().resolve()
|
|
148
|
+
selected_root = _git_context_path(start, global_args, "--show-toplevel")
|
|
149
|
+
selected_git_dir = _git_context_path(start, global_args, "--absolute-git-dir")
|
|
150
|
+
if selected_root is None or selected_git_dir is None:
|
|
151
|
+
return None
|
|
152
|
+
normal_root = _git_context_path(selected_root, (), "--show-toplevel")
|
|
153
|
+
normal_git_dir = _git_context_path(selected_root, (), "--absolute-git-dir")
|
|
154
|
+
if selected_root != normal_root or selected_git_dir != normal_git_dir:
|
|
155
|
+
return None
|
|
156
|
+
return selected_root
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _git_context_path(root: Path, global_args: tuple[str, ...], query: str) -> Path | None:
|
|
160
|
+
# Override any command-local monitor configuration too; metadata lookup must
|
|
161
|
+
# not invoke a daemon or a model. The shared helper bounds every Git query.
|
|
162
|
+
proc = git(root, *global_args, "-c", "core.fsmonitor=false", "rev-parse", query, check=False)
|
|
163
|
+
if proc.returncode or not proc.stdout:
|
|
164
|
+
return None
|
|
165
|
+
return Path(proc.stdout.removesuffix(b"\n").decode("utf-8", "surrogateescape")).resolve()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _boundary_deny(reason: str) -> dict[str, Any]:
|
|
169
|
+
return {
|
|
170
|
+
"hookSpecificOutput": {
|
|
171
|
+
"hookEventName": "PreToolUse",
|
|
172
|
+
"permissionDecision": "deny",
|
|
173
|
+
"permissionDecisionReason": f"Hermes Gate: {reason}",
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def read_stdin_payload() -> dict[str, Any]:
|
|
179
|
+
try:
|
|
180
|
+
value = json.load(sys.stdin)
|
|
181
|
+
except (json.JSONDecodeError, OSError):
|
|
182
|
+
return {}
|
|
183
|
+
return value if isinstance(value, dict) else {}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _session_path(session_id: str, root: Path) -> Path:
|
|
187
|
+
cache = (
|
|
188
|
+
Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "kwik-e-gate" / "sessions"
|
|
189
|
+
)
|
|
190
|
+
cache.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
key = hashlib.sha256(f"{session_id}\0{root}".encode()).hexdigest()
|
|
192
|
+
return cache / f"{key}.json"
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _read_json(path: Path) -> dict[str, Any]:
|
|
196
|
+
try:
|
|
197
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
198
|
+
except (FileNotFoundError, json.JSONDecodeError, OSError):
|
|
199
|
+
return {}
|
|
200
|
+
return raw if isinstance(raw, dict) else {}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _atomic_json(path: Path, value: dict[str, Any]) -> None:
|
|
204
|
+
temporary = path.with_suffix(".tmp")
|
|
205
|
+
temporary.write_text(json.dumps(value, sort_keys=True) + "\n", encoding="utf-8")
|
|
206
|
+
os.chmod(temporary, 0o600)
|
|
207
|
+
os.replace(temporary, path)
|