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/rules/base.py ADDED
@@ -0,0 +1,1026 @@
1
+ """Frozen public rule API (SPEC 5.3).
2
+
3
+ Rules are pure functions decorated with :func:`rule` that yield :class:`Hit`
4
+ values. ``line`` and ``file`` scope rules take a :class:`FileContext` and leave
5
+ ``Hit.path`` ``None``; the engine fills it in. ``change`` scope rules take a
6
+ :class:`ChangeContext` and set ``Hit.path`` to the changed file each hit is
7
+ about.
8
+
9
+ Line numbers are 1-based and follow Git (:func:`codeveto.model.git_lines`).
10
+ Columns are 1-based too. A ``Hit.redact`` span is ``(line, start_col,
11
+ end_col)`` on ``Hit.side``: ``end_col`` is exclusive and ``None`` means to the
12
+ end of the line, so a multi-line secret redacts each of its lines.
13
+
14
+ A rule that cannot fully check a file raises :class:`PartialCoverage`; the
15
+ engine keeps the hits yielded before it and marks the file ``partial``.
16
+ Line regexes see at most :data:`MAX_LINE_CHARS` characters at a time:
17
+ :meth:`FileContext.changed_lines` hands a longer line over as overlapping
18
+ windows (:class:`LineText` carries each window's offset in the real line).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import ast
24
+ import re
25
+ import tomllib
26
+ import warnings
27
+ from collections.abc import Callable, Iterable, Iterator, Mapping
28
+ from dataclasses import dataclass
29
+ from enum import StrEnum
30
+ from functools import cached_property
31
+ from types import MappingProxyType
32
+ from typing import Literal, TypeVar
33
+
34
+ from codeveto import embedded as _embedded
35
+ from codeveto import jsonsafe as _jsonsafe
36
+ from codeveto import languages as _languages
37
+ from codeveto import lexers as _lexers
38
+ from codeveto import statements as _statements
39
+ from codeveto import yamlish as _yamlish
40
+ from codeveto.embedded import Embedded
41
+ from codeveto.lexers import CommentSpan, LexResult, LineIndex, StringSpan
42
+ from codeveto.model import (
43
+ Changeset,
44
+ FileChange,
45
+ FileKind,
46
+ Side,
47
+ deletion_points,
48
+ git_lines,
49
+ )
50
+ from codeveto.statements import Statement
51
+ from codeveto.yamlish import YamlError, YamlResult
52
+
53
+ __all__ = [
54
+ "LINE_WINDOW_OVERLAP",
55
+ "MAX_LINE_CHARS",
56
+ "NON_WAIVABLE_RULES",
57
+ "REGISTRY",
58
+ "Change",
59
+ "ChangeContext",
60
+ "ChangeRule",
61
+ "Example",
62
+ "ExpectEntry",
63
+ "FileContext",
64
+ "FileRule",
65
+ "Hit",
66
+ "LineText",
67
+ "PartialCoverage",
68
+ "RedactSpan",
69
+ "Registry",
70
+ "Rule",
71
+ "RuleMeta",
72
+ "Scope",
73
+ "Severity",
74
+ "bad",
75
+ "good",
76
+ "line_windows",
77
+ "rule",
78
+ ]
79
+
80
+ RULE_ID = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*/[a-z0-9]+(?:-[a-z0-9]+)*")
81
+
82
+ MAX_LINE_CHARS = 4000
83
+ """Longest text handed to line regexes at once (SPEC 5.3); longer lines come as windows."""
84
+
85
+ LINE_WINDOW_OVERLAP = 256
86
+ """Characters two consecutive windows of a long line share (SPEC 5.3)."""
87
+
88
+
89
+ class LineText(str):
90
+ """One changed line, or one window of a line over :data:`MAX_LINE_CHARS`.
91
+
92
+ It is the text itself (a ``str``) plus where it sits in the real line:
93
+ ``offset`` is the 0-based index of its first character there and
94
+ ``line_length`` the real line's length. Report columns with
95
+ :meth:`column`; check :attr:`at_line_start` / :attr:`at_line_end` before
96
+ treating the window's ends as the line's (``^``, ``$``, ``startswith``).
97
+ """
98
+
99
+ offset: int
100
+ line_length: int
101
+
102
+ def __new__(cls, text: str, offset: int = 0, line_length: int | None = None) -> LineText:
103
+ value = super().__new__(cls, text)
104
+ value.offset = offset
105
+ value.line_length = len(text) + offset if line_length is None else line_length
106
+ return value
107
+
108
+ def column(self, index: int) -> int:
109
+ """1-based column in the real line of ``self[index]``."""
110
+ return self.offset + index + 1
111
+
112
+ @property
113
+ def at_line_start(self) -> bool:
114
+ return self.offset == 0
115
+
116
+ @property
117
+ def at_line_end(self) -> bool:
118
+ return self.offset + len(self) == self.line_length
119
+
120
+
121
+ def line_windows(text: str) -> Iterator[LineText]:
122
+ """``text`` whole, or as overlapping :data:`MAX_LINE_CHARS` windows when longer."""
123
+ size = len(text)
124
+ if size <= MAX_LINE_CHARS:
125
+ yield LineText(text, 0, size)
126
+ return
127
+ step = MAX_LINE_CHARS - LINE_WINDOW_OVERLAP
128
+ start = 0
129
+ while True:
130
+ yield LineText(text[start : start + MAX_LINE_CHARS], start, size)
131
+ if start + MAX_LINE_CHARS >= size:
132
+ return
133
+ start += step
134
+
135
+
136
+ NON_WAIVABLE_RULES: frozenset[str] = frozenset(
137
+ {
138
+ "agent/reviewer-config-weakened",
139
+ "agent/reviewer-directive",
140
+ "agent/hidden-unicode",
141
+ "agent/suppression-added",
142
+ "agent/codeveto-workflow-changed",
143
+ "secrets/private-key",
144
+ }
145
+ )
146
+ """Rules repository config cannot disable or downgrade (SPEC 6.3).
147
+
148
+ The ``@rule`` decorator marks these IDs ``non_waivable`` whatever the
149
+ decorator call says.
150
+ """
151
+
152
+
153
+ class PartialCoverage(Exception):
154
+ """Raised by a rule that could not fully check its file.
155
+
156
+ ``reason`` must be a fixed text written by the rule author (never text
157
+ taken from the reviewed file); the engine shows it as the coverage reason
158
+ and keeps the hits the rule yielded before raising.
159
+ """
160
+
161
+ def __init__(self, reason: str) -> None:
162
+ if not isinstance(reason, str) or not reason.strip():
163
+ raise ValueError("PartialCoverage needs a non-empty reason")
164
+ super().__init__(reason)
165
+ self.reason = reason
166
+
167
+
168
+ # --- Severity and scope ----------------------------------------------------
169
+
170
+
171
+ class Severity(StrEnum):
172
+ """Finding severity; orders by rank (``note < warning < error``).
173
+
174
+ ``<``, ``<=``, ``>`` and ``>=`` accept only other ``Severity`` values and
175
+ raise ``TypeError`` for anything else, plain strings included, so a lexical
176
+ string comparison can never pass for a rank comparison. Equality is the
177
+ string's: ``Severity.ERROR == "error"``.
178
+ """
179
+
180
+ ERROR = "error"
181
+ WARNING = "warning"
182
+ NOTE = "note"
183
+
184
+ @property
185
+ def rank(self) -> int:
186
+ return _SEVERITY_RANK[self.value]
187
+
188
+ def _rank_of(self, other: object, op: str) -> int:
189
+ # Raise rather than return NotImplemented: Severity is a str, so the
190
+ # fallback would be str's lexical comparison ("error" < "note").
191
+ if not isinstance(other, Severity):
192
+ raise TypeError(
193
+ f"'{op}' is only defined between Severity values, not with {type(other).__name__}"
194
+ )
195
+ return other.rank
196
+
197
+ def __lt__(self, other: object) -> bool:
198
+ return self.rank < self._rank_of(other, "<")
199
+
200
+ def __le__(self, other: object) -> bool:
201
+ return self.rank <= self._rank_of(other, "<=")
202
+
203
+ def __gt__(self, other: object) -> bool:
204
+ return self.rank > self._rank_of(other, ">")
205
+
206
+ def __ge__(self, other: object) -> bool:
207
+ return self.rank >= self._rank_of(other, ">=")
208
+
209
+
210
+ _SEVERITY_RANK: dict[str, int] = {"note": 0, "warning": 1, "error": 2}
211
+
212
+
213
+ class Scope(StrEnum):
214
+ """What a rule looks at: one file's lines, one file as a whole, or the change."""
215
+
216
+ LINE = "line"
217
+ FILE = "file"
218
+ CHANGE = "change"
219
+
220
+
221
+ # --- Hit ---------------------------------------------------------------------
222
+
223
+
224
+ RedactSpan = tuple[int, int, int | None]
225
+ """``(line, start_col, end_col)``: 1-based, ``end_col`` exclusive or ``None``."""
226
+
227
+
228
+ def _is_int(value: object) -> bool:
229
+ return isinstance(value, int) and not isinstance(value, bool)
230
+
231
+
232
+ def _optional_positive(name: str, value: object) -> None:
233
+ if value is None:
234
+ return
235
+ if not _is_int(value):
236
+ raise TypeError(f"Hit.{name} must be None or an int, got {value!r}")
237
+ if value < 1: # type: ignore[operator]
238
+ raise ValueError(f"Hit.{name} must be None or >= 1, got {value!r}")
239
+
240
+
241
+ def _optional_text(name: str, value: object) -> None:
242
+ if value is not None and not isinstance(value, str):
243
+ raise TypeError(f"Hit.{name} must be None or a str, got {type(value).__name__}")
244
+
245
+
246
+ def _redact_spans(value: object) -> tuple[RedactSpan, ...]:
247
+ # Lists are accepted and frozen into tuples so a Hit stays hashable;
248
+ # any other container is a mistake worth surfacing at the rule.
249
+ if not isinstance(value, (tuple, list)):
250
+ raise TypeError(f"Hit.redact must be a tuple of spans, got {type(value).__name__}")
251
+ spans: list[RedactSpan] = []
252
+ for span in value:
253
+ if not isinstance(span, (tuple, list)):
254
+ raise TypeError(f"Hit.redact span must be a tuple, got {span!r}")
255
+ if len(span) != 3:
256
+ raise ValueError(f"Hit.redact span must be (line, start_col, end_col), got {span!r}")
257
+ line, start, end = span
258
+ if not _is_int(line) or not _is_int(start) or not (end is None or _is_int(end)):
259
+ raise TypeError(f"Hit.redact span needs ints (end_col may be None), got {span!r}")
260
+ if line < 1 or start < 1 or (end is not None and end <= start):
261
+ raise ValueError(
262
+ f"Hit.redact span needs line >= 1, start_col >= 1, end_col > start_col, "
263
+ f"got {span!r}"
264
+ )
265
+ spans.append((line, start, end))
266
+ return tuple(spans)
267
+
268
+
269
+ @dataclass(frozen=True, slots=True)
270
+ class Hit:
271
+ """One finding location reported by a rule.
272
+
273
+ ``line..end_line`` is the span; the engine anchors it to the first changed
274
+ line inside. ``line=None`` is a file-level hit (``file`` scope only).
275
+ ``path`` is set only by ``change`` scope rules and must name a file in the
276
+ changeset. ``severity`` (a :class:`Severity` or its string value) lowers
277
+ this hit below the rule's metadata severity, which is its maximum; the
278
+ engine treats a hit above that maximum as a rule error. A wrong type
279
+ raises ``TypeError``, a wrong value ``ValueError``.
280
+ """
281
+
282
+ line: int | None
283
+ end_line: int | None = None
284
+ column: int | None = None
285
+ side: Side = Side.NEW
286
+ message: str | None = None
287
+ evidence: str | None = None
288
+ redact: tuple[RedactSpan, ...] = ()
289
+ path: str | None = None
290
+ severity: Severity | None = None
291
+
292
+ def __post_init__(self) -> None:
293
+ object.__setattr__(self, "side", Side(self.side))
294
+ if self.severity is not None:
295
+ if not isinstance(self.severity, str):
296
+ raise TypeError("Hit.severity must be None, a Severity or its string value")
297
+ object.__setattr__(self, "severity", Severity(self.severity))
298
+ _optional_positive("line", self.line)
299
+ _optional_positive("end_line", self.end_line)
300
+ _optional_positive("column", self.column)
301
+ if self.line is None and (self.end_line is not None or self.column is not None):
302
+ raise ValueError("a file-level Hit (line=None) has no end_line or column")
303
+ if self.end_line is not None and self.line is not None and self.end_line < self.line:
304
+ raise ValueError("Hit.end_line must be >= Hit.line")
305
+ _optional_text("message", self.message)
306
+ _optional_text("evidence", self.evidence)
307
+ _optional_text("path", self.path)
308
+ if self.path == "":
309
+ raise ValueError("Hit.path must be None or a non-empty path")
310
+ object.__setattr__(self, "redact", _redact_spans(self.redact))
311
+
312
+
313
+ # --- Contexts ----------------------------------------------------------------
314
+
315
+ _T = TypeVar("_T")
316
+
317
+ ParseError = ValueError | SyntaxError | RecursionError | MemoryError
318
+ """What a failed ``json``/``toml``/``python_ast`` parse keeps as its error.
319
+
320
+ ``MemoryError`` is CPython's "parser stack overflowed" for hostile nesting.
321
+ """
322
+
323
+
324
+ def _parse(text: str | None, parser: Callable[[str], _T]) -> tuple[_T | None, ParseError | None]:
325
+ # Never raises for bad input, so the cached_property callers cache failures too.
326
+ if text is None:
327
+ return None, None
328
+ # One leading byte order mark is not content (SPEC 5.5); line numbers stay.
329
+ text = text.removeprefix("\ufeff")
330
+ try:
331
+ return parser(text), None
332
+ except (SyntaxError, ValueError, RecursionError, MemoryError) as exc:
333
+ return None, exc
334
+
335
+
336
+ def _python_parser(filename: str) -> Callable[[str], ast.Module]:
337
+ def parse(text: str) -> ast.Module:
338
+ # As in legacy: compile-time warnings about the reviewed code (invalid
339
+ # escapes and the like) must neither become errors under -W error nor
340
+ # write untrusted source text to stderr.
341
+ with warnings.catch_warnings():
342
+ warnings.simplefilter("ignore", SyntaxWarning)
343
+ warnings.simplefilter("ignore", DeprecationWarning)
344
+ return ast.parse(text, filename=filename)
345
+
346
+ return parse
347
+
348
+
349
+ class FileContext:
350
+ """Read-only view of one changed file handed to ``line`` and ``file`` rules."""
351
+
352
+ def __init__(
353
+ self, change: FileChange, language: str, file_class: str, changeset: Changeset
354
+ ) -> None:
355
+ self._change = change
356
+ self._language = language
357
+ self._file_class = file_class
358
+ self._changeset = changeset
359
+
360
+ # Plain attributes of the change.
361
+
362
+ @property
363
+ def change(self) -> FileChange:
364
+ return self._change
365
+
366
+ @property
367
+ def path(self) -> str:
368
+ return self._change.path
369
+
370
+ @property
371
+ def old_path(self) -> str | None:
372
+ return self._change.old_path
373
+
374
+ @property
375
+ def language(self) -> str:
376
+ return self._language
377
+
378
+ @property
379
+ def file_class(self) -> str:
380
+ return self._file_class
381
+
382
+ @property
383
+ def kind(self) -> FileKind:
384
+ return self._change.kind
385
+
386
+ @property
387
+ def flags(self) -> frozenset[str]:
388
+ return self._change.flags
389
+
390
+ @property
391
+ def old_mode(self) -> str | None:
392
+ return self._change.old_mode
393
+
394
+ @property
395
+ def new_mode(self) -> str | None:
396
+ return self._change.new_mode
397
+
398
+ @property
399
+ def size(self) -> int | None:
400
+ """New-side size in bytes (``None`` for a deletion)."""
401
+ return self._change.new_size
402
+
403
+ @property
404
+ def new_text(self) -> str | None:
405
+ return self._change.new_text
406
+
407
+ @property
408
+ def old_text(self) -> str | None:
409
+ return self._change.old_text
410
+
411
+ @property
412
+ def added_lines(self) -> frozenset[int]:
413
+ return self._change.added_lines
414
+
415
+ @property
416
+ def removed_lines(self) -> frozenset[int]:
417
+ return self._change.removed_lines
418
+
419
+ @property
420
+ def changeset(self) -> Changeset:
421
+ return self._changeset
422
+
423
+ # Derived, cached helpers.
424
+
425
+ @cached_property
426
+ def lines(self) -> tuple[str, ...]:
427
+ """New-side lines in Git numbering (``lines[n - 1]`` is line ``n``)."""
428
+ return git_lines(self._change.new_text)
429
+
430
+ @cached_property
431
+ def old_lines(self) -> tuple[str, ...]:
432
+ """Old-side lines in Git numbering."""
433
+ return git_lines(self._change.old_text)
434
+
435
+ @cached_property
436
+ def deletion_points(self) -> frozenset[int]:
437
+ return deletion_points(self._change.hunks)
438
+
439
+ @cached_property
440
+ def _json(self) -> tuple[object, ParseError | None]:
441
+ return _parse(self._change.new_text, _jsonsafe.loads)
442
+
443
+ @cached_property
444
+ def _old_json(self) -> tuple[object, ParseError | None]:
445
+ return _parse(self._change.old_text, _jsonsafe.loads)
446
+
447
+ @property
448
+ def json(self) -> object:
449
+ """Parsed new-side JSON, ``None`` on failure (JSON ``null`` is also ``None``)."""
450
+ return self._json[0]
451
+
452
+ @property
453
+ def json_error(self) -> ParseError | None:
454
+ return self._json[1]
455
+
456
+ @property
457
+ def old_json(self) -> object:
458
+ return self._old_json[0]
459
+
460
+ @property
461
+ def old_json_error(self) -> ParseError | None:
462
+ return self._old_json[1]
463
+
464
+ @cached_property
465
+ def _toml(self) -> tuple[dict[str, object] | None, ParseError | None]:
466
+ return _parse(self._change.new_text, tomllib.loads)
467
+
468
+ @cached_property
469
+ def _old_toml(self) -> tuple[dict[str, object] | None, ParseError | None]:
470
+ return _parse(self._change.old_text, tomllib.loads)
471
+
472
+ @property
473
+ def toml(self) -> dict[str, object] | None:
474
+ """Parsed new-side TOML, ``None`` on failure (see ``toml_error``)."""
475
+ return self._toml[0]
476
+
477
+ @property
478
+ def toml_error(self) -> ParseError | None:
479
+ return self._toml[1]
480
+
481
+ @property
482
+ def old_toml(self) -> dict[str, object] | None:
483
+ return self._old_toml[0]
484
+
485
+ @property
486
+ def old_toml_error(self) -> ParseError | None:
487
+ return self._old_toml[1]
488
+
489
+ @cached_property
490
+ def _python_ast(self) -> tuple[ast.Module | None, ParseError | None]:
491
+ return _parse(self._change.new_text, _python_parser(self.path))
492
+
493
+ @cached_property
494
+ def _old_python_ast(self) -> tuple[ast.Module | None, ParseError | None]:
495
+ old_name = self._change.old_path or self._change.path
496
+ return _parse(self._change.old_text, _python_parser(old_name))
497
+
498
+ @property
499
+ def python_ast(self) -> ast.Module | None:
500
+ """``ast.parse`` of the new side, ``None`` on failure (see ``python_ast_error``)."""
501
+ return self._python_ast[0]
502
+
503
+ @property
504
+ def python_ast_error(self) -> ParseError | None:
505
+ return self._python_ast[1]
506
+
507
+ @property
508
+ def old_python_ast(self) -> ast.Module | None:
509
+ return self._old_python_ast[0]
510
+
511
+ @property
512
+ def old_python_ast_error(self) -> ParseError | None:
513
+ return self._old_python_ast[1]
514
+
515
+ # Lexer-backed helpers (SPEC 5.5). All are new-side and cached.
516
+
517
+ @cached_property
518
+ def spans(self) -> LexResult:
519
+ """Lexer output for ``new_text`` (empty for a deletion)."""
520
+ text = self._change.new_text
521
+ if text is None:
522
+ return LexResult()
523
+ return _lexers.lex(text, self._language, path=self.path)
524
+
525
+ @cached_property
526
+ def masked_code(self) -> str:
527
+ """``new_text`` with string and comment interiors blanked.
528
+
529
+ Delimiters and line breaks stay, interpolation code stays visible, and
530
+ for Vue/Svelte everything outside ``<script>`` blocks is blanked. Same
531
+ length as ``new_text``, so offsets and line numbers carry over.
532
+ """
533
+ text = self._change.new_text
534
+ return "" if not text else _lexers.mask(text, self.spans)
535
+
536
+ @cached_property
537
+ def _flat_spans(self) -> tuple[tuple[StringSpan, ...], tuple[CommentSpan, ...]]:
538
+ return _lexers.flatten(self.spans)
539
+
540
+ def comments(self) -> tuple[CommentSpan, ...]:
541
+ """Every comment span, nested ones (inside interpolations) included, by offset."""
542
+ return self._flat_spans[1]
543
+
544
+ def strings(self) -> tuple[StringSpan, ...]:
545
+ """Every string span, nested ones included, by offset."""
546
+ return self._flat_spans[0]
547
+
548
+ @cached_property
549
+ def _statements(self) -> tuple[Statement, ...]:
550
+ python_ast = self.python_ast if self._language == "python" else None
551
+ return _statements.split(
552
+ self._change.new_text,
553
+ self._language,
554
+ self.spans,
555
+ self.masked_code,
556
+ python_ast=python_ast,
557
+ path=self.path,
558
+ )
559
+
560
+ def statements(self) -> tuple[Statement, ...]:
561
+ """Logical statements of the new side (see :mod:`codeveto.statements`)."""
562
+ return self._statements
563
+
564
+ @cached_property
565
+ def line_index(self) -> LineIndex:
566
+ """Offset to ``(line, column)`` map for ``new_text`` and span offsets."""
567
+ return LineIndex(self._change.new_text or "")
568
+
569
+ @cached_property
570
+ def _yaml(self) -> YamlResult | None:
571
+ text = self._change.new_text
572
+ return None if text is None else _yamlish.parse(text.removeprefix("\ufeff"))
573
+
574
+ @cached_property
575
+ def _old_yaml(self) -> YamlResult | None:
576
+ text = self._change.old_text
577
+ return None if text is None else _yamlish.parse(text.removeprefix("\ufeff"))
578
+
579
+ @property
580
+ def yaml(self) -> YamlResult | None:
581
+ """``yamlish`` reading of the new side (``None`` for a deletion).
582
+
583
+ Documents with a hard error or an unsupported construct are left out;
584
+ see ``yaml_error`` and ``YamlResult.unsupported``.
585
+ """
586
+ return self._yaml
587
+
588
+ @property
589
+ def yaml_error(self) -> YamlError | None:
590
+ """The first hard YAML syntax error of the new side, if any."""
591
+ result = self._yaml
592
+ return result.errors[0] if result is not None and result.errors else None
593
+
594
+ @property
595
+ def old_yaml(self) -> YamlResult | None:
596
+ return self._old_yaml
597
+
598
+ @property
599
+ def old_yaml_error(self) -> YamlError | None:
600
+ result = self._old_yaml
601
+ return result.errors[0] if result is not None and result.errors else None
602
+
603
+ @cached_property
604
+ def _embedded(self) -> tuple[Embedded, ...]:
605
+ text = self._change.new_text
606
+ if not text:
607
+ return ()
608
+ if self._language == "dockerfile":
609
+ return _embedded.dockerfile_scripts(text, self.spans)
610
+ if self._language == "yaml" and self._file_class == "workflow":
611
+ return _embedded.workflow_scripts(self._yaml)
612
+ return ()
613
+
614
+ def embedded_scripts(self) -> tuple[Embedded, ...]:
615
+ """Scripts inside this file that ``masked_code`` blanks (new side).
616
+
617
+ Workflow ``run:`` values and Dockerfile ``RUN`` commands and heredoc
618
+ bodies, each with its language and an exact line map (see
619
+ :mod:`codeveto.embedded`). Empty for every other file.
620
+ """
621
+ return self._embedded
622
+
623
+ @cached_property
624
+ def test_regions(self) -> tuple[tuple[int, int], ...]:
625
+ """1-based inclusive new-side line ranges of in-file test code (Rust, Go)."""
626
+ if self._language not in ("rust", "go"):
627
+ return ()
628
+ return _languages.test_regions(
629
+ self._language, self._change.new_text, masked=self.masked_code
630
+ )
631
+
632
+ def in_test_region(self, line: int) -> bool:
633
+ """Is new-side ``line`` inside an in-file test region?"""
634
+ return any(start <= line <= end for start, end in self.test_regions)
635
+
636
+ def changed_lines(self, side: Side | str = Side.NEW) -> Iterator[tuple[int, LineText]]:
637
+ """``(number, text)`` of each changed line on ``side``, in line order.
638
+
639
+ New side: ``added_lines``; old side: ``removed_lines``. A line longer
640
+ than :data:`MAX_LINE_CHARS` comes as several pairs with the same
641
+ number, one per overlapping window (:data:`LINE_WINDOW_OVERLAP`
642
+ characters shared); ``text.column(i)`` maps an index back to the real
643
+ column. The engine reports one finding per rule and line, so a match
644
+ inside an overlap counts once.
645
+ """
646
+ side = Side(side)
647
+ lines = self.lines if side is Side.NEW else self.old_lines
648
+ changed = self.added_lines if side is Side.NEW else self.removed_lines
649
+ for number in sorted(changed):
650
+ if number <= len(lines):
651
+ for window in line_windows(lines[number - 1]):
652
+ yield number, window
653
+
654
+ @cached_property
655
+ def long_lines(self) -> tuple[int, ...]:
656
+ """New-side changed lines longer than :data:`MAX_LINE_CHARS` (scanned as windows)."""
657
+ lines = self.lines
658
+ return tuple(
659
+ n
660
+ for n in sorted(self.added_lines)
661
+ if n <= len(lines) and len(lines[n - 1]) > MAX_LINE_CHARS
662
+ )
663
+
664
+ @cached_property
665
+ def text_issues(self) -> tuple[str, ...]:
666
+ """Why the text layer covered this file only partly (lexer, YAML reader).
667
+
668
+ Empty when coverage is complete; the engine turns a non-empty value
669
+ into ``partial`` coverage.
670
+ """
671
+ issues = [f"lexer: {issue}" for issue in self.spans.issues] if self.spans.partial else []
672
+ if self._language == "yaml" and self._yaml is not None:
673
+ issues.extend(f"yaml: {note}" for note in self._yaml.unsupported)
674
+ return tuple(issues)
675
+
676
+
677
+ class ChangeContext:
678
+ """Read-only view of the whole change handed to ``change`` scope rules."""
679
+
680
+ def __init__(self, changeset: Changeset, files: Iterable[FileContext]) -> None:
681
+ self._changeset = changeset
682
+ self._files = tuple(files)
683
+
684
+ @property
685
+ def changeset(self) -> Changeset:
686
+ return self._changeset
687
+
688
+ @property
689
+ def files(self) -> tuple[FileContext, ...]:
690
+ return self._files
691
+
692
+ def files_by_class(self, cls: str) -> tuple[FileContext, ...]:
693
+ """Contexts of the changed files whose file class is ``cls``, in change order."""
694
+ return tuple(f for f in self._files if f.file_class == cls)
695
+
696
+
697
+ # --- Rule metadata and registry ---------------------------------------------
698
+
699
+ FileRule = Callable[[FileContext], Iterable[Hit]]
700
+ ChangeRule = Callable[[ChangeContext], Iterable[Hit]]
701
+ _F = TypeVar("_F", bound=FileRule | ChangeRule)
702
+
703
+
704
+ @dataclass(frozen=True, slots=True)
705
+ class RuleMeta:
706
+ """Validated metadata of one rule."""
707
+
708
+ id: str
709
+ severity: Severity
710
+ title: str
711
+ languages: frozenset[str] | None
712
+ classes: frozenset[str] | None
713
+ scope: Scope
714
+ introduced_only: bool
715
+ rationale: str
716
+ hint: str
717
+ tags: frozenset[str]
718
+ default_enabled: bool
719
+ non_waivable: bool
720
+ kinds: frozenset[FileKind] = frozenset({FileKind.TEXT})
721
+ """File kinds a ``file`` rule handles; ``line`` rules only ever see text."""
722
+
723
+ @property
724
+ def pack(self) -> str:
725
+ return self.id.split("/", 1)[0]
726
+
727
+ @property
728
+ def name(self) -> str:
729
+ return self.id.split("/", 1)[1]
730
+
731
+
732
+ @dataclass(frozen=True, slots=True)
733
+ class Rule:
734
+ """A registered rule: its metadata and its check function."""
735
+
736
+ meta: RuleMeta
737
+ func: FileRule | ChangeRule
738
+
739
+ @property
740
+ def id(self) -> str:
741
+ return self.meta.id
742
+
743
+
744
+ def _text(name: str, value: object) -> str:
745
+ if not isinstance(value, str) or not value.strip():
746
+ raise ValueError(f"rule {name} must be a non-empty string")
747
+ return value
748
+
749
+
750
+ def _names(name: str, value: Iterable[str] | None, *, allow_none: bool) -> frozenset[str] | None:
751
+ if value is None:
752
+ if allow_none:
753
+ return None
754
+ raise ValueError(f"rule {name} must not be None")
755
+ if isinstance(value, str):
756
+ raise TypeError(f"rule {name} must be a collection of strings, not a string")
757
+ result = frozenset(value)
758
+ if any(not isinstance(v, str) or not v for v in result):
759
+ raise ValueError(f"rule {name} must hold non-empty strings")
760
+ if allow_none and not result:
761
+ raise ValueError(f"rule {name} must be None (all) or non-empty")
762
+ return result
763
+
764
+
765
+ def _flag(name: str, value: object) -> bool:
766
+ if not isinstance(value, bool):
767
+ raise TypeError(f"rule {name} must be a bool")
768
+ return value
769
+
770
+
771
+ def _kinds(value: Iterable[FileKind | str], scope: Scope) -> frozenset[FileKind]:
772
+ if isinstance(value, str):
773
+ raise TypeError("rule kinds must be a collection of file kinds, not a string")
774
+ kinds = frozenset(FileKind(k) for k in value)
775
+ if not kinds:
776
+ raise ValueError("rule kinds must not be empty")
777
+ if scope is not Scope.FILE and kinds != {FileKind.TEXT}:
778
+ raise ValueError("only file scope rules may handle non-text kinds")
779
+ return kinds
780
+
781
+
782
+ class Registry:
783
+ """Rules by ID. Registering an ID twice raises ``ValueError``."""
784
+
785
+ def __init__(self) -> None:
786
+ self._rules: dict[str, Rule] = {}
787
+
788
+ def register(self, entry: Rule) -> Rule:
789
+ if entry.id in self._rules:
790
+ raise ValueError(f"duplicate rule id {entry.id!r}")
791
+ self._rules[entry.id] = entry
792
+ return entry
793
+
794
+ def get(self, rule_id: str) -> Rule | None:
795
+ return self._rules.get(rule_id)
796
+
797
+ def ids(self) -> frozenset[str]:
798
+ """Every registered ID."""
799
+ return frozenset(self._rules)
800
+
801
+ def discard(self, rule_ids: Iterable[str]) -> None:
802
+ """Remove these IDs (pack discovery rolls a failed pack back with it)."""
803
+ for rule_id in rule_ids:
804
+ self._rules.pop(rule_id, None)
805
+
806
+ def all(self) -> tuple[Rule, ...]:
807
+ """Every rule, sorted by ID."""
808
+ return tuple(self._rules[k] for k in sorted(self._rules))
809
+
810
+ def by_pack(self, pack: str) -> tuple[Rule, ...]:
811
+ """Rules of one pack, sorted by ID."""
812
+ return tuple(r for r in self.all() if r.meta.pack == pack)
813
+
814
+ def __contains__(self, rule_id: object) -> bool:
815
+ return rule_id in self._rules
816
+
817
+ def __len__(self) -> int:
818
+ return len(self._rules)
819
+
820
+ def rule(
821
+ self,
822
+ *,
823
+ id: str,
824
+ severity: Severity | Literal["error", "warning", "note"],
825
+ title: str,
826
+ languages: Iterable[str] | None = None,
827
+ classes: Iterable[str] | None = None,
828
+ scope: Scope | Literal["line", "file", "change"] = "line",
829
+ introduced_only: bool = True,
830
+ rationale: str,
831
+ hint: str,
832
+ tags: Iterable[str] = (),
833
+ default_enabled: bool = True,
834
+ non_waivable: bool = False,
835
+ kinds: Iterable[FileKind | str] = (FileKind.TEXT,),
836
+ ) -> Callable[[_F], _F]:
837
+ """Decorator that validates metadata and registers the function.
838
+
839
+ ``kinds`` lists the file kinds a ``file`` rule handles (default text
840
+ only); a binary, symlink, submodule or LFS-pointer file counts as
841
+ checked only when an enabled rule handles its kind. IDs in
842
+ :data:`NON_WAIVABLE_RULES` are always ``non_waivable``.
843
+ """
844
+ if not isinstance(id, str) or not RULE_ID.fullmatch(id):
845
+ raise ValueError(f"rule id {id!r} must look like '<pack>/<kebab-name>'")
846
+ rule_scope = Scope(scope)
847
+ meta = RuleMeta(
848
+ id=id,
849
+ severity=Severity(severity),
850
+ title=_text("title", title),
851
+ languages=_names("languages", languages, allow_none=True),
852
+ classes=_names("classes", classes, allow_none=True),
853
+ scope=rule_scope,
854
+ introduced_only=_flag("introduced_only", introduced_only),
855
+ rationale=_text("rationale", rationale),
856
+ hint=_text("hint", hint),
857
+ tags=_names("tags", tags, allow_none=False) or frozenset(),
858
+ default_enabled=_flag("default_enabled", default_enabled),
859
+ non_waivable=_flag("non_waivable", non_waivable) or id in NON_WAIVABLE_RULES,
860
+ kinds=_kinds(kinds, rule_scope),
861
+ )
862
+
863
+ def decorate(func: _F) -> _F:
864
+ if not callable(func):
865
+ raise TypeError(f"rule {id!r} must decorate a function")
866
+ self.register(Rule(meta=meta, func=func))
867
+ return func
868
+
869
+ return decorate
870
+
871
+
872
+ REGISTRY = Registry()
873
+ """The process-wide registry that rule packs register into."""
874
+
875
+ rule = REGISTRY.rule
876
+
877
+
878
+ # --- Examples ------------------------------------------------------------------
879
+
880
+ ExpectEntry = tuple[str, int | None, Side]
881
+
882
+
883
+ @dataclass(frozen=True, slots=True)
884
+ class Change:
885
+ """One file of a rule example (``None`` text means the side is absent)."""
886
+
887
+ old: str | None = None
888
+ new: str | None = None
889
+ old_path: str | None = None
890
+ mode: str | None = None
891
+ binary: bool = False
892
+ size: int | None = None
893
+
894
+ def __post_init__(self) -> None:
895
+ if self.old is None and self.new is None and not self.binary:
896
+ raise ValueError("an example Change needs old or new text")
897
+ if self.size is not None and (isinstance(self.size, bool) or self.size < 0):
898
+ raise ValueError("Change.size must be None or >= 0")
899
+
900
+
901
+ @dataclass(frozen=True, slots=True)
902
+ class Example:
903
+ """A rule example: ``bad`` ones list every expected hit, ``good`` ones none."""
904
+
905
+ kind: Literal["bad", "good"]
906
+ files: Mapping[str, Change]
907
+ expect: tuple[ExpectEntry, ...] = ()
908
+ note: str = ""
909
+ min_python: tuple[int, int] | None = None
910
+ """A bad example whose hits need this Python or newer (older ones expect none)."""
911
+
912
+ def __post_init__(self) -> None:
913
+ if self.kind not in ("bad", "good"):
914
+ raise ValueError(f"Example.kind must be 'bad' or 'good', got {self.kind!r}")
915
+ files = dict(self.files)
916
+ if not files:
917
+ raise ValueError("an Example needs at least one file")
918
+ for path, change in files.items():
919
+ if not isinstance(path, str) or not path:
920
+ raise ValueError("Example file paths must be non-empty strings")
921
+ if not isinstance(change, Change):
922
+ raise TypeError(f"Example file {path!r} must map to a Change")
923
+ object.__setattr__(self, "files", MappingProxyType(files))
924
+ expect: list[ExpectEntry] = []
925
+ for path, line, side in self.expect:
926
+ if path not in files:
927
+ raise ValueError(f"expected hit on {path!r}, which is not an example file")
928
+ side = Side(side)
929
+ if line is not None:
930
+ if isinstance(line, bool) or not isinstance(line, int) or line < 1:
931
+ raise ValueError(f"expected line must be None or >= 1, got {line!r}")
932
+ change = files[path]
933
+ text = change.new if side is Side.NEW else change.old
934
+ if text is None:
935
+ raise ValueError(
936
+ f"expected {side} line {line} of {path!r}, which has no {side} text"
937
+ )
938
+ count = len(git_lines(text))
939
+ if line > count:
940
+ raise ValueError(
941
+ f"expected {side} line {line} of {path!r}, which has {count} line(s)"
942
+ )
943
+ expect.append((path, line, side))
944
+ object.__setattr__(self, "expect", tuple(expect))
945
+ if self.kind == "bad" and not self.expect:
946
+ raise ValueError("a bad Example needs at least one expected hit")
947
+ if self.kind == "good" and self.expect:
948
+ raise ValueError("a good Example cannot expect hits")
949
+ if self.min_python is not None and (
950
+ not isinstance(self.min_python, tuple)
951
+ or len(self.min_python) != 2
952
+ or not all(_is_int(v) for v in self.min_python)
953
+ ):
954
+ raise ValueError("Example.min_python must be a (major, minor) tuple")
955
+
956
+
957
+ # An expectation marker closes a line. "# expect", "// expect" and "-- expect"
958
+ # stand alone on the line or follow two spaces or a tab, as in the SPEC
959
+ # examples, so that floor division ("a // expect") is not a marker; "--" also
960
+ # needs whitespace after it, so a shell flag ("--expect") never is.
961
+ # "<!-- expect -->" is unambiguous and may follow any whitespace.
962
+ _MARKER = re.compile(
963
+ r"(?:(?:^[ \t]*|[ \t]*(?:\t| ))(?:#[ \t]*|//[ \t]*|--[ \t]+)expect"
964
+ r"|(?:^|[ \t]+)<!--[ \t]*expect[ \t]*-->)[ \t]*\Z"
965
+ )
966
+
967
+
968
+ def _strip_markers(text: str | None) -> tuple[str | None, tuple[int, ...]]:
969
+ """Remove end-of-line expect markers; return the text and their line numbers."""
970
+ if text is None:
971
+ return None, ()
972
+ out: list[str] = []
973
+ marked: list[int] = []
974
+ for number, part in enumerate(text.split("\n"), start=1):
975
+ body, cr = (part[:-1], "\r") if part.endswith("\r") else (part, "")
976
+ match = _MARKER.search(body)
977
+ if match:
978
+ body = body[: match.start()]
979
+ if _MARKER.search(body):
980
+ raise ValueError(f"line {number} has more than one expect marker; use expect=")
981
+ marked.append(number)
982
+ out.append(body + cr)
983
+ return "\n".join(out), tuple(marked)
984
+
985
+
986
+ def bad(
987
+ path: str,
988
+ new: str | None,
989
+ *,
990
+ old: str | None = None,
991
+ expect: Iterable[tuple[str, int | None, Side | str]] | None = None,
992
+ note: str = "",
993
+ min_python: tuple[int, int] | None = None,
994
+ ) -> Example:
995
+ """A bad example for one file, with hits taken from inline expect markers.
996
+
997
+ Markers in ``new`` expect new-side hits, markers in ``old`` old-side hits.
998
+ Pass ``expect=`` instead of markers for file-level or unmarked hits; giving
999
+ both, or neither, raises ``ValueError``. ``min_python`` marks hits that
1000
+ only the given Python version or a newer one can produce.
1001
+ """
1002
+ new_text, new_marks = _strip_markers(new)
1003
+ old_text, old_marks = _strip_markers(old)
1004
+ found: tuple[ExpectEntry, ...] = tuple((path, n, Side.NEW) for n in new_marks) + tuple(
1005
+ (path, n, Side.OLD) for n in old_marks
1006
+ )
1007
+ if expect is not None:
1008
+ if found:
1009
+ raise ValueError(f"bad example {path!r}: use expect markers or expect=, not both")
1010
+ found = tuple((p, line, Side(side)) for p, line, side in expect)
1011
+ elif not found:
1012
+ raise ValueError(f"bad example {path!r} has no expect marker and no expect=")
1013
+ return Example(
1014
+ kind="bad",
1015
+ files={path: Change(old=old_text, new=new_text)},
1016
+ expect=found,
1017
+ note=note,
1018
+ min_python=min_python,
1019
+ )
1020
+
1021
+
1022
+ def good(path: str, new: str | None, *, old: str | None = None, note: str = "") -> Example:
1023
+ """A good example for one file; an expect marker in it raises ``ValueError``."""
1024
+ if _strip_markers(new)[1] or _strip_markers(old)[1]:
1025
+ raise ValueError(f"good example {path!r} contains an expect marker")
1026
+ return Example(kind="good", files={path: Change(old=old, new=new)}, note=note)