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/model.py ADDED
@@ -0,0 +1,372 @@
1
+ """Frozen data model for a reviewed change (SPEC 5, 5.1, 5.2).
2
+
3
+ Line numbers are 1-based and follow Git: text is split on LF, a CR is dropped
4
+ only where it precedes LF, and a final line without a newline still counts while
5
+ a trailing newline adds no phantom empty line. Hunks use Git's ``--unified=0``
6
+ header convention: a side with ``count == 0`` has ``start`` set to the line
7
+ *after which* the other side's block sits (``0`` at the top of the file).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import difflib
13
+ from collections.abc import Iterable
14
+ from dataclasses import dataclass, field
15
+ from enum import StrEnum
16
+ from typing import Literal, cast, get_args
17
+
18
+ __all__ = [
19
+ "AnchorSource",
20
+ "Changeset",
21
+ "FileChange",
22
+ "FileKind",
23
+ "FileStatus",
24
+ "Hunk",
25
+ "Mode",
26
+ "Side",
27
+ "deletion_points",
28
+ "git_lines",
29
+ ]
30
+
31
+ Mode = Literal["range", "commit", "staged", "worktree"]
32
+ AnchorSource = Literal["explicit", "upstream", "origin-head", "head", "base", "parent"]
33
+
34
+ _MODES: frozenset[str] = frozenset(get_args(Mode))
35
+ _ANCHOR_SOURCES: frozenset[str] = frozenset(get_args(AnchorSource))
36
+ _REGULAR_MODE = "100644"
37
+ _SYMLINK_MODE = "120000"
38
+ _GITLINK_MODE = "160000"
39
+
40
+
41
+ class Side(StrEnum):
42
+ """Which side of the comparison a line belongs to."""
43
+
44
+ NEW = "new"
45
+ OLD = "old"
46
+
47
+
48
+ class FileStatus(StrEnum):
49
+ """How a path changed between the two sides."""
50
+
51
+ ADDED = "added"
52
+ MODIFIED = "modified"
53
+ DELETED = "deleted"
54
+ RENAMED = "renamed"
55
+ TYPE_CHANGED = "type_changed"
56
+
57
+
58
+ class FileKind(StrEnum):
59
+ """What a path holds (the new side, or the old side for a deletion)."""
60
+
61
+ TEXT = "text"
62
+ BINARY = "binary"
63
+ SYMLINK = "symlink"
64
+ SUBMODULE = "submodule"
65
+ LFS_POINTER = "lfs_pointer"
66
+
67
+
68
+ def git_lines(text: str | None) -> tuple[str, ...]:
69
+ """Split ``text`` into lines numbered as Git numbers them.
70
+
71
+ Splits on LF only and strips a CR only when it precedes LF; a lone CR stays
72
+ part of its line. A trailing LF does not create an empty last line, and a
73
+ final line without LF is kept. ``None`` and ``""`` give no lines.
74
+ """
75
+ if not text:
76
+ return ()
77
+ parts = text.split("\n")
78
+ result = [row.removesuffix("\r") for row in parts[:-1]]
79
+ if parts[-1]:
80
+ result.append(parts[-1])
81
+ return tuple(result)
82
+
83
+
84
+ def _check_container(owner: str, name: str, value: object, kind: type, item: type) -> None:
85
+ # Strict on purpose: a set or list here would make the frozen object
86
+ # mutable or unhashable, and the mistake would surface far from its cause.
87
+ if type(value) is not kind:
88
+ raise TypeError(f"{owner}.{name} must be a {kind.__name__}, got {type(value).__name__}")
89
+ for element in cast("Iterable[object]", value):
90
+ if not isinstance(element, item) or (item is int and isinstance(element, bool)):
91
+ raise TypeError(f"{owner}.{name} must hold {item.__name__} values, got {element!r}")
92
+
93
+
94
+ def _check_line_numbers(name: str, values: frozenset[int]) -> None:
95
+ _check_container("FileChange", name, values, frozenset, int)
96
+ for value in values:
97
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
98
+ raise ValueError(f"{name} must hold line numbers >= 1, got {value!r}")
99
+
100
+
101
+ @dataclass(frozen=True, slots=True)
102
+ class Hunk:
103
+ """One changed block in Git ``--unified=0`` header form."""
104
+
105
+ old_start: int
106
+ old_count: int
107
+ new_start: int
108
+ new_count: int
109
+
110
+ def __post_init__(self) -> None:
111
+ for name in ("old_start", "old_count", "new_start", "new_count"):
112
+ value = getattr(self, name)
113
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
114
+ raise ValueError(f"Hunk.{name} must be an int >= 0, got {value!r}")
115
+ if self.old_count == 0 and self.new_count == 0:
116
+ raise ValueError("Hunk must change at least one line")
117
+ if self.old_count and self.old_start < 1:
118
+ raise ValueError("Hunk.old_start must be >= 1 when old_count > 0")
119
+ if self.new_count and self.new_start < 1:
120
+ raise ValueError("Hunk.new_start must be >= 1 when new_count > 0")
121
+
122
+ @property
123
+ def old_lines(self) -> range:
124
+ """Old-side line numbers removed or replaced by this hunk."""
125
+ return range(self.old_start, self.old_start + self.old_count)
126
+
127
+ @property
128
+ def new_lines(self) -> range:
129
+ """New-side line numbers added or replacing old lines in this hunk."""
130
+ return range(self.new_start, self.new_start + self.new_count)
131
+
132
+ @property
133
+ def is_pure_deletion(self) -> bool:
134
+ return self.new_count == 0
135
+
136
+ @property
137
+ def is_pure_insertion(self) -> bool:
138
+ return self.old_count == 0
139
+
140
+
141
+ def deletion_points(hunks: Iterable[Hunk]) -> frozenset[int]:
142
+ """New-side anchor line for each pure-deletion hunk.
143
+
144
+ Git sets ``new_start`` of a pure deletion to the new line just before the
145
+ removed block (``0`` when the block was at the top); that line is the
146
+ anchor, clamped to 1 so a deletion at the top or of the whole file still
147
+ has a reportable line.
148
+ """
149
+ return frozenset(max(h.new_start, 1) for h in hunks if h.is_pure_deletion)
150
+
151
+
152
+ def _diff_lines(text: str | None) -> tuple[str, ...]:
153
+ # Same numbering as git_lines, but each line keeps its CR and LF so that a
154
+ # CR-only or missing-final-newline difference is a change, as in ``git diff``.
155
+ if not text:
156
+ return ()
157
+ parts = text.split("\n")
158
+ result = [row + "\n" for row in parts[:-1]]
159
+ if parts[-1]:
160
+ result.append(parts[-1])
161
+ return tuple(result)
162
+
163
+
164
+ def _hunks_from_lines(old: tuple[str, ...], new: tuple[str, ...]) -> tuple[Hunk, ...]:
165
+ matcher = difflib.SequenceMatcher(None, old, new, autojunk=False)
166
+ hunks: list[Hunk] = []
167
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
168
+ if tag == "equal":
169
+ continue
170
+ old_count = i2 - i1
171
+ new_count = j2 - j1
172
+ hunks.append(
173
+ Hunk(
174
+ old_start=i1 + 1 if old_count else i1,
175
+ old_count=old_count,
176
+ new_start=j1 + 1 if new_count else j1,
177
+ new_count=new_count,
178
+ )
179
+ )
180
+ return tuple(hunks)
181
+
182
+
183
+ def _text_size(text: str | None) -> int | None:
184
+ if text is None:
185
+ return None
186
+ return len(text.encode("utf-8", "surrogateescape"))
187
+
188
+
189
+ @dataclass(frozen=True, slots=True)
190
+ class FileChange:
191
+ """One changed path.
192
+
193
+ ``old_path`` is set only for renames. ``old_mode``/``new_mode`` are Git
194
+ octal mode strings (``"100644"``, ``"100755"``, ``"120000"``, ``"160000"``),
195
+ ``None`` for an absent side. ``old_text``/``new_text`` are ``None`` when the
196
+ side is absent or its content is not reviewed as text. ``added_lines`` are
197
+ new-side and ``removed_lines`` old-side line numbers inside hunks.
198
+ """
199
+
200
+ path: str
201
+ old_path: str | None
202
+ status: FileStatus
203
+ kind: FileKind
204
+ old_mode: str | None
205
+ new_mode: str | None
206
+ old_text: str | None
207
+ new_text: str | None
208
+ old_size: int | None
209
+ new_size: int | None
210
+ added_lines: frozenset[int] = frozenset()
211
+ removed_lines: frozenset[int] = frozenset()
212
+ hunks: tuple[Hunk, ...] = ()
213
+ similarity: int | None = None
214
+ symlink_target: str | None = None
215
+ submodule_old: str | None = None
216
+ submodule_new: str | None = None
217
+ flags: frozenset[str] = frozenset()
218
+ issues: tuple[str, ...] = field(default=())
219
+
220
+ def __post_init__(self) -> None:
221
+ object.__setattr__(self, "status", FileStatus(self.status))
222
+ object.__setattr__(self, "kind", FileKind(self.kind))
223
+ if not isinstance(self.path, str) or not self.path:
224
+ raise ValueError("FileChange.path must be a non-empty string")
225
+ if self.status is FileStatus.RENAMED:
226
+ if not self.old_path or self.old_path == self.path:
227
+ raise ValueError("a renamed FileChange needs an old_path different from path")
228
+ elif self.old_path is not None:
229
+ raise ValueError("FileChange.old_path is only set for renames")
230
+ if self.status is FileStatus.ADDED and (
231
+ self.old_text is not None or self.old_mode is not None
232
+ ):
233
+ raise ValueError("an added FileChange has no old side")
234
+ if self.status is FileStatus.DELETED and (
235
+ self.new_text is not None or self.new_mode is not None
236
+ ):
237
+ raise ValueError("a deleted FileChange has no new side")
238
+ _check_line_numbers("added_lines", self.added_lines)
239
+ _check_line_numbers("removed_lines", self.removed_lines)
240
+ _check_container("FileChange", "hunks", self.hunks, tuple, Hunk)
241
+ _check_container("FileChange", "flags", self.flags, frozenset, str)
242
+ _check_container("FileChange", "issues", self.issues, tuple, str)
243
+ for name in ("old_size", "new_size"):
244
+ value = getattr(self, name)
245
+ if value is not None and (
246
+ isinstance(value, bool) or not isinstance(value, int) or value < 0
247
+ ):
248
+ raise ValueError(f"FileChange.{name} must be None or an int >= 0, got {value!r}")
249
+ similarity = self.similarity
250
+ if similarity is not None and (
251
+ isinstance(similarity, bool)
252
+ or not isinstance(similarity, int)
253
+ or not 0 <= similarity <= 100
254
+ ):
255
+ raise ValueError(f"FileChange.similarity must be None or 0..100, got {similarity!r}")
256
+
257
+ @classmethod
258
+ def from_texts(
259
+ cls,
260
+ path: str,
261
+ old: str | None,
262
+ new: str | None,
263
+ *,
264
+ old_path: str | None = None,
265
+ status: FileStatus | None = None,
266
+ kind: FileKind = FileKind.TEXT,
267
+ old_mode: str | None = None,
268
+ new_mode: str | None = None,
269
+ old_size: int | None = None,
270
+ new_size: int | None = None,
271
+ similarity: int | None = None,
272
+ symlink_target: str | None = None,
273
+ submodule_old: str | None = None,
274
+ submodule_new: str | None = None,
275
+ flags: Iterable[str] = (),
276
+ issues: Iterable[str] = (),
277
+ ) -> FileChange:
278
+ """Build a text change, computing hunks and changed lines with difflib.
279
+
280
+ For tests and rule examples; Git intake computes the same fields from
281
+ ``git diff``. Both number lines as :func:`git_lines` does and compare
282
+ lines with their line ending, so a CR-only change or a missing final
283
+ newline is a changed line, as Git reports it. They do not always agree
284
+ on hunk *shape*: where the alignment is ambiguous (for example an
285
+ insertion next to a repeated line), difflib and Git's Myers diff can
286
+ place the same edit one line apart, which moves ``added_lines``,
287
+ ``deletion_points`` and introduced-only pairing. Keep example edits
288
+ unambiguous when a rule depends on exact hunk placement.
289
+
290
+ Status is inferred when omitted: no old text is ``added``, no new text
291
+ is ``deleted``, an ``old_path`` is ``renamed``, otherwise ``modified``.
292
+ Modes default per present side by ``kind``: ``120000`` for a symlink,
293
+ ``160000`` for a submodule, otherwise ``100644``. Sizes default to the
294
+ UTF-8 byte length of each text.
295
+ """
296
+ if status is None:
297
+ if old is None and new is None:
298
+ raise ValueError("from_texts needs a status when both sides are None")
299
+ if old is None:
300
+ status = FileStatus.ADDED
301
+ elif new is None:
302
+ status = FileStatus.DELETED
303
+ elif old_path is not None:
304
+ status = FileStatus.RENAMED
305
+ else:
306
+ status = FileStatus.MODIFIED
307
+ status = FileStatus(status)
308
+ kind = FileKind(kind)
309
+ default_mode = {FileKind.SYMLINK: _SYMLINK_MODE, FileKind.SUBMODULE: _GITLINK_MODE}.get(
310
+ kind, _REGULAR_MODE
311
+ )
312
+ has_old = status is not FileStatus.ADDED
313
+ has_new = status is not FileStatus.DELETED
314
+ if old_mode is None and has_old:
315
+ old_mode = default_mode
316
+ if new_mode is None and has_new:
317
+ new_mode = default_mode
318
+ hunks = _hunks_from_lines(_diff_lines(old), _diff_lines(new))
319
+ added = frozenset(n for h in hunks for n in h.new_lines)
320
+ removed = frozenset(n for h in hunks for n in h.old_lines)
321
+ return cls(
322
+ path=path,
323
+ old_path=old_path,
324
+ status=status,
325
+ kind=kind,
326
+ old_mode=old_mode,
327
+ new_mode=new_mode,
328
+ old_text=old,
329
+ new_text=new,
330
+ old_size=_text_size(old) if old_size is None else old_size,
331
+ new_size=_text_size(new) if new_size is None else new_size,
332
+ added_lines=added,
333
+ removed_lines=removed,
334
+ hunks=hunks,
335
+ similarity=similarity,
336
+ symlink_target=symlink_target,
337
+ submodule_old=submodule_old,
338
+ submodule_new=submodule_new,
339
+ flags=frozenset(flags),
340
+ issues=tuple(issues),
341
+ )
342
+
343
+
344
+ @dataclass(frozen=True, slots=True)
345
+ class Changeset:
346
+ """Everything one review compares (SPEC 5.1, 7.1).
347
+
348
+ ``base``/``head``/``merge_base``/``anchor`` are full object IDs or ``None``
349
+ where the mode has no such revision (``head`` is ``None`` for the private
350
+ index and the working tree). ``snapshot`` is the tree OID of the reviewed
351
+ private index or working tree (staged and worktree modes), else ``None``.
352
+ """
353
+
354
+ mode: Mode
355
+ base: str | None
356
+ head: str | None
357
+ merge_base: str | None
358
+ anchor: str | None
359
+ anchor_source: AnchorSource
360
+ files: tuple[FileChange, ...] = ()
361
+ issues: tuple[str, ...] = ()
362
+ snapshot: str | None = None
363
+
364
+ def __post_init__(self) -> None:
365
+ if self.mode not in _MODES:
366
+ raise ValueError(f"unknown Changeset.mode {self.mode!r}")
367
+ if self.anchor_source not in _ANCHOR_SOURCES:
368
+ raise ValueError(f"unknown Changeset.anchor_source {self.anchor_source!r}")
369
+ _check_container("Changeset", "files", self.files, tuple, FileChange)
370
+ _check_container("Changeset", "issues", self.issues, tuple, str)
371
+ if self.snapshot is not None and not isinstance(self.snapshot, str):
372
+ raise TypeError("Changeset.snapshot must be a tree OID string or None")
@@ -0,0 +1,28 @@
1
+ """Publishing a review to a forge (SPEC 10.4, 10.5): ``codeveto publish github|forgejo``.
2
+
3
+ - :mod:`.http`: a small JSON-over-HTTPS client on ``urllib`` with timeouts,
4
+ bounded retries and backoff on server errors and rate limits, no redirects,
5
+ and errors that never contain the token.
6
+ - :mod:`.event`: the trusted workflow context (event payload, repository,
7
+ server and API URLs) read from the runner's environment.
8
+ - :mod:`.untrusted`: the report is untrusted data: strict JSON, size cap,
9
+ schema validation, revisions equal to the event's, verdict consistent with
10
+ the findings.
11
+ - :mod:`.diff`: changed lines of a pull request from GitHub file patches or a
12
+ unified diff, so findings outside the change are dropped.
13
+ - :mod:`.github`, :mod:`.forgejo`: the publishers.
14
+ - :mod:`.action`: the steps of the composite GitHub Action and the Forgejo
15
+ workflow that are not ``review`` or ``publish`` (revision preparation and
16
+ the final exit code).
17
+
18
+ Publishing never changes the review's exit code: every publishing problem
19
+ becomes a warning in the job summary (or on stderr without one).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ __all__ = ["PublishError"]
25
+
26
+
27
+ class PublishError(Exception):
28
+ """Publishing could not go ahead; the message is safe to show (no token, no raw data)."""