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.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """CodeVeto: strict, deterministic-first code review for Git changes."""
2
+
3
+ __version__ = "0.1.0"
codeveto/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Allow running CodeVeto with ``python -m codeveto``."""
2
+
3
+ import sys
4
+
5
+ from codeveto.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1,19 @@
1
+ """The optional AI pass (SPEC 9): packets, providers, verification, budgets, report policy.
2
+
3
+ Deterministic rules stay the verdict's backbone; the AI pass only adds
4
+ findings that survive :mod:`codeveto.ai.verify`, each anchored to a changed
5
+ line by an exact quote. Repository text reaches a model only inside packets
6
+ (:mod:`codeveto.ai.packets`), as JSON data in the user turn, never in the
7
+ fixed system prompt (:mod:`codeveto.ai.prompt`).
8
+
9
+ - :mod:`codeveto.ai.packets`: line objects, context, 24 KiB packets, secret
10
+ redaction, sensitive-path exclusion, risk ordering, ``packet_id``/``run_id``.
11
+ - :mod:`codeveto.ai.verify`: strict parsing and every rejection reason.
12
+ - :mod:`codeveto.ai.providers`: ``claude`` and ``openai`` adapters (optional
13
+ SDKs imported lazily inside them).
14
+ - :mod:`codeveto.ai.runner`: budgets, deadline and bounded concurrency.
15
+ - :mod:`codeveto.ai.policy`: the report ``ai`` section, AI findings and the
16
+ verdict policy (``blocking``, ``required``, ``--ai-optional``).
17
+ - :mod:`codeveto.ai.harness`: ``codeveto packets`` / ``codeveto verify`` as
18
+ library functions (also used by the MCP server).
19
+ """
codeveto/ai/harness.py ADDED
@@ -0,0 +1,303 @@
1
+ """Harness mode (SPEC 9.4): the agent of the harness answers the packets, CodeVeto verifies.
2
+
3
+ No network is involved. :func:`build_packets` is ``codeveto packets``: the
4
+ document ``{protocol, run_id, base, head, snapshot, instructions,
5
+ wire_schema, packets[]}``. The agent answers with a responses document
6
+ ``{"run_id": ..., "responses": [{"packet_id": ..., "findings": [...]}]}``
7
+ holding exactly one entry per packet (empty findings mean "nothing to
8
+ report"). :func:`verify_responses` is ``codeveto verify``: it runs a fresh
9
+ intake and the rules, **regenerates** the packets, and checks the document
10
+ against them:
11
+
12
+ - a document that is not strict JSON, does not have exactly ``run_id`` and
13
+ ``responses``, or whose ``run_id`` is not the fresh run's (``stale_run``,
14
+ the change moved since ``codeveto packets``) means the pass could not be
15
+ done: it is ``failed`` and the review ``incomplete``;
16
+ - an entry for a packet the fresh run does not have is ``unknown_packet``, a
17
+ second entry for one packet ``duplicate``, a malformed or oversized entry
18
+ ``schema`` or ``bounds``; a packet without an entry is ``skipped`` (``no
19
+ response``);
20
+ - every finding goes through :class:`codeveto.ai.verify.Verifier`.
21
+
22
+ The result is a full JSON report v1 with ``ai.provider = "harness"``, under
23
+ the same policy as a network pass (:mod:`codeveto.ai.policy`).
24
+ :func:`read_responses_file` reads the file the CLI is given: a regular file
25
+ opened with ``O_NONBLOCK`` (a FIFO or device never blocks the review), at
26
+ most 2 MiB.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import os
33
+ import stat
34
+ import time
35
+ from collections.abc import Callable, Mapping
36
+ from typing import Any
37
+
38
+ from codeveto import cli_review, engine, report, schema
39
+ from codeveto.ai import packets as ai_packets
40
+ from codeveto.ai import policy as ai_policy
41
+ from codeveto.ai import prompt
42
+ from codeveto.ai.runner import PacketResult, Pass, failed_to_start, pass_status
43
+ from codeveto.ai.verify import Rejection, ResponseError, Verifier, parse, safe_id
44
+ from codeveto.engine import EngineResult
45
+
46
+ __all__ = [
47
+ "MAX_RESPONSES_BYTES",
48
+ "PROVIDER",
49
+ "HarnessError",
50
+ "build_packets",
51
+ "check_responses",
52
+ "packets_for",
53
+ "read_responses_file",
54
+ "review_with_responses",
55
+ "verify_responses",
56
+ ]
57
+
58
+ PROVIDER = "harness"
59
+ MAX_RESPONSES_BYTES = 2 * 1024 * 1024
60
+ _DOCUMENT_ID = "(responses)"
61
+ _DOCUMENT_SCHEMA: dict[str, Any] = {
62
+ "type": "object",
63
+ "additionalProperties": False,
64
+ "required": ["run_id", "responses"],
65
+ "properties": {"run_id": {"type": "string"}, "responses": {"type": "array"}},
66
+ }
67
+
68
+
69
+ class HarnessError(ValueError):
70
+ """The responses file cannot be read (not a regular file, too large)."""
71
+
72
+
73
+ def read_responses_file(path: str | os.PathLike[str]) -> bytes:
74
+ """The bytes of a responses file: a regular file, opened non-blocking, at most 2 MiB."""
75
+ flags = os.O_RDONLY
76
+ for name in ("O_NONBLOCK", "O_NOCTTY", "O_CLOEXEC", "O_BINARY"):
77
+ flags |= getattr(os, name, 0)
78
+ try:
79
+ fd = os.open(path, flags)
80
+ except OSError:
81
+ # Windows refuses to open a directory (PermissionError); give the same
82
+ # message as the fstat check below on every platform.
83
+ if os.path.isdir(path):
84
+ raise HarnessError("the responses file is not a regular file") from None
85
+ raise
86
+ try:
87
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
88
+ raise HarnessError("the responses file is not a regular file")
89
+ chunks: list[bytes] = []
90
+ size = 0
91
+ while size <= MAX_RESPONSES_BYTES:
92
+ chunk = os.read(fd, min(65536, MAX_RESPONSES_BYTES + 1 - size))
93
+ if not chunk:
94
+ break
95
+ chunks.append(chunk)
96
+ size += len(chunk)
97
+ if size > MAX_RESPONSES_BYTES:
98
+ raise HarnessError("the responses file is larger than 2 MiB")
99
+ return b"".join(chunks)
100
+ finally:
101
+ os.close(fd)
102
+
103
+
104
+ def _args(
105
+ repo: str | os.PathLike[str],
106
+ *,
107
+ base: str | None,
108
+ head: str | None,
109
+ comparison: str | None,
110
+ staged: bool,
111
+ commit: str | None,
112
+ anchor: str | None,
113
+ ) -> argparse.Namespace:
114
+ args = argparse.Namespace(
115
+ repo=os.fspath(repo),
116
+ base=base,
117
+ head=head,
118
+ comparison=comparison,
119
+ staged=staged,
120
+ commit=commit,
121
+ anchor=anchor,
122
+ )
123
+ problem = cli_review.usage_problem(args)
124
+ if problem is not None:
125
+ raise ValueError(problem)
126
+ return args
127
+
128
+
129
+ def packets_for(prepared: cli_review.Prepared) -> ai_packets.PacketSet:
130
+ """The packets of a prepared review, under its trusted config."""
131
+ config = prepared.config
132
+ return ai_packets.build(
133
+ prepared.changeset,
134
+ registry=prepared.registry,
135
+ file_class=config.policy().file_class,
136
+ max_packets=config.ai.max_packets,
137
+ )
138
+
139
+
140
+ def build_packets(
141
+ repo: str | os.PathLike[str] = ".",
142
+ *,
143
+ base: str | None = None,
144
+ head: str | None = None,
145
+ comparison: str | None = None,
146
+ staged: bool = False,
147
+ commit: str | None = None,
148
+ anchor: str | None = None,
149
+ ) -> dict[str, Any]:
150
+ """The ``codeveto packets`` document for a revision selection (as for ``review``)."""
151
+ args = _args(
152
+ repo,
153
+ base=base,
154
+ head=head,
155
+ comparison=comparison,
156
+ staged=staged,
157
+ commit=commit,
158
+ anchor=anchor,
159
+ )
160
+ return packets_for(cli_review.prepare(args)).document()
161
+
162
+
163
+ def _unusable(packets: ai_packets.PacketSet, problem: str, rejections: list[Rejection]) -> Pass:
164
+ run = failed_to_start(packets, problem, provider=PROVIDER)
165
+ run.rejections = rejections
166
+ return run
167
+
168
+
169
+ def check_responses(
170
+ packets: ai_packets.PacketSet, responses: bytes | str | Mapping[str, Any]
171
+ ) -> Pass:
172
+ """Verify a responses document against freshly built ``packets``."""
173
+ try:
174
+ doc = (
175
+ responses
176
+ if isinstance(responses, Mapping)
177
+ else parse(responses, limit=MAX_RESPONSES_BYTES)
178
+ )
179
+ except ResponseError as exc:
180
+ problem = f"the responses document is unusable ({exc.detail})"
181
+ return _unusable(packets, problem, [Rejection(_DOCUMENT_ID, exc.reason, exc.detail)])
182
+ if not isinstance(doc, Mapping) or schema.validate(doc, _DOCUMENT_SCHEMA):
183
+ detail = "the document must be an object with exactly run_id and responses"
184
+ problem = f"the responses document is unusable ({detail})"
185
+ return _unusable(packets, problem, [Rejection(_DOCUMENT_ID, "schema", detail)])
186
+ entries = list(doc["responses"])
187
+ if doc["run_id"] != packets.run_id:
188
+ detail = "the responses are for another run; run codeveto packets again"
189
+ rejections = [
190
+ Rejection(
191
+ safe_id(e.get("packet_id") if isinstance(e, Mapping) else None), "stale_run", detail
192
+ )
193
+ for e in entries
194
+ ] or [Rejection(_DOCUMENT_ID, "stale_run", detail)]
195
+ return _unusable(packets, f"stale run_id: {detail}", rejections)
196
+ verifier = Verifier(secrets=packets.secrets)
197
+ run = Pass(
198
+ status="complete",
199
+ provider=PROVIDER,
200
+ model=None,
201
+ endpoint=None,
202
+ effort=None,
203
+ run_id=packets.run_id,
204
+ coverage=list(packets.coverage),
205
+ gaps=list(packets.gaps),
206
+ )
207
+ statuses: dict[str, PacketResult] = {}
208
+ for number, entry in enumerate(entries, 1):
209
+ try:
210
+ if len(prompt.canonical(entry)) > prompt.MAX_RESPONSE_BYTES:
211
+ raise ResponseError("bounds", "the response is larger than 256 KiB")
212
+ packet_id, findings = verifier.envelope(entry)
213
+ except ResponseError as exc:
214
+ claimed = entry.get("packet_id") if isinstance(entry, Mapping) else None
215
+ run.rejections.append(
216
+ Rejection(safe_id(claimed), exc.reason, f"response {number}: {exc.detail}")
217
+ )
218
+ continue
219
+ except (TypeError, ValueError):
220
+ detail = f"response {number}: not encodable as JSON"
221
+ run.rejections.append(Rejection("(invalid)", "schema", detail))
222
+ continue
223
+ packet = packets.get(packet_id)
224
+ if packet is None:
225
+ detail = f"response {number}: no packet of this run has this packet_id"
226
+ run.rejections.append(Rejection(safe_id(packet_id), "unknown_packet", detail))
227
+ continue
228
+ if packet_id in statuses:
229
+ detail = f"response {number}: a second response for this packet"
230
+ run.rejections.append(Rejection(packet_id, "duplicate", detail))
231
+ continue
232
+ verified, rejections = verifier.check(packet, findings)
233
+ run.verified += verified
234
+ run.rejections += rejections
235
+ statuses[packet_id] = PacketResult(packet_id, packet.path, "verified")
236
+ run.packets = [
237
+ statuses.get(p.packet_id) or PacketResult(p.packet_id, p.path, "skipped", "no response")
238
+ for p in packets.packets
239
+ ]
240
+ run.status = pass_status(run.packets, packets)
241
+ return run
242
+
243
+
244
+ def review_with_responses(
245
+ prepared: cli_review.Prepared,
246
+ result: EngineResult,
247
+ responses: bytes | str | Mapping[str, Any],
248
+ *,
249
+ started: float,
250
+ clock: Callable[[], float] = time.perf_counter,
251
+ ) -> dict[str, Any]:
252
+ """The JSON report of a prepared review whose AI pass is the harness's responses."""
253
+ settings = prepared.config.ai
254
+ run = check_responses(packets_for(prepared), responses)
255
+ found, _ = ai_policy.ai_findings(
256
+ run.verified,
257
+ blocking=settings.blocking,
258
+ fail_on=result.fail_on,
259
+ rule_findings=result.findings,
260
+ registry=prepared.registry,
261
+ )
262
+ issues = ai_policy.issues(run, blocking=settings.blocking, required=settings.required)
263
+ return report.build_report(
264
+ result,
265
+ prepared.changeset,
266
+ started=started,
267
+ clock=clock,
268
+ anchor_notes=prepared.plan.anchor_notes,
269
+ config_notes=prepared.config.config_notes,
270
+ extra_issues=issues,
271
+ ai=ai_policy.section(run),
272
+ ai_findings=found,
273
+ )
274
+
275
+
276
+ def verify_responses(
277
+ repo: str | os.PathLike[str],
278
+ responses: bytes | str | Mapping[str, Any],
279
+ *,
280
+ base: str | None = None,
281
+ head: str | None = None,
282
+ comparison: str | None = None,
283
+ staged: bool = False,
284
+ commit: str | None = None,
285
+ anchor: str | None = None,
286
+ clock: Callable[[], float] = time.perf_counter,
287
+ ) -> dict[str, Any]:
288
+ """``codeveto verify`` as a function: fresh intake, rules, packets, verification, report."""
289
+ started = clock()
290
+ args = _args(
291
+ repo,
292
+ base=base,
293
+ head=head,
294
+ comparison=comparison,
295
+ staged=staged,
296
+ commit=commit,
297
+ anchor=anchor,
298
+ )
299
+ prepared = cli_review.prepare(args)
300
+ result = engine.review(
301
+ prepared.changeset, registry=prepared.registry, policy=prepared.config.policy()
302
+ )
303
+ return review_with_responses(prepared, result, responses, started=started, clock=clock)