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/config.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import fnmatch
|
|
4
|
+
import math
|
|
5
|
+
import tomllib
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ConfigError(ValueError):
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# A provider names the output contract the engine can bind to the local diff and
|
|
16
|
+
# parse; `review.argv[0]` names the executable and may differ. A name the engine
|
|
17
|
+
# has no contract for would run its argv verbatim and could only ever produce an
|
|
18
|
+
# unavailable or wrong review, so it is a profile error rather than a runtime one.
|
|
19
|
+
SUPPORTED_REVIEW_PROVIDERS: tuple[str, ...] = ("coderabbit", "jsonl")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class CommandSpec:
|
|
24
|
+
name: str
|
|
25
|
+
argv: tuple[str, ...]
|
|
26
|
+
timeout_seconds: float
|
|
27
|
+
globs: tuple[str, ...] = ("**/*",)
|
|
28
|
+
|
|
29
|
+
def applies(self, files: list[str]) -> bool:
|
|
30
|
+
return any(any(_matches(path, pattern) for pattern in self.globs) for path in files)
|
|
31
|
+
|
|
32
|
+
def expanded_argv(self, files: list[str]) -> list[str]:
|
|
33
|
+
out: list[str] = []
|
|
34
|
+
for part in self.argv:
|
|
35
|
+
if part == "{files}":
|
|
36
|
+
out.extend(files)
|
|
37
|
+
else:
|
|
38
|
+
out.append(part)
|
|
39
|
+
return out
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class LintLangSpec:
|
|
44
|
+
enabled: bool = False
|
|
45
|
+
argv: tuple[str, ...] = ("lintlang", "scan", "--format", "json", "{files}")
|
|
46
|
+
trigger_globs: tuple[str, ...] = ()
|
|
47
|
+
timeout_seconds: float = 4.0
|
|
48
|
+
blocking_threshold: str = "MEDIUM"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class ReviewSpec:
|
|
53
|
+
provider: str = "coderabbit"
|
|
54
|
+
argv: tuple[str, ...] = ("coderabbit", "review", "--agent")
|
|
55
|
+
timeout_seconds: float = 180.0
|
|
56
|
+
material_severities: tuple[str, ...] = ("critical", "major")
|
|
57
|
+
material_categories: tuple[str, ...] = (
|
|
58
|
+
"correctness",
|
|
59
|
+
"security",
|
|
60
|
+
"data-loss",
|
|
61
|
+
"concurrency",
|
|
62
|
+
"api-contract",
|
|
63
|
+
)
|
|
64
|
+
fallback_argv: tuple[str, ...] = ()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class AdapterSpec:
|
|
69
|
+
enabled: bool = False
|
|
70
|
+
name: str = "native"
|
|
71
|
+
argv: tuple[str, ...] = ()
|
|
72
|
+
minimum_version: str = ""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class GateConfig:
|
|
77
|
+
root: Path
|
|
78
|
+
fast_budget_seconds: float = 8.0
|
|
79
|
+
full_required_local: bool = False
|
|
80
|
+
review_required: bool = True
|
|
81
|
+
exclusions: tuple[str, ...] = (
|
|
82
|
+
".git/**",
|
|
83
|
+
".hermes/hermes_gate_runner.py",
|
|
84
|
+
".pytest_cache/**",
|
|
85
|
+
".ruff_cache/**",
|
|
86
|
+
"**/__pycache__/**",
|
|
87
|
+
"vendor/**",
|
|
88
|
+
"node_modules/**",
|
|
89
|
+
"dist/**",
|
|
90
|
+
"build/**",
|
|
91
|
+
)
|
|
92
|
+
fast: tuple[CommandSpec, ...] = ()
|
|
93
|
+
full: tuple[CommandSpec, ...] = ()
|
|
94
|
+
repair: tuple[CommandSpec, ...] = ()
|
|
95
|
+
lintlang: LintLangSpec = field(default_factory=LintLangSpec)
|
|
96
|
+
review: ReviewSpec = field(default_factory=ReviewSpec)
|
|
97
|
+
adapter: AdapterSpec = field(default_factory=AdapterSpec)
|
|
98
|
+
adapter_status: str = "NOT_CONFIGURED"
|
|
99
|
+
routing_full_globs: tuple[str, ...] = ()
|
|
100
|
+
routing_review_globs: tuple[str, ...] = ()
|
|
101
|
+
|
|
102
|
+
def included(self, path: str) -> bool:
|
|
103
|
+
return not any(_matches(path, pattern) for pattern in self.exclusions)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _matches(path: str, pattern: str) -> bool:
|
|
107
|
+
return fnmatch.fnmatch(path, pattern) or (
|
|
108
|
+
pattern.startswith("**/") and fnmatch.fnmatch(path, pattern[3:])
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _strings(value: Any, key: str, *, allow_empty: bool = False) -> tuple[str, ...]:
|
|
113
|
+
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
|
|
114
|
+
raise ConfigError(f"{key} must be an array of strings")
|
|
115
|
+
if not allow_empty and not value:
|
|
116
|
+
raise ConfigError(f"{key} must not be empty")
|
|
117
|
+
return tuple(value)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _commands(data: Any, key: str) -> tuple[CommandSpec, ...]:
|
|
121
|
+
if data is None:
|
|
122
|
+
return ()
|
|
123
|
+
if not isinstance(data, list):
|
|
124
|
+
raise ConfigError(f"[[{key}]] must be an array of tables")
|
|
125
|
+
result: list[CommandSpec] = []
|
|
126
|
+
for index, raw in enumerate(data):
|
|
127
|
+
if not isinstance(raw, dict):
|
|
128
|
+
raise ConfigError(f"{key}[{index}] must be a table")
|
|
129
|
+
argv = _strings(raw.get("argv"), f"{key}[{index}].argv")
|
|
130
|
+
timeout = _seconds(raw.get("timeout_seconds", 8.0), f"{key}[{index}].timeout_seconds")
|
|
131
|
+
result.append(
|
|
132
|
+
CommandSpec(
|
|
133
|
+
name=str(raw.get("name") or f"{key}-{index + 1}"),
|
|
134
|
+
argv=argv,
|
|
135
|
+
timeout_seconds=timeout,
|
|
136
|
+
globs=_strings(raw.get("globs", ["**/*"]), f"{key}[{index}].globs"),
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
return tuple(result)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _seconds(value: Any, key: str) -> float:
|
|
143
|
+
try:
|
|
144
|
+
result = float(value)
|
|
145
|
+
except (TypeError, ValueError) as exc:
|
|
146
|
+
raise ConfigError(f"{key} must be finite and positive") from exc
|
|
147
|
+
if not math.isfinite(result) or result <= 0:
|
|
148
|
+
raise ConfigError(f"{key} must be finite and positive")
|
|
149
|
+
return result
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def load_config(root: Path) -> GateConfig:
|
|
153
|
+
path = root / ".hermes" / "gate.toml"
|
|
154
|
+
if not path.is_file():
|
|
155
|
+
raise FileNotFoundError(path)
|
|
156
|
+
try:
|
|
157
|
+
raw = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
158
|
+
except (tomllib.TOMLDecodeError, OSError) as exc:
|
|
159
|
+
raise ConfigError(str(exc)) from exc
|
|
160
|
+
gate = raw.get("gate", {})
|
|
161
|
+
lint = raw.get("lintlang", {})
|
|
162
|
+
review = raw.get("review", {})
|
|
163
|
+
adapter = raw.get("adapter", {})
|
|
164
|
+
routing = raw.get("routing", {})
|
|
165
|
+
if not all(isinstance(item, dict) for item in (gate, lint, review, adapter, routing)):
|
|
166
|
+
raise ConfigError("gate, lintlang, review, adapter, and routing must be tables")
|
|
167
|
+
budget = _seconds(gate.get("fast_budget_seconds", 8.0), "gate.fast_budget_seconds")
|
|
168
|
+
review_required = gate.get("review_required", True)
|
|
169
|
+
if not isinstance(review_required, bool):
|
|
170
|
+
raise ConfigError("gate.review_required must be a boolean")
|
|
171
|
+
provider = str(review.get("provider", "coderabbit"))
|
|
172
|
+
if provider not in SUPPORTED_REVIEW_PROVIDERS:
|
|
173
|
+
raise ConfigError(
|
|
174
|
+
f'review.provider "{provider}" is not a supported review provider; '
|
|
175
|
+
f"supported: {', '.join(SUPPORTED_REVIEW_PROVIDERS)} "
|
|
176
|
+
"(review.argv[0] may still name any compatible executable)"
|
|
177
|
+
)
|
|
178
|
+
return GateConfig(
|
|
179
|
+
root=root,
|
|
180
|
+
fast_budget_seconds=budget,
|
|
181
|
+
full_required_local=bool(gate.get("full_required_local", False)),
|
|
182
|
+
review_required=review_required,
|
|
183
|
+
exclusions=_strings(gate.get("exclusions", list(GateConfig.exclusions)), "gate.exclusions"),
|
|
184
|
+
fast=_commands(raw.get("fast"), "fast"),
|
|
185
|
+
full=_commands(raw.get("full"), "full"),
|
|
186
|
+
repair=_commands(raw.get("repair"), "repair"),
|
|
187
|
+
lintlang=LintLangSpec(
|
|
188
|
+
enabled=bool(lint.get("enabled", False)),
|
|
189
|
+
argv=_strings(lint.get("argv", list(LintLangSpec.argv)), "lintlang.argv"),
|
|
190
|
+
trigger_globs=_strings(
|
|
191
|
+
lint.get("trigger_globs", []), "lintlang.trigger_globs", allow_empty=True
|
|
192
|
+
),
|
|
193
|
+
timeout_seconds=_seconds(lint.get("timeout_seconds", 4.0), "lintlang.timeout_seconds"),
|
|
194
|
+
blocking_threshold=str(lint.get("blocking_threshold", "MEDIUM")).upper(),
|
|
195
|
+
),
|
|
196
|
+
review=ReviewSpec(
|
|
197
|
+
provider=provider,
|
|
198
|
+
argv=_strings(review.get("argv", list(ReviewSpec.argv)), "review.argv"),
|
|
199
|
+
timeout_seconds=_seconds(review.get("timeout_seconds", 180.0), "review.timeout_seconds"),
|
|
200
|
+
material_severities=tuple(
|
|
201
|
+
item.lower()
|
|
202
|
+
for item in _strings(
|
|
203
|
+
review.get("material_severities", list(ReviewSpec.material_severities)),
|
|
204
|
+
"review.material_severities",
|
|
205
|
+
)
|
|
206
|
+
),
|
|
207
|
+
material_categories=tuple(
|
|
208
|
+
item.lower()
|
|
209
|
+
for item in _strings(
|
|
210
|
+
review.get("material_categories", list(ReviewSpec.material_categories)),
|
|
211
|
+
"review.material_categories",
|
|
212
|
+
)
|
|
213
|
+
),
|
|
214
|
+
fallback_argv=_strings(
|
|
215
|
+
review.get("fallback_argv", []), "review.fallback_argv", allow_empty=True
|
|
216
|
+
),
|
|
217
|
+
),
|
|
218
|
+
adapter=AdapterSpec(
|
|
219
|
+
enabled=bool(adapter.get("enabled", False)),
|
|
220
|
+
name=str(adapter.get("name", "native")),
|
|
221
|
+
argv=_strings(adapter.get("argv", []), "adapter.argv", allow_empty=True),
|
|
222
|
+
minimum_version=str(adapter.get("minimum_version", "")),
|
|
223
|
+
),
|
|
224
|
+
adapter_status=str(gate.get("adapter_status", "NOT_CONFIGURED")),
|
|
225
|
+
routing_full_globs=_strings(
|
|
226
|
+
routing.get("full_globs", []), "routing.full_globs", allow_empty=True
|
|
227
|
+
),
|
|
228
|
+
routing_review_globs=_strings(
|
|
229
|
+
routing.get("review_globs", []), "routing.review_globs", allow_empty=True
|
|
230
|
+
),
|
|
231
|
+
)
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""``kwik-e-gate delegate-judge``: judge one child workspace with the fast gate.
|
|
2
|
+
|
|
3
|
+
Wire contract (see README "Hermes Agent quality-gate seam"): read one JSON request
|
|
4
|
+
object from stdin and write exactly one JSON ``{"verdict", "feedback"}``
|
|
5
|
+
object to stdout. This module never runs a shell and never changes the
|
|
6
|
+
process's working directory; every gate call is bound to the caller-supplied
|
|
7
|
+
``workspace`` argument, so concurrent invocations of this command in separate
|
|
8
|
+
processes cannot race.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, TextIO
|
|
16
|
+
|
|
17
|
+
from .engine import fast
|
|
18
|
+
from .gitstate import repo_root
|
|
19
|
+
from .status import Status
|
|
20
|
+
|
|
21
|
+
REQUEST_VERSION = 1
|
|
22
|
+
MAX_FEEDBACK_CHARS = 800
|
|
23
|
+
MAX_FAILED_CHECKS = 5
|
|
24
|
+
|
|
25
|
+
# name -> expected type for fields the emitter always sends with a concrete value.
|
|
26
|
+
_REQUIRED_FIELDS: dict[str, type] = {
|
|
27
|
+
"version": int,
|
|
28
|
+
"goal": str,
|
|
29
|
+
"summary": str,
|
|
30
|
+
"attempt": int,
|
|
31
|
+
"max_retries": int,
|
|
32
|
+
"task_index": int,
|
|
33
|
+
"completed": bool,
|
|
34
|
+
}
|
|
35
|
+
# name -> expected type for fields the emitter may send as ``null``.
|
|
36
|
+
_NULLABLE_FIELDS: dict[str, type] = {
|
|
37
|
+
"subagent_id": str,
|
|
38
|
+
"session_id": str,
|
|
39
|
+
"model": str,
|
|
40
|
+
"api_calls": int,
|
|
41
|
+
"workspace": str,
|
|
42
|
+
}
|
|
43
|
+
# name -> expected type for fields the emitter may omit entirely.
|
|
44
|
+
_OPTIONAL_FIELDS: dict[str, type] = {
|
|
45
|
+
"workspace_isolated": bool,
|
|
46
|
+
}
|
|
47
|
+
_TYPE_LABELS: dict[type, str] = {int: "an integer", str: "a string", bool: "a boolean"}
|
|
48
|
+
_NO_WORKSPACE = "workspace unavailable: request has no workspace path"
|
|
49
|
+
_NOT_A_DIRECTORY = "workspace unavailable: path is not a directory"
|
|
50
|
+
_UNDECODABLE_STDIN = "stdin is not decodable text"
|
|
51
|
+
_PASSING_STATUSES = (Status.PASS, Status.NOT_APPLICABLE)
|
|
52
|
+
_CHECK_PASSING_STATUSES = {"pass", "skipped", "not_applicable"}
|
|
53
|
+
# The exact sentinel `repo_runner._execute`, `adapters.run_adapter`, and
|
|
54
|
+
# `engine._execution_dict` all use when a check's executable cannot be
|
|
55
|
+
# launched. Checks that carry a structured `unavailable` bool are trusted
|
|
56
|
+
# directly; this is the fallback for check shapes that only report it in
|
|
57
|
+
# `reason` text, matched exactly rather than by substring so an unrelated
|
|
58
|
+
# check whose own output happens to mention "unavailable" is not misread.
|
|
59
|
+
_EXECUTABLE_UNAVAILABLE_REASON = "executable unavailable"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def read_request(stream: TextIO) -> tuple[dict[str, Any] | None, str]:
|
|
63
|
+
"""Read the one required JSON request object from ``stream``.
|
|
64
|
+
|
|
65
|
+
Returns ``(request, "")`` on success, or ``(None, reason)`` when the bytes
|
|
66
|
+
on the stream are not a single JSON object.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
raw = stream.read()
|
|
71
|
+
except OSError as exc:
|
|
72
|
+
return None, f"cannot read stdin: {exc}"
|
|
73
|
+
except UnicodeError:
|
|
74
|
+
# The seam contract is exactly one JSON object on stdout; exception
|
|
75
|
+
# text could carry raw undecodable bytes, so the reason stays fixed.
|
|
76
|
+
return None, _UNDECODABLE_STDIN
|
|
77
|
+
try:
|
|
78
|
+
value = json.loads(raw)
|
|
79
|
+
except json.JSONDecodeError as exc:
|
|
80
|
+
return None, f"stdin is not valid JSON: {exc}"
|
|
81
|
+
if not isinstance(value, dict):
|
|
82
|
+
return None, "request must be a JSON object"
|
|
83
|
+
return value, ""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def validate_request(value: dict[str, Any]) -> str:
|
|
87
|
+
"""Return "" when ``value`` matches the consumer contract, else a compact reason."""
|
|
88
|
+
|
|
89
|
+
for field, kind in _REQUIRED_FIELDS.items():
|
|
90
|
+
if field not in value:
|
|
91
|
+
return f"missing required field: {field}"
|
|
92
|
+
if not _matches(value[field], kind):
|
|
93
|
+
return f"{field} must be {_TYPE_LABELS[kind]}"
|
|
94
|
+
for field, kind in _NULLABLE_FIELDS.items():
|
|
95
|
+
if field in value and value[field] is not None and not _matches(value[field], kind):
|
|
96
|
+
return f"{field} must be {_TYPE_LABELS[kind]} or null"
|
|
97
|
+
for field, kind in _OPTIONAL_FIELDS.items():
|
|
98
|
+
if field in value and not _matches(value[field], kind):
|
|
99
|
+
return f"{field} must be {_TYPE_LABELS[kind]}"
|
|
100
|
+
if not _feedback_shape_ok(value.get("previous_feedback")):
|
|
101
|
+
return "previous_feedback must be a string, an array of strings, or null"
|
|
102
|
+
if value["version"] != REQUEST_VERSION:
|
|
103
|
+
return f"unsupported request version: {value['version']!r}"
|
|
104
|
+
workspace = value.get("workspace")
|
|
105
|
+
if isinstance(workspace, str) and not workspace.strip():
|
|
106
|
+
return "workspace must not be empty"
|
|
107
|
+
if value["attempt"] < 1:
|
|
108
|
+
return "attempt must be a positive integer (attempts are one-based)"
|
|
109
|
+
if value["max_retries"] < 0:
|
|
110
|
+
return "max_retries must be non-negative"
|
|
111
|
+
return ""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _feedback_shape_ok(value: Any) -> bool:
|
|
115
|
+
# The judge never reads prior feedback; the check only keeps the wire shape honest.
|
|
116
|
+
if value is None or isinstance(value, str):
|
|
117
|
+
return True
|
|
118
|
+
return isinstance(value, list) and all(isinstance(item, str) for item in value)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _matches(value: Any, kind: type) -> bool:
|
|
122
|
+
if kind is bool:
|
|
123
|
+
return isinstance(value, bool)
|
|
124
|
+
if kind is int:
|
|
125
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
126
|
+
return isinstance(value, kind)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def judge(request: dict[str, Any]) -> dict[str, str]:
|
|
130
|
+
"""Map one delegate-judge request to a bounded ``{"verdict", "feedback"}`` object."""
|
|
131
|
+
|
|
132
|
+
error = validate_request(request)
|
|
133
|
+
if error:
|
|
134
|
+
return {"verdict": "error", "feedback": _bound(f"invalid request: {error}")}
|
|
135
|
+
workspace_value = request.get("workspace")
|
|
136
|
+
if workspace_value is None:
|
|
137
|
+
return {"verdict": "error", "feedback": _NO_WORKSPACE}
|
|
138
|
+
workspace = Path(workspace_value).expanduser()
|
|
139
|
+
if not workspace.is_dir():
|
|
140
|
+
return {"verdict": "error", "feedback": _NOT_A_DIRECTORY}
|
|
141
|
+
root = repo_root(workspace)
|
|
142
|
+
if root is None:
|
|
143
|
+
return {"verdict": "error", "feedback": "workspace is not a Git repository"}
|
|
144
|
+
outcome = fast(root)
|
|
145
|
+
return _map_outcome(outcome, attempt=request["attempt"], max_retries=request["max_retries"])
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _map_outcome(outcome: dict[str, Any], *, attempt: int, max_retries: int) -> dict[str, str]:
|
|
149
|
+
try:
|
|
150
|
+
status = Status(str(outcome.get("status", Status.ERROR.value)))
|
|
151
|
+
except ValueError:
|
|
152
|
+
status = Status.ERROR
|
|
153
|
+
reason = str(outcome.get("reason") or "")
|
|
154
|
+
if status in _PASSING_STATUSES:
|
|
155
|
+
return {"verdict": "pass", "feedback": ""}
|
|
156
|
+
if status is Status.NOT_CONFIGURED:
|
|
157
|
+
return {"verdict": "error", "feedback": _bound(f"gate not configured: {reason}")}
|
|
158
|
+
if status is Status.FAIL:
|
|
159
|
+
failing = _failing_checks(outcome)
|
|
160
|
+
feedback = _bound(_fail_feedback(reason, failing))
|
|
161
|
+
if any(_check_unavailable(check) for check in failing):
|
|
162
|
+
# A check that could not even launch is an environment/adapter
|
|
163
|
+
# problem, not something a correction turn can fix: the seam
|
|
164
|
+
# contract calls for "error" here, not "retry" or "reject".
|
|
165
|
+
return {"verdict": "error", "feedback": feedback}
|
|
166
|
+
# `attempt` is one-based (the first attempt is 1) and `max_retries` counts
|
|
167
|
+
# allowed correction turns after that first attempt, so up to
|
|
168
|
+
# `max_retries` further attempts are still owed while attempt <= max_retries.
|
|
169
|
+
verdict = "retry" if attempt <= max_retries else "reject"
|
|
170
|
+
return {"verdict": verdict, "feedback": feedback}
|
|
171
|
+
# ERROR, and any status `fast` is not documented to return (PARKED,
|
|
172
|
+
# REVIEW_UNAVAILABLE): treat conservatively as an adapter/tool problem.
|
|
173
|
+
return {"verdict": "error", "feedback": _bound(f"gate error: {reason or status.value}")}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _failing_checks(outcome: dict[str, Any]) -> list[dict[str, Any]]:
|
|
177
|
+
receipt = outcome.get("receipt")
|
|
178
|
+
checks = receipt.get("checks") if isinstance(receipt, dict) else None
|
|
179
|
+
if not isinstance(checks, list):
|
|
180
|
+
return []
|
|
181
|
+
return [
|
|
182
|
+
check
|
|
183
|
+
for check in checks
|
|
184
|
+
if isinstance(check, dict)
|
|
185
|
+
and str(check.get("status", "")).lower() not in _CHECK_PASSING_STATUSES
|
|
186
|
+
]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _check_unavailable(check: dict[str, Any]) -> bool:
|
|
190
|
+
unavailable = check.get("unavailable")
|
|
191
|
+
if isinstance(unavailable, bool):
|
|
192
|
+
return unavailable
|
|
193
|
+
return str(check.get("reason") or "") == _EXECUTABLE_UNAVAILABLE_REASON
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _fail_feedback(reason: str, failing: list[dict[str, Any]]) -> str:
|
|
197
|
+
lines = [reason or "fast gate failed"]
|
|
198
|
+
for check in failing[:MAX_FAILED_CHECKS]:
|
|
199
|
+
name = str(check.get("name", "check"))
|
|
200
|
+
detail = str(check.get("reason") or check.get("status") or "failed")
|
|
201
|
+
lines.append(f"- {name}: {detail}")
|
|
202
|
+
overflow = len(failing) - MAX_FAILED_CHECKS
|
|
203
|
+
if overflow > 0:
|
|
204
|
+
lines.append(f"...and {overflow} more failing check(s)")
|
|
205
|
+
return "\n".join(lines)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _bound(text: str) -> str:
|
|
209
|
+
if len(text) <= MAX_FEEDBACK_CHARS:
|
|
210
|
+
return text
|
|
211
|
+
return text[: MAX_FEEDBACK_CHARS - 1].rstrip() + "…"
|
kwik_e_gate/doctor.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .binding import capture_binding
|
|
11
|
+
from .codex_install import installed as codex_installed
|
|
12
|
+
from .config import ConfigError, ReviewSpec, load_config
|
|
13
|
+
from .execution import run_argv
|
|
14
|
+
from .gitstate import ContentReadError, ScopeError, diff_digest, repo_root, scope
|
|
15
|
+
from .init_repo import verify_runner
|
|
16
|
+
from .receipts import read_receipt
|
|
17
|
+
from .status import Status
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _provider_auth_status(returncode: int, output: str) -> str:
|
|
21
|
+
"""Interpret CodeRabbit's agent event instead of trusting its status exit code."""
|
|
22
|
+
for line in output.splitlines():
|
|
23
|
+
try:
|
|
24
|
+
event = json.loads(line)
|
|
25
|
+
except json.JSONDecodeError:
|
|
26
|
+
continue
|
|
27
|
+
if not isinstance(event, dict):
|
|
28
|
+
continue
|
|
29
|
+
if event.get("authenticated") is True:
|
|
30
|
+
return "AUTHENTICATED"
|
|
31
|
+
if event.get("authenticated") is False:
|
|
32
|
+
return "AUTH_REQUIRED"
|
|
33
|
+
status = str(event.get("status", "")).lower()
|
|
34
|
+
if status in {"not_authenticated", "unauthenticated", "auth_required"}:
|
|
35
|
+
return "AUTH_REQUIRED"
|
|
36
|
+
if status in {"authenticated", "signed_in"}:
|
|
37
|
+
return "AUTHENTICATED"
|
|
38
|
+
return "AUTHENTICATED" if returncode == 0 else "AUTH_REQUIRED"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _provider_executable(name: str, root: Path | None) -> str | None:
|
|
42
|
+
"""Resolve the configured review executable the way `review` will launch it."""
|
|
43
|
+
found = shutil.which(name)
|
|
44
|
+
if found:
|
|
45
|
+
return str(Path(found).resolve())
|
|
46
|
+
if root is not None:
|
|
47
|
+
candidate = root / name
|
|
48
|
+
if candidate.is_file() and os.access(candidate, os.X_OK):
|
|
49
|
+
return str(candidate)
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _provider_report(spec: ReviewSpec, root: Path | None) -> dict[str, Any]:
|
|
54
|
+
"""Probe the executable the profile names, not a fixed binary."""
|
|
55
|
+
executable = spec.argv[0]
|
|
56
|
+
binary = _provider_executable(executable, root)
|
|
57
|
+
report: dict[str, Any] = {"name": spec.provider, "argv0": executable, "binary": binary}
|
|
58
|
+
if binary is None:
|
|
59
|
+
report["status"] = "NOT_CONFIGURED"
|
|
60
|
+
installer_copy = Path.home() / ".local" / "bin" / executable
|
|
61
|
+
if installer_copy.is_file():
|
|
62
|
+
report["detail"] = f"{installer_copy} exists but is not on PATH"
|
|
63
|
+
return report
|
|
64
|
+
if spec.provider == "jsonl":
|
|
65
|
+
report["status"] = "AVAILABLE"
|
|
66
|
+
return report
|
|
67
|
+
execution = run_argv(
|
|
68
|
+
[binary, "auth", "status", "--agent"],
|
|
69
|
+
cwd=root or Path.cwd(),
|
|
70
|
+
timeout_seconds=5,
|
|
71
|
+
output_cap=4096,
|
|
72
|
+
)
|
|
73
|
+
detail = (execution.stdout or execution.stderr).strip()[:1000]
|
|
74
|
+
report["status"] = _provider_auth_status(execution.returncode, detail)
|
|
75
|
+
report["detail"] = detail
|
|
76
|
+
return report
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def diagnose(start: Path | None = None) -> dict[str, Any]:
|
|
80
|
+
began = time.monotonic()
|
|
81
|
+
root = repo_root(start)
|
|
82
|
+
codex = codex_installed()
|
|
83
|
+
config = None
|
|
84
|
+
profile: dict[str, Any] = {}
|
|
85
|
+
if root is not None:
|
|
86
|
+
try:
|
|
87
|
+
config = load_config(root)
|
|
88
|
+
profile = {"status": "PASS", "adapter_status": config.adapter_status}
|
|
89
|
+
except FileNotFoundError:
|
|
90
|
+
profile = {"status": "NOT_CONFIGURED", "next_action": "kwik-e-gate init"}
|
|
91
|
+
except ConfigError as exc:
|
|
92
|
+
profile = {"status": "ERROR", "reason": str(exc)}
|
|
93
|
+
# Without a usable profile, report on the default provider so the operator
|
|
94
|
+
# still learns whether the reviewer is ready once the profile is fixed.
|
|
95
|
+
provider = _provider_report(config.review if config is not None else ReviewSpec(), root)
|
|
96
|
+
if root is None:
|
|
97
|
+
return {
|
|
98
|
+
"schema": "hermes-gate/doctor-v1",
|
|
99
|
+
"status": Status.NOT_APPLICABLE.value,
|
|
100
|
+
"repository": None,
|
|
101
|
+
"codex": codex,
|
|
102
|
+
"provider": provider,
|
|
103
|
+
"elapsed_ms": round((time.monotonic() - began) * 1000),
|
|
104
|
+
}
|
|
105
|
+
runner_ok, runner_detail = verify_runner(root)
|
|
106
|
+
try:
|
|
107
|
+
selected, scope_base = scope(root)
|
|
108
|
+
if config:
|
|
109
|
+
selected = [path for path in selected if config.included(path)]
|
|
110
|
+
digest = diff_digest(root, selected, base=scope_base)
|
|
111
|
+
input_error = None
|
|
112
|
+
except (ContentReadError, ScopeError) as exc:
|
|
113
|
+
digest = None
|
|
114
|
+
input_error = str(exc)
|
|
115
|
+
receipts: dict[str, Any] = {}
|
|
116
|
+
for kind in ("fast", "review", "full"):
|
|
117
|
+
receipt = read_receipt(root, kind)
|
|
118
|
+
try:
|
|
119
|
+
current_binding = capture_binding(root, kind, config) if config else None
|
|
120
|
+
except (ContentReadError, OSError):
|
|
121
|
+
current_binding = None
|
|
122
|
+
receipts[kind] = {
|
|
123
|
+
"status": "MISSING" if receipt is None else receipt.get("status", "ERROR"),
|
|
124
|
+
"stale": bool(receipt and (
|
|
125
|
+
digest is None or receipt.get("diff_sha256") != digest
|
|
126
|
+
or current_binding is None or receipt.get("binding") != current_binding
|
|
127
|
+
)),
|
|
128
|
+
}
|
|
129
|
+
statuses = [profile["status"], "PASS" if runner_ok else "NOT_CONFIGURED"]
|
|
130
|
+
if input_error or profile["status"] == "ERROR":
|
|
131
|
+
overall = "ERROR"
|
|
132
|
+
elif all(item == "PASS" for item in statuses):
|
|
133
|
+
overall = "PASS"
|
|
134
|
+
else:
|
|
135
|
+
overall = "NOT_CONFIGURED"
|
|
136
|
+
return {
|
|
137
|
+
"schema": "hermes-gate/doctor-v1",
|
|
138
|
+
"status": overall,
|
|
139
|
+
"repository": str(root),
|
|
140
|
+
"profile": profile,
|
|
141
|
+
"runner": {"status": "PASS" if runner_ok else "NOT_CONFIGURED", "detail": runner_detail},
|
|
142
|
+
**({"input_error": input_error} if input_error else {}),
|
|
143
|
+
"codex": codex,
|
|
144
|
+
"provider": provider,
|
|
145
|
+
"receipts": receipts,
|
|
146
|
+
"elapsed_ms": round((time.monotonic() - began) * 1000),
|
|
147
|
+
}
|