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,194 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections.abc import Iterable
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from .status import Status
9
+
10
+ MATERIAL_CATEGORIES = {
11
+ "correctness",
12
+ "security",
13
+ "data-loss",
14
+ "concurrency",
15
+ "api-contract",
16
+ }
17
+ MATERIAL_SEVERITIES = {"critical", "major"}
18
+ NONMATERIAL_CATEGORIES = {"style", "documentation"}
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Finding:
23
+ severity: str
24
+ category: str
25
+ path: str
26
+ line: int | None
27
+ message: str
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class NormalizedReview:
32
+ status: Status
33
+ findings: tuple[Finding, ...]
34
+ suppressed_count: int
35
+ reason: str = ""
36
+
37
+
38
+ def normalize_coderabbit_output(
39
+ payload: str | dict[str, Any] | list[Any],
40
+ *,
41
+ material_severities: Iterable[str] = MATERIAL_SEVERITIES,
42
+ material_categories: Iterable[str] = MATERIAL_CATEGORIES,
43
+ ) -> NormalizedReview:
44
+ events: list[dict[str, Any]] = []
45
+ if isinstance(payload, str):
46
+ for line in payload.splitlines():
47
+ if not line.strip():
48
+ continue
49
+ try:
50
+ item = json.loads(line)
51
+ except json.JSONDecodeError:
52
+ continue
53
+ if isinstance(item, dict):
54
+ events.append(item)
55
+ elif isinstance(payload, dict):
56
+ events = [payload]
57
+ elif isinstance(payload, list):
58
+ events = [item for item in payload if isinstance(item, dict)]
59
+ if not events:
60
+ return NormalizedReview(Status.REVIEW_UNAVAILABLE, (), 0, "no parseable agent events")
61
+
62
+ severities = {item.lower() for item in material_severities}
63
+ categories = {item.lower() for item in material_categories}
64
+ findings: list[Finding] = []
65
+ suppressed = 0
66
+ completed = False
67
+ error = ""
68
+ for event in events:
69
+ event_type = str(event.get("type", "")).lower()
70
+ if event_type == "error":
71
+ error = str(event.get("message") or event.get("error") or "provider error")
72
+ if event_type in {"complete", "completed"}:
73
+ completed = True
74
+ if event_type != "finding":
75
+ continue
76
+ severity = str(event.get("severity", "info")).lower()
77
+ message = str(
78
+ event.get("message")
79
+ or event.get("title")
80
+ or event.get("codegenInstructions")
81
+ or "CodeRabbit finding"
82
+ )
83
+ category = _category(event, message)
84
+ # CLI findings can omit category. Unclassified selected-severity findings
85
+ # need a disposition; vocabulary inference must not silently turn them green.
86
+ material = severity in severities and (
87
+ category in categories or category == "unclassified"
88
+ )
89
+ if not material:
90
+ suppressed += 1
91
+ continue
92
+ line = event.get("line") or event.get("lineNumber")
93
+ findings.append(
94
+ Finding(
95
+ severity=severity,
96
+ category=category,
97
+ path=str(event.get("fileName") or event.get("path") or ""),
98
+ line=int(line) if isinstance(line, int | float) else None,
99
+ message=message,
100
+ )
101
+ )
102
+
103
+ if error:
104
+ return NormalizedReview(Status.REVIEW_UNAVAILABLE, tuple(findings), suppressed, error)
105
+ if not completed:
106
+ return NormalizedReview(
107
+ Status.REVIEW_UNAVAILABLE, (), suppressed, "review did not complete"
108
+ )
109
+ return NormalizedReview(
110
+ Status.FAIL if findings else Status.PASS,
111
+ tuple(findings),
112
+ suppressed,
113
+ )
114
+
115
+
116
+ def normalize_jsonl_output(
117
+ payload: str,
118
+ *,
119
+ digest: str,
120
+ reviewed_paths: list[str],
121
+ material_severities: Iterable[str] = MATERIAL_SEVERITIES,
122
+ material_categories: Iterable[str] = MATERIAL_CATEGORIES,
123
+ ) -> NormalizedReview:
124
+ """Parse a bounded reviewer stream with an explicit exact-diff completion claim."""
125
+ try:
126
+ events = [json.loads(line) for line in payload.splitlines() if line.strip()]
127
+ except json.JSONDecodeError:
128
+ return NormalizedReview(Status.REVIEW_UNAVAILABLE, (), 0, "invalid JSONL review output")
129
+ if not events or any(not isinstance(event, dict) for event in events):
130
+ return NormalizedReview(Status.REVIEW_UNAVAILABLE, (), 0, "invalid JSONL review events")
131
+ completions = [event for event in events if event.get("type") == "complete"]
132
+ if len(completions) != 1 or events[-1] is not completions[0]:
133
+ return NormalizedReview(Status.REVIEW_UNAVAILABLE, (), 0, "one final completion required")
134
+ completion = completions[0]
135
+ if completion.get("digest") != digest or completion.get("reviewed_paths") != reviewed_paths:
136
+ return NormalizedReview(Status.REVIEW_UNAVAILABLE, (), 0, "review scope does not match current diff")
137
+ severities = set(material_severities)
138
+ categories = set(material_categories)
139
+ findings: list[Finding] = []
140
+ suppressed = 0
141
+ for event in events[:-1]:
142
+ if event.get("type") == "error":
143
+ return NormalizedReview(
144
+ Status.REVIEW_UNAVAILABLE, (), 0, str(event.get("message") or "provider error")
145
+ )
146
+ if event.get("type") != "finding":
147
+ return NormalizedReview(Status.REVIEW_UNAVAILABLE, (), 0, "unknown review event")
148
+ severity, category = event.get("severity"), event.get("category")
149
+ path, message, line = event.get("path"), event.get("message"), event.get("line")
150
+ if (
151
+ not isinstance(severity, str)
152
+ or not isinstance(category, str)
153
+ or not isinstance(path, str)
154
+ or path not in reviewed_paths
155
+ or not isinstance(message, str)
156
+ or not message.strip()
157
+ or (line is not None and (not isinstance(line, int) or isinstance(line, bool) or line < 1))
158
+ ):
159
+ return NormalizedReview(Status.REVIEW_UNAVAILABLE, (), 0, "invalid or unscoped finding")
160
+ if severity.lower() in severities and category.lower() in categories:
161
+ findings.append(Finding(severity.lower(), category.lower(), path, line, message))
162
+ else:
163
+ suppressed += 1
164
+ return NormalizedReview(Status.FAIL if findings else Status.PASS, tuple(findings), suppressed)
165
+
166
+
167
+ def _category(event: dict[str, Any], message: str) -> str:
168
+ raw = str(event.get("category") or event.get("typeName") or "").lower().replace("_", "-")
169
+ if raw in MATERIAL_CATEGORIES | NONMATERIAL_CATEGORIES:
170
+ return raw
171
+ text = f"{raw} {message}".lower()
172
+ mapping = (
173
+ (
174
+ "security",
175
+ (
176
+ "security",
177
+ "vulnerab",
178
+ "injection",
179
+ "credential",
180
+ "auth",
181
+ "interpolat",
182
+ "placeholder syntax",
183
+ "bound parameter",
184
+ ),
185
+ ),
186
+ ("data-loss", ("data loss", "truncate", "overwrite", "corrupt", "delete")),
187
+ ("concurrency", ("race", "deadlock", "concurr", "thread", "atomic")),
188
+ ("api-contract", ("api contract", "breaking change", "compatib", "schema")),
189
+ ("correctness", ("correctness", "logic", "exception", "crash", "wrong", "bug", "null")),
190
+ )
191
+ for category, needles in mapping:
192
+ if any(needle in text for needle in needles):
193
+ return category
194
+ return "unclassified"
@@ -0,0 +1,115 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import tempfile
6
+ from datetime import UTC, datetime
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .binding import capture_binding
11
+ from .config import ConfigError
12
+ from .gitstate import ContentReadError, GitError, diff_digest, git_dir, head, repo_identity
13
+
14
+ SCHEMA = "hermes-gate/receipt-v1"
15
+
16
+
17
+ def receipt_dir(root: Path) -> Path:
18
+ return git_dir(root) / "kwik-e-gate" / "receipts"
19
+
20
+
21
+ def receipt_path(root: Path, kind: str) -> Path:
22
+ return receipt_dir(root) / f"{kind}.json"
23
+
24
+
25
+ def write_receipt(
26
+ root: Path,
27
+ kind: str,
28
+ *,
29
+ status: str,
30
+ digest: str,
31
+ elapsed_ms: int,
32
+ command_versions: dict[str, str] | None = None,
33
+ checks: list[dict[str, Any]] | None = None,
34
+ findings: list[dict[str, Any]] | None = None,
35
+ extra: dict[str, Any] | None = None,
36
+ ) -> dict[str, Any]:
37
+ payload: dict[str, Any] = {
38
+ "schema": SCHEMA,
39
+ "kind": kind,
40
+ "status": status,
41
+ "created_at": datetime.now(UTC).isoformat(),
42
+ "repository": repo_identity(root),
43
+ "diff_sha256": digest,
44
+ "elapsed_ms": elapsed_ms,
45
+ "command_versions": command_versions or {},
46
+ "checks": checks or [],
47
+ "findings": findings or [],
48
+ }
49
+ if extra:
50
+ payload.update(extra)
51
+ _atomic_json(receipt_path(root, kind), payload)
52
+ return payload
53
+
54
+
55
+ def read_receipt(root: Path, kind: str) -> dict[str, Any] | None:
56
+ path = receipt_path(root, kind)
57
+ try:
58
+ raw = json.loads(path.read_text(encoding="utf-8"))
59
+ except (FileNotFoundError, json.JSONDecodeError, OSError):
60
+ return None
61
+ return raw if isinstance(raw, dict) else None
62
+
63
+
64
+ def valid_receipt(
65
+ root: Path, kind: str, digest: str | None = None, *, binding: dict[str, Any] | None = None
66
+ ) -> dict[str, Any] | None:
67
+ raw = read_receipt(root, kind)
68
+ if not raw:
69
+ return None
70
+ return raw if receipt_matches(root, raw, kind, digest, binding=binding) else None
71
+
72
+
73
+ def receipt_matches(
74
+ root: Path, raw: dict[str, Any], kind: str, digest: str | None = None,
75
+ *, binding: dict[str, Any] | None = None,
76
+ ) -> bool:
77
+ """Validate stored or exported PASS evidence against current local inputs."""
78
+ if raw.get("schema") != SCHEMA or raw.get("kind") != kind:
79
+ return False
80
+ try:
81
+ expected = digest or diff_digest(root)
82
+ current_binding = binding if binding is not None else capture_binding(root, kind)
83
+ except (ContentReadError, GitError, ConfigError, OSError, ValueError, TypeError):
84
+ return False
85
+ if raw.get("status") != "PASS" or raw.get("diff_sha256") != expected:
86
+ return False
87
+ repository = raw.get("repository")
88
+ if not isinstance(repository, dict) or repository.get("root") != str(root.resolve()):
89
+ return False
90
+ if repository.get("head") != head(root) or raw.get("binding") != current_binding:
91
+ return False
92
+ checks = raw.get("checks")
93
+ if not isinstance(checks, list) or not checks:
94
+ return False
95
+ allowed = {"PASS", "NOT_APPLICABLE", "pass", "skipped"}
96
+ return (
97
+ all(isinstance(check, dict) and check.get("status") in allowed for check in checks)
98
+ and any(check.get("status") in {"PASS", "pass"} for check in checks)
99
+ )
100
+
101
+
102
+ def _atomic_json(path: Path, value: dict[str, Any]) -> None:
103
+ path.parent.mkdir(parents=True, exist_ok=True)
104
+ fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
105
+ try:
106
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
107
+ json.dump(value, handle, sort_keys=True, indent=2)
108
+ handle.write("\n")
109
+ handle.flush()
110
+ os.fsync(handle.fileno())
111
+ os.chmod(temporary, 0o600)
112
+ os.replace(temporary, path)
113
+ finally:
114
+ if os.path.exists(temporary):
115
+ os.unlink(temporary)