codeveto 0.1.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.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/ai/runner.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""One AI pass against a provider: budgets, deadline and bounded concurrency (SPEC 9.5).
|
|
2
|
+
|
|
3
|
+
:func:`run` sends the packets of a :class:`~codeveto.ai.packets.PacketSet` in
|
|
4
|
+
order and verifies every answer as it arrives:
|
|
5
|
+
|
|
6
|
+
- The pass starts only when the secrets pack is registered (otherwise packets
|
|
7
|
+
could carry unredacted secrets to a network provider) and the provider's
|
|
8
|
+
:meth:`~codeveto.ai.providers.Provider.prepare` (SDK import, credentials,
|
|
9
|
+
capability step) succeeds; otherwise it is ``failed`` and not ``started``.
|
|
10
|
+
- Packet 1 is sent alone, so the cacheable system prompt is written once
|
|
11
|
+
before the rest go out, at most ``concurrency`` at a time.
|
|
12
|
+
- Budgets are reserved before a packet is sent, so the totals never exceed
|
|
13
|
+
them: every request in flight holds its ``max_tokens`` against
|
|
14
|
+
``max_total_output_tokens`` and an upper bound of its input (the UTF-8
|
|
15
|
+
bytes of the system prompt with the wire schema, of the packet, and a
|
|
16
|
+
fixed allowance for message framing; a token is never shorter than a
|
|
17
|
+
byte) against ``max_total_input_tokens``, until its usage replaces the
|
|
18
|
+
reservation. A packet's ``max_tokens`` is ``max_output_tokens``, lowered to
|
|
19
|
+
the output budget left after usage and reservations; a packet is
|
|
20
|
+
``skipped`` (``input token budget``, ``output token budget``) when its
|
|
21
|
+
reservation does not fit, when less than :data:`MIN_OUTPUT_TOKENS` of
|
|
22
|
+
output would be left, once the deadline has passed, or after an abort. A
|
|
23
|
+
request's timeout is 180 s or the time left before the deadline. Requests
|
|
24
|
+
still in flight at the deadline are abandoned (``error``, ``deadline``) and
|
|
25
|
+
keep their reservations: worker threads are daemons, so a hung request
|
|
26
|
+
never keeps the process alive.
|
|
27
|
+
- Outcomes map to packet statuses: an answer that verifies (even with every
|
|
28
|
+
finding rejected) is ``verified``; an unusable answer, an error, an
|
|
29
|
+
unexpected stop or an abort is ``error``; ``truncated`` and ``refused`` keep
|
|
30
|
+
their names. An ``abort`` stops the pass: the remaining packets are skipped,
|
|
31
|
+
and when no packet had verified yet the pass counts as not ``started`` (the
|
|
32
|
+
AI was unavailable, like a failed capability step).
|
|
33
|
+
- Usage adds up every outcome's counters. The pass is ``complete`` when every
|
|
34
|
+
packet verified and nothing was left out for a non-deliberate reason,
|
|
35
|
+
``failed`` when no packet verified, else ``partial``.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import queue
|
|
41
|
+
import threading
|
|
42
|
+
import time
|
|
43
|
+
from collections import deque
|
|
44
|
+
from collections.abc import Callable
|
|
45
|
+
from dataclasses import dataclass, field
|
|
46
|
+
|
|
47
|
+
from codeveto.ai import prompt
|
|
48
|
+
from codeveto.ai.packets import Packet, PacketSet
|
|
49
|
+
from codeveto.ai.providers import Outcome, Provider, ProviderUnavailable, Request, Usage
|
|
50
|
+
from codeveto.ai.verify import Rejection, Verified, Verifier
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"FRAMING_TOKENS",
|
|
54
|
+
"MIN_OUTPUT_TOKENS",
|
|
55
|
+
"NO_REDACTION",
|
|
56
|
+
"REQUEST_TIMEOUT_S",
|
|
57
|
+
"PacketResult",
|
|
58
|
+
"Pass",
|
|
59
|
+
"failed_to_start",
|
|
60
|
+
"pass_status",
|
|
61
|
+
"run",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
REQUEST_TIMEOUT_S = 180.0
|
|
65
|
+
FRAMING_TOKENS = 512
|
|
66
|
+
"""Input allowance per request for roles, message framing and structured-output setup."""
|
|
67
|
+
MIN_OUTPUT_TOKENS = 1024
|
|
68
|
+
"""A packet is not sent with less output room than this (``output token budget``)."""
|
|
69
|
+
NO_REDACTION = (
|
|
70
|
+
"the secrets pack is not installed, so packets could not be redacted; "
|
|
71
|
+
"no code was sent to the provider"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True, slots=True)
|
|
76
|
+
class PacketResult:
|
|
77
|
+
packet_id: str
|
|
78
|
+
path: str
|
|
79
|
+
status: str # verified | refused | truncated | error | skipped
|
|
80
|
+
reason: str | None = None
|
|
81
|
+
served_model: str | None = None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(slots=True)
|
|
85
|
+
class Pass:
|
|
86
|
+
"""The outcome of one AI pass (network provider or harness)."""
|
|
87
|
+
|
|
88
|
+
status: str
|
|
89
|
+
provider: str
|
|
90
|
+
model: str | None
|
|
91
|
+
endpoint: str | None
|
|
92
|
+
effort: str | None
|
|
93
|
+
run_id: str | None
|
|
94
|
+
packets: list[PacketResult] = field(default_factory=list)
|
|
95
|
+
coverage: list[tuple[str, str]] = field(default_factory=list)
|
|
96
|
+
gaps: list[tuple[str, str]] = field(default_factory=list)
|
|
97
|
+
usage: Usage = field(default_factory=Usage)
|
|
98
|
+
verified: list[Verified] = field(default_factory=list)
|
|
99
|
+
rejections: list[Rejection] = field(default_factory=list)
|
|
100
|
+
problem: str | None = None
|
|
101
|
+
started: bool = True
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def pass_status(results: list[PacketResult], packets: PacketSet) -> str:
|
|
105
|
+
"""``complete``, ``partial`` or ``failed`` for the packet results of a pass."""
|
|
106
|
+
verified = sum(1 for r in results if r.status == "verified")
|
|
107
|
+
if packets.packets and verified == 0:
|
|
108
|
+
return "failed"
|
|
109
|
+
if verified < len(packets.packets) or packets.partial:
|
|
110
|
+
return "partial"
|
|
111
|
+
return "complete"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def failed_to_start(
|
|
115
|
+
packets: PacketSet,
|
|
116
|
+
problem: str,
|
|
117
|
+
*,
|
|
118
|
+
provider: str,
|
|
119
|
+
model: str | None = None,
|
|
120
|
+
endpoint: str | None = None,
|
|
121
|
+
effort: str | None = None,
|
|
122
|
+
) -> Pass:
|
|
123
|
+
"""A pass that could not start: every packet ``skipped``, status ``failed``."""
|
|
124
|
+
return Pass(
|
|
125
|
+
status="failed",
|
|
126
|
+
provider=provider,
|
|
127
|
+
model=model,
|
|
128
|
+
endpoint=endpoint,
|
|
129
|
+
effort=effort,
|
|
130
|
+
run_id=packets.run_id,
|
|
131
|
+
packets=[
|
|
132
|
+
PacketResult(p.packet_id, p.path, "skipped", "the AI pass did not start")
|
|
133
|
+
for p in packets.packets
|
|
134
|
+
],
|
|
135
|
+
coverage=list(packets.coverage),
|
|
136
|
+
gaps=list(packets.gaps),
|
|
137
|
+
problem=problem,
|
|
138
|
+
started=False,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class _Settings:
|
|
143
|
+
"""The budget fields the runner reads from ``AISettings`` (or a test double)."""
|
|
144
|
+
|
|
145
|
+
def __init__(self, settings: object) -> None:
|
|
146
|
+
self.max_output_tokens = int(getattr(settings, "max_output_tokens", 32_000))
|
|
147
|
+
total_in = getattr(settings, "max_total_input_tokens", None)
|
|
148
|
+
total_out = getattr(settings, "max_total_output_tokens", None)
|
|
149
|
+
self.max_total_input = None if total_in is None else int(total_in)
|
|
150
|
+
self.max_total_output = None if total_out is None else int(total_out)
|
|
151
|
+
self.deadline_s = float(getattr(settings, "deadline_s", 600.0))
|
|
152
|
+
self.concurrency = max(1, int(getattr(settings, "concurrency", 4)))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def run(
|
|
156
|
+
provider: Provider,
|
|
157
|
+
packets: PacketSet,
|
|
158
|
+
settings: object,
|
|
159
|
+
*,
|
|
160
|
+
clock: Callable[[], float] = time.monotonic,
|
|
161
|
+
) -> Pass:
|
|
162
|
+
"""Run one pass (see the module docstring)."""
|
|
163
|
+
budget = _Settings(settings)
|
|
164
|
+
if packets.packets and not packets.redaction:
|
|
165
|
+
return failed_to_start(packets, NO_REDACTION, provider=provider.name, model=provider.model)
|
|
166
|
+
if packets.packets:
|
|
167
|
+
try:
|
|
168
|
+
provider.prepare()
|
|
169
|
+
except ProviderUnavailable as exc:
|
|
170
|
+
return failed_to_start(
|
|
171
|
+
packets,
|
|
172
|
+
str(exc),
|
|
173
|
+
provider=provider.name,
|
|
174
|
+
model=provider.model,
|
|
175
|
+
endpoint=provider.endpoint,
|
|
176
|
+
)
|
|
177
|
+
result = Pass(
|
|
178
|
+
status="complete",
|
|
179
|
+
provider=provider.name,
|
|
180
|
+
model=provider.model,
|
|
181
|
+
endpoint=provider.endpoint,
|
|
182
|
+
effort=provider.effort,
|
|
183
|
+
run_id=packets.run_id,
|
|
184
|
+
coverage=list(packets.coverage),
|
|
185
|
+
gaps=list(packets.gaps),
|
|
186
|
+
)
|
|
187
|
+
verifier = Verifier(secrets=packets.secrets)
|
|
188
|
+
deadline = clock() + budget.deadline_s
|
|
189
|
+
done: dict[int, PacketResult] = {}
|
|
190
|
+
pending: deque[tuple[int, Packet]] = deque(enumerate(packets.packets))
|
|
191
|
+
inflight: dict[int, tuple[Packet, tuple[int, int]]] = {}
|
|
192
|
+
answers: queue.Queue[tuple[int, Outcome]] = queue.Queue()
|
|
193
|
+
aborted: list[str] = []
|
|
194
|
+
first = True
|
|
195
|
+
|
|
196
|
+
def worker(index: int, request: Request) -> None:
|
|
197
|
+
try:
|
|
198
|
+
outcome = provider.review(request)
|
|
199
|
+
except Exception as exc: # an adapter bug fails its packet, never the process
|
|
200
|
+
outcome = Outcome("error", reason=f"the provider failed ({type(exc).__name__})")
|
|
201
|
+
answers.put((index, outcome))
|
|
202
|
+
|
|
203
|
+
reserved = {"input": 0, "output": 0}
|
|
204
|
+
prompt_bytes = len(prompt.system_prompt(embed_schema=True).encode("utf-8"))
|
|
205
|
+
|
|
206
|
+
def input_bound(packet: Packet) -> int:
|
|
207
|
+
return prompt_bytes + len(packet.message.encode("utf-8")) + FRAMING_TOKENS
|
|
208
|
+
|
|
209
|
+
def skip_reason(packet: Packet) -> str | None:
|
|
210
|
+
if aborted:
|
|
211
|
+
return "the AI pass was aborted"
|
|
212
|
+
if clock() >= deadline:
|
|
213
|
+
return "deadline"
|
|
214
|
+
if budget.max_total_input is not None and (
|
|
215
|
+
result.usage.total_input + reserved["input"] + input_bound(packet)
|
|
216
|
+
> budget.max_total_input
|
|
217
|
+
):
|
|
218
|
+
return "input token budget"
|
|
219
|
+
if budget.max_total_output is not None and (
|
|
220
|
+
budget.max_total_output - result.usage.output_tokens - reserved["output"]
|
|
221
|
+
< MIN_OUTPUT_TOKENS
|
|
222
|
+
):
|
|
223
|
+
return "output token budget"
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
def send(index: int, packet: Packet) -> None:
|
|
227
|
+
reason = skip_reason(packet)
|
|
228
|
+
if reason is not None:
|
|
229
|
+
done[index] = PacketResult(packet.packet_id, packet.path, "skipped", reason)
|
|
230
|
+
return
|
|
231
|
+
max_tokens = budget.max_output_tokens
|
|
232
|
+
if budget.max_total_output is not None:
|
|
233
|
+
room = budget.max_total_output - result.usage.output_tokens - reserved["output"]
|
|
234
|
+
max_tokens = min(max_tokens, room)
|
|
235
|
+
timeout = max(1.0, min(REQUEST_TIMEOUT_S, deadline - clock()))
|
|
236
|
+
request = Request(packet.packet_id, packet.message, max_tokens, timeout)
|
|
237
|
+
holds = (input_bound(packet), max_tokens)
|
|
238
|
+
reserved["input"] += holds[0]
|
|
239
|
+
reserved["output"] += holds[1]
|
|
240
|
+
inflight[index] = (packet, holds)
|
|
241
|
+
threading.Thread(target=worker, args=(index, request), daemon=True).start()
|
|
242
|
+
|
|
243
|
+
while pending or inflight:
|
|
244
|
+
limit = 1 if first else budget.concurrency
|
|
245
|
+
while pending and len(inflight) < limit:
|
|
246
|
+
send(*pending.popleft())
|
|
247
|
+
if not inflight:
|
|
248
|
+
continue
|
|
249
|
+
try:
|
|
250
|
+
index, outcome = answers.get(timeout=max(0.0, deadline - clock()))
|
|
251
|
+
except queue.Empty:
|
|
252
|
+
if clock() < deadline:
|
|
253
|
+
continue
|
|
254
|
+
for index, (packet, _) in sorted(inflight.items()):
|
|
255
|
+
done[index] = PacketResult(packet.packet_id, packet.path, "error", "deadline")
|
|
256
|
+
inflight.clear()
|
|
257
|
+
continue
|
|
258
|
+
first = False
|
|
259
|
+
packet, (held_input, held_output) = inflight.pop(index)
|
|
260
|
+
reserved["input"] -= held_input
|
|
261
|
+
reserved["output"] -= held_output
|
|
262
|
+
result.usage = result.usage + outcome.usage
|
|
263
|
+
done[index] = _handle(packet, outcome, verifier, result, aborted)
|
|
264
|
+
result.packets = [done[i] for i in sorted(done)]
|
|
265
|
+
result.status = pass_status(result.packets, packets)
|
|
266
|
+
if aborted:
|
|
267
|
+
result.problem = aborted[0]
|
|
268
|
+
# Rejected credentials, an unknown model or a rejected request before any
|
|
269
|
+
# packet verified: the AI was unavailable, as if the capability step failed.
|
|
270
|
+
result.started = any(r.status == "verified" for r in result.packets)
|
|
271
|
+
return result
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _handle(
|
|
275
|
+
packet: Packet, outcome: Outcome, verifier: Verifier, result: Pass, aborted: list[str]
|
|
276
|
+
) -> PacketResult:
|
|
277
|
+
served = outcome.served_model
|
|
278
|
+
|
|
279
|
+
def packet_result(status: str, reason: str | None) -> PacketResult:
|
|
280
|
+
return PacketResult(packet.packet_id, packet.path, status, reason, served)
|
|
281
|
+
|
|
282
|
+
if outcome.status == "ok":
|
|
283
|
+
verified, rejections, error = verifier.response(packet, outcome.text or "")
|
|
284
|
+
result.verified += verified
|
|
285
|
+
result.rejections += rejections
|
|
286
|
+
if error is not None:
|
|
287
|
+
return packet_result("error", f"the response was rejected ({error})")
|
|
288
|
+
return packet_result("verified", None)
|
|
289
|
+
if outcome.status in ("truncated", "refused"):
|
|
290
|
+
return packet_result(outcome.status, outcome.reason)
|
|
291
|
+
if outcome.status == "abort":
|
|
292
|
+
aborted.append(outcome.reason or "the provider aborted the pass")
|
|
293
|
+
return packet_result("error", outcome.reason or outcome.status)
|
codeveto/ai/verify.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""Verification of AI responses against the packets they answer (SPEC 9.3).
|
|
2
|
+
|
|
3
|
+
Nothing a model (or a harness's agent) returns is trusted. A response is
|
|
4
|
+
parsed strictly (:func:`parse`: size cap, no duplicate keys, no NaN or
|
|
5
|
+
Infinity, no oversized integers), its envelope is validated against the wire
|
|
6
|
+
schema with :mod:`codeveto.schema`, and then every finding is checked in this
|
|
7
|
+
order; the first failure is its rejection reason:
|
|
8
|
+
|
|
9
|
+
1. ``schema``: the finding fails the wire schema's finding object, its
|
|
10
|
+
``line`` is not an ``int`` (``type(x) is int``) or is below 1.
|
|
11
|
+
2. ``bounds``: after cleaning (control and format characters replaced,
|
|
12
|
+
whitespace collapsed, secrets redacted), an empty or over-long ``title``
|
|
13
|
+
(120 characters), ``explanation`` or ``suggestion`` (600); findings beyond
|
|
14
|
+
the eighth of a packet are rejected together as one ``bounds`` rejection.
|
|
15
|
+
3. ``unknown_packet``: the finding names another packet than the response.
|
|
16
|
+
4. ``path_mismatch``: the path is not the packet's path for that side.
|
|
17
|
+
5. ``line_not_changed``: the line is not one of the packet's own changed
|
|
18
|
+
lines on that side.
|
|
19
|
+
6. ``trivial_anchor``: the cited line has fewer than 3 alphanumeric
|
|
20
|
+
characters.
|
|
21
|
+
7. ``quote_mismatch``: after NFC normalization, removal of Cf characters and
|
|
22
|
+
stripping ASCII spaces and tabs at both ends, the quote does not equal the
|
|
23
|
+
**redacted** packet text of that line.
|
|
24
|
+
8. ``url_in_text``: title, explanation or suggestion contains ``://``,
|
|
25
|
+
``www.``, ``javascript:``, ``data:``/``mailto:``/``vbscript:`` URLs (after
|
|
26
|
+
any non-alphanumeric character, ``_`` included), a protocol-relative
|
|
27
|
+
``//host.tld``, a Markdown link to a URL or path, an image or an HTML link,
|
|
28
|
+
also once format characters are removed and NFKC is applied.
|
|
29
|
+
9. ``duplicate``: a verified finding already has the same ``(path, side,
|
|
30
|
+
line, category)``.
|
|
31
|
+
|
|
32
|
+
A verified finding's prose has control and format characters replaced by
|
|
33
|
+
spaces and every known secret value redacted (:func:`codeveto.redact.redact_text`).
|
|
34
|
+
Response-level problems (unparseable, too large, bad envelope) reject the
|
|
35
|
+
response as a whole (``schema`` or ``bounds``); a response for an unknown or
|
|
36
|
+
stale packet is ``unknown_packet`` or ``stale_run``. Rejection details are
|
|
37
|
+
written by CodeVeto (counts and numbers), never copied from the response.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import re
|
|
43
|
+
import unicodedata
|
|
44
|
+
from collections.abc import Mapping, Sequence
|
|
45
|
+
from dataclasses import dataclass
|
|
46
|
+
from typing import Any
|
|
47
|
+
|
|
48
|
+
from codeveto import jsonsafe, redact, schema
|
|
49
|
+
from codeveto.ai import prompt
|
|
50
|
+
from codeveto.ai.packets import Packet
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"REASONS",
|
|
54
|
+
"Rejection",
|
|
55
|
+
"ResponseError",
|
|
56
|
+
"Verified",
|
|
57
|
+
"Verifier",
|
|
58
|
+
"normalize_quote",
|
|
59
|
+
"parse",
|
|
60
|
+
"safe_id",
|
|
61
|
+
"trivial",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
REASONS: tuple[str, ...] = (
|
|
65
|
+
"unknown_packet",
|
|
66
|
+
"stale_run",
|
|
67
|
+
"path_mismatch",
|
|
68
|
+
"line_not_changed",
|
|
69
|
+
"quote_mismatch",
|
|
70
|
+
"trivial_anchor",
|
|
71
|
+
"schema",
|
|
72
|
+
"bounds",
|
|
73
|
+
"url_in_text",
|
|
74
|
+
"duplicate",
|
|
75
|
+
)
|
|
76
|
+
"""The fixed ``ai.rejections[].reason`` enum (SPEC 9.3)."""
|
|
77
|
+
|
|
78
|
+
_MIN_ALNUM = 3
|
|
79
|
+
_URL = re.compile(
|
|
80
|
+
r"://" # any scheme, wherever it starts (a GFM autolink after "_" too)
|
|
81
|
+
r"|(?<![a-z0-9])www\." # www. after anything but a letter or digit
|
|
82
|
+
r"|(?<![a-z0-9])javascript:"
|
|
83
|
+
r"|(?<![a-z0-9])(?:data|mailto|vbscript):\S"
|
|
84
|
+
r"|(?<![a-z0-9:/])//[a-z0-9\-]+(?:\.[a-z0-9\-]+)+" # protocol-relative //host.tld
|
|
85
|
+
r"|!\[" # Markdown image
|
|
86
|
+
r"|\]\(\s*(?:[a-z][a-z0-9+.\-]{0,30}:|/|#|\.{1,2}/)" # Markdown link to a URL or path
|
|
87
|
+
r"|<\s*(?:a\s+href|img\s)", # HTML link or image
|
|
88
|
+
re.IGNORECASE,
|
|
89
|
+
)
|
|
90
|
+
_UNSAFE = frozenset({"Cc", "Cf", "Cs", "Zl", "Zp"})
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ResponseError(ValueError):
|
|
94
|
+
"""A response that cannot be used at all; ``reason`` is ``schema`` or ``bounds``."""
|
|
95
|
+
|
|
96
|
+
def __init__(self, reason: str, detail: str) -> None:
|
|
97
|
+
super().__init__(detail)
|
|
98
|
+
self.reason = reason
|
|
99
|
+
self.detail = detail
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
103
|
+
result: dict[str, Any] = {}
|
|
104
|
+
for key, value in pairs:
|
|
105
|
+
if key in result:
|
|
106
|
+
raise ResponseError("schema", "the JSON has a duplicate key")
|
|
107
|
+
result[key] = value
|
|
108
|
+
return result
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _no_constant(name: str) -> object:
|
|
112
|
+
raise ResponseError("schema", "the JSON has NaN or Infinity")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def parse(raw: str | bytes, *, limit: int = prompt.MAX_RESPONSE_BYTES) -> object:
|
|
116
|
+
"""Strict JSON: at most ``limit`` UTF-8 bytes, no duplicate keys, no NaN/Infinity."""
|
|
117
|
+
data = raw.encode("utf-8", "surrogatepass") if isinstance(raw, str) else bytes(raw)
|
|
118
|
+
if len(data) > limit:
|
|
119
|
+
raise ResponseError("bounds", f"the response is larger than {limit // 1024} KiB")
|
|
120
|
+
try:
|
|
121
|
+
text = data.decode("utf-8")
|
|
122
|
+
except UnicodeDecodeError:
|
|
123
|
+
raise ResponseError("schema", "the response is not UTF-8") from None
|
|
124
|
+
try:
|
|
125
|
+
return jsonsafe.loads(
|
|
126
|
+
text.removeprefix("\N{ZERO WIDTH NO-BREAK SPACE}"),
|
|
127
|
+
object_pairs_hook=_no_duplicates,
|
|
128
|
+
parse_constant=_no_constant,
|
|
129
|
+
)
|
|
130
|
+
except ResponseError:
|
|
131
|
+
raise
|
|
132
|
+
except (ValueError, RecursionError):
|
|
133
|
+
raise ResponseError("schema", "the response is not valid JSON") from None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def normalize_quote(text: str) -> str:
|
|
137
|
+
"""NFC, Cf characters removed, ASCII spaces and tabs stripped at both ends."""
|
|
138
|
+
nfc = unicodedata.normalize("NFC", text)
|
|
139
|
+
kept = "".join(c for c in nfc if unicodedata.category(c) != "Cf")
|
|
140
|
+
return kept.strip(" \t")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def trivial(text: str) -> bool:
|
|
144
|
+
"""Has the line fewer than 3 alphanumeric characters (``trivial_anchor``)?"""
|
|
145
|
+
count = 0
|
|
146
|
+
for char in normalize_quote(text):
|
|
147
|
+
if char.isalnum():
|
|
148
|
+
count += 1
|
|
149
|
+
if count >= _MIN_ALNUM:
|
|
150
|
+
return False
|
|
151
|
+
return True
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _without_cf(text: str) -> str:
|
|
155
|
+
"""``text`` without format characters (a URL split by zero-width characters shows)."""
|
|
156
|
+
return "".join(c for c in text if unicodedata.category(c) != "Cf")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _has_link(text: str) -> bool:
|
|
160
|
+
"""A URL, link or image in ``text``, also once format characters are gone and NFKC applied."""
|
|
161
|
+
bare = _without_cf(text)
|
|
162
|
+
return any(_URL.search(v) for v in (text, bare, unicodedata.normalize("NFKC", bare)))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _plain(text: str) -> str:
|
|
166
|
+
"""Control and format characters as spaces, whitespace runs collapsed."""
|
|
167
|
+
return " ".join("".join(" " if unicodedata.category(c) in _UNSAFE else c for c in text).split())
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _clean(text: str, secrets: Sequence[str]) -> str:
|
|
171
|
+
return (redact.redact_text(_plain(text), secrets) or "").strip()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@dataclass(frozen=True, slots=True)
|
|
175
|
+
class Rejection:
|
|
176
|
+
packet_id: str
|
|
177
|
+
reason: str
|
|
178
|
+
detail: str | None = None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass(frozen=True, slots=True)
|
|
182
|
+
class Verified:
|
|
183
|
+
"""A finding that passed every check; prose is cleaned and redacted."""
|
|
184
|
+
|
|
185
|
+
packet_id: str
|
|
186
|
+
path: str
|
|
187
|
+
old_path: str | None
|
|
188
|
+
file_class: str
|
|
189
|
+
side: str
|
|
190
|
+
line: int
|
|
191
|
+
text: str # the redacted packet text of the cited line
|
|
192
|
+
category: str
|
|
193
|
+
severity: str
|
|
194
|
+
title: str
|
|
195
|
+
explanation: str
|
|
196
|
+
suggestion: str
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class Verifier:
|
|
200
|
+
"""Checks responses for one run; keeps the duplicate keys across packets.
|
|
201
|
+
|
|
202
|
+
``secrets`` are the raw secret values the packets redacted; they are
|
|
203
|
+
redacted from AI prose too.
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
def __init__(self, secrets: Sequence[str] = ()) -> None:
|
|
207
|
+
self.secrets = tuple(secrets)
|
|
208
|
+
self.seen: set[tuple[str, str, int, str]] = set()
|
|
209
|
+
wire = prompt.wire_schema()
|
|
210
|
+
self._finding_schema: dict[str, Any] = wire["properties"]["findings"]["items"]
|
|
211
|
+
self._envelope_schema: dict[str, Any] = {
|
|
212
|
+
**wire,
|
|
213
|
+
"properties": {**wire["properties"], "findings": {"type": "array"}},
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
def envelope(self, value: object) -> tuple[str, list[object]]:
|
|
217
|
+
"""``(packet_id, findings)`` of a response object, or :class:`ResponseError`."""
|
|
218
|
+
if not isinstance(value, Mapping) or schema.validate(value, self._envelope_schema):
|
|
219
|
+
raise ResponseError("schema", "the response does not match the wire schema")
|
|
220
|
+
return value["packet_id"], list(value["findings"])
|
|
221
|
+
|
|
222
|
+
def check(
|
|
223
|
+
self, packet: Packet, findings: Sequence[object]
|
|
224
|
+
) -> tuple[list[Verified], list[Rejection]]:
|
|
225
|
+
"""Verify the findings of one response to ``packet``."""
|
|
226
|
+
verified: list[Verified] = []
|
|
227
|
+
rejections: list[Rejection] = []
|
|
228
|
+
pid = packet.packet_id
|
|
229
|
+
limit = prompt.MAX_FINDINGS_PER_PACKET
|
|
230
|
+
for index, item in enumerate(findings[:limit], 1):
|
|
231
|
+
outcome = self._one(packet, item, index)
|
|
232
|
+
if isinstance(outcome, Rejection):
|
|
233
|
+
rejections.append(outcome)
|
|
234
|
+
else:
|
|
235
|
+
verified.append(outcome)
|
|
236
|
+
extra = len(findings) - limit
|
|
237
|
+
if extra > 0:
|
|
238
|
+
rejections.append(
|
|
239
|
+
Rejection(pid, "bounds", f"{extra} finding(s) beyond the {limit}-finding limit")
|
|
240
|
+
)
|
|
241
|
+
return verified, rejections
|
|
242
|
+
|
|
243
|
+
def _one(self, packet: Packet, item: object, index: int) -> Verified | Rejection:
|
|
244
|
+
pid = packet.packet_id
|
|
245
|
+
|
|
246
|
+
def reject(reason: str, detail: str) -> Rejection:
|
|
247
|
+
return Rejection(pid, reason, f"finding {index}: {detail}")
|
|
248
|
+
|
|
249
|
+
if not isinstance(item, Mapping) or schema.validate(item, self._finding_schema):
|
|
250
|
+
return reject("schema", "does not match the wire schema")
|
|
251
|
+
line = item["line"]
|
|
252
|
+
if type(line) is not int or line < 1:
|
|
253
|
+
return reject("schema", "line must be an integer of at least 1")
|
|
254
|
+
title, explanation, suggestion = item["title"], item["explanation"], item["suggestion"]
|
|
255
|
+
cleaned = {
|
|
256
|
+
name: _clean(item[name], self.secrets)
|
|
257
|
+
for name in ("title", "explanation", "suggestion")
|
|
258
|
+
}
|
|
259
|
+
for name, cap in (
|
|
260
|
+
("title", prompt.MAX_TITLE_CHARS),
|
|
261
|
+
("explanation", prompt.MAX_EXPLANATION_CHARS),
|
|
262
|
+
("suggestion", prompt.MAX_SUGGESTION_CHARS),
|
|
263
|
+
):
|
|
264
|
+
if not 1 <= len(cleaned[name]) <= cap:
|
|
265
|
+
return reject("bounds", f"{name} must have 1 to {cap} characters")
|
|
266
|
+
if item["packet_id"] != pid:
|
|
267
|
+
return reject("unknown_packet", "names a different packet")
|
|
268
|
+
side = item["side"]
|
|
269
|
+
if item["path"] != packet.path_for(side):
|
|
270
|
+
return reject("path_mismatch", f"the path is not this packet's {side}-side path")
|
|
271
|
+
text = packet.anchors.get((side, line))
|
|
272
|
+
if text is None:
|
|
273
|
+
return reject("line_not_changed", f"{side} line {line} is not a changed line here")
|
|
274
|
+
if trivial(text):
|
|
275
|
+
return reject("trivial_anchor", f"{side} line {line} has too little content to cite")
|
|
276
|
+
if normalize_quote(item["quote"]) != normalize_quote(text):
|
|
277
|
+
return reject("quote_mismatch", f"the quote does not match {side} line {line}")
|
|
278
|
+
if any(_has_link(v) for v in (title, explanation, suggestion)):
|
|
279
|
+
return reject("url_in_text", "the text contains a URL, link or image")
|
|
280
|
+
category = item["category"]
|
|
281
|
+
key = (packet.path, side, line, category)
|
|
282
|
+
if key in self.seen:
|
|
283
|
+
return reject("duplicate", f"{side} line {line} already has a {category} finding")
|
|
284
|
+
self.seen.add(key)
|
|
285
|
+
return Verified(
|
|
286
|
+
packet_id=pid,
|
|
287
|
+
path=packet.path,
|
|
288
|
+
old_path=packet.old_path,
|
|
289
|
+
file_class=packet.file_class,
|
|
290
|
+
side=side,
|
|
291
|
+
line=line,
|
|
292
|
+
text=text,
|
|
293
|
+
category=category,
|
|
294
|
+
severity=item["severity"],
|
|
295
|
+
title=cleaned["title"],
|
|
296
|
+
explanation=cleaned["explanation"],
|
|
297
|
+
suggestion=cleaned["suggestion"],
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
def response(
|
|
301
|
+
self, packet: Packet, raw: str | bytes
|
|
302
|
+
) -> tuple[list[Verified], list[Rejection], str | None]:
|
|
303
|
+
"""Verify one provider response (text) to ``packet``.
|
|
304
|
+
|
|
305
|
+
Returns ``(verified, rejections, error)``; ``error`` is set (and the
|
|
306
|
+
response rejected as a whole) when the response could not be used.
|
|
307
|
+
"""
|
|
308
|
+
try:
|
|
309
|
+
value = parse(raw)
|
|
310
|
+
packet_id, findings = self.envelope(value)
|
|
311
|
+
except ResponseError as exc:
|
|
312
|
+
return [], [Rejection(packet.packet_id, exc.reason, exc.detail)], exc.reason
|
|
313
|
+
if packet_id != packet.packet_id:
|
|
314
|
+
detail = "the response names a different packet"
|
|
315
|
+
return [], [Rejection(packet.packet_id, "unknown_packet", detail)], "unknown_packet"
|
|
316
|
+
verified, rejections = self.check(packet, findings)
|
|
317
|
+
return verified, rejections, None
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def safe_id(value: object) -> str:
|
|
321
|
+
"""A packet ID fit for a rejection record: the value when it looks like one, else a label."""
|
|
322
|
+
if isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value):
|
|
323
|
+
return value
|
|
324
|
+
return "(invalid)"
|