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/engine.py ADDED
@@ -0,0 +1,1570 @@
1
+ """Rule execution: selection, anchoring, filters, ignores, fingerprints, verdict (SPEC 5.2, 5.6).
2
+
3
+ :func:`review` runs every enabled rule over a :class:`~codeveto.model.Changeset`
4
+ and returns an :class:`EngineResult`. Configuration reaches the engine only
5
+ through a :class:`Policy` (implemented by ``config.py``; :class:`DefaultPolicy`
6
+ otherwise), and the engine applies what the policy returns as is.
7
+
8
+ Order of work:
9
+
10
+ 1. Every changed file gets a language and file class (``policy.file_class``
11
+ first, then :func:`codeveto.languages.classify`) and a ``FileContext``.
12
+ Files intake skipped (``skipped:<reason>``, ``invalid-path``) are
13
+ ``skipped``; binary, symlink, submodule and LFS-pointer files are
14
+ ``checked`` only when an enabled ``file`` rule handles their kind, else
15
+ ``skipped``. That is benign only for a deleted file, a pure rename, or an
16
+ image binary: one intake identified by magic bytes (``image:<format>``
17
+ flag) that is not executable and did not change mode. Lexer and YAML
18
+ ``text_issues`` make a text file ``partial``; long lines do not, since
19
+ ``changed_lines()`` hands them to rules as overlapping windows.
20
+ 2. ``line`` and ``file`` rules run per file, sorted by ID, selected by
21
+ language, class and kind. Classes suppress packs as SPEC 5.4 says: ``docs``
22
+ suppresses the language bug-pattern packs, ``generated``/``vendored``/
23
+ ``minified`` those and ``hygiene``; secrets, security, agent, ci and deps
24
+ always run; a rule that lists a class in ``classes`` always runs there.
25
+ Then ``change`` rules run once with a ``ChangeContext`` of every file.
26
+ 3. Hits are anchored (SPEC 5.2): a span ``line..end_line`` anchors to its
27
+ first changed line (new side: ``added_lines`` and deletion points; old
28
+ side: ``removed_lines``); a hit with no changed line in its span is
29
+ dropped. ``line=None`` is allowed for ``file`` and ``change`` rules on an
30
+ added, deleted, renamed, type- or mode-changed file or a non-text file. A
31
+ location outside the file, a ``path`` on a line/file hit, an unknown
32
+ ``path`` on a change hit or a bad redact span is a rule error.
33
+ 4. Introduced-only filter (``line`` rules with ``introduced_only``): when a
34
+ rule's call leaves new-side hits, it runs again on the paired old side (a
35
+ reversed ``FileContext`` of ``old_text``). Old hits count on removed lines
36
+ and on the old line next to each deletion point (the line a deletion-point
37
+ anchor stands for). Each hit's *key* is its normalized evidence, or its
38
+ normalized line text when it has none. A new hit is dropped when an
39
+ unused old hit of the same rule has the same key, first in the same hunk,
40
+ else anywhere in the file (a moved block); each old hit cancels at most
41
+ one new hit. :func:`normalize` strips the ends and collapses whitespace
42
+ runs to one space, so re-indenting does not re-report, while a changed
43
+ argument, string or quote does. An old hit cancels a new one only when
44
+ its effective severity (step 6) is at least the new hit's, so a
45
+ pre-existing warning that the change turns into an error is reported.
46
+ 5. Exceptions and budgets: a rule that raises (anything but
47
+ ``KeyboardInterrupt``: ``SystemExit`` and ``GeneratorExit`` too) keeps the
48
+ hits it yielded before, and its file becomes ``partial`` with an issue
49
+ naming the rule and file (only the exception's type name is shown, never
50
+ its text). :class:`~codeveto.rules.base.PartialCoverage` makes the file
51
+ ``partial`` with the rule's reason. Rule time is measured per call; on
52
+ POSIX in the main thread an interval timer (``SIGALRM``) also interrupts a
53
+ call that outlives its rule's remaining budget or the review's, and the
54
+ previous handler and timer are restored afterwards. Once a rule has spent
55
+ ``rule_budget_s`` in total, or the review ``total_budget_s``, no further
56
+ calls of it (or of any rule) are scheduled, the files left out become
57
+ ``partial`` and an issue naming the rule makes the review incomplete.
58
+ Code that ignores signals (a regex running in C, other threads, Windows)
59
+ cannot be interrupted: callers enforce :func:`hard_deadline_s` with a
60
+ watchdog (see there).
61
+ 6. Severity and dedupe: a hit's effective severity is the lower of its own
62
+ ``Hit.severity`` (when set) and ``policy.severity``, so a hit never
63
+ exceeds its rule's configured severity; a hit whose ``severity`` exceeds
64
+ the rule's metadata severity is a rule error. Dedupe on ``(rule, path,
65
+ side, line)`` keeps the first hit of the highest effective severity. Then
66
+ config ignores (``policy.ignore_reason``; the policy alone
67
+ enforces the repository-config limits on non-waivable rules, SPEC 6.3),
68
+ inline ignores (SPEC 7.3, see :func:`inline_ignorable` and step 7),
69
+ redaction, stable fingerprints, then a cap of :data:`MAX_FINDINGS` keeping
70
+ blocking findings first, and the verdict.
71
+ 7. Inline ignores: a ``codeveto-ignore: <rule> -- <reason>`` comment covers
72
+ its own line when code precedes it, else its line and the next. It is
73
+ honoured only when the policy allows inline ignores, the rule is
74
+ :func:`inline_ignorable`, the old side had the same ignore comment at the
75
+ paired line (a comment created around an unchanged line does not count),
76
+ and the covered line is not a pure insertion. Any other ignore next to a
77
+ finding becomes a :class:`ProposedIgnore` and the finding stays; when
78
+ ``agent/suppression-added`` is registered and enabled, each added or
79
+ edited one also raises that rule at the finding's severity. When the rule
80
+ itself reported the comment's line (its own, weaker hit), the finding with
81
+ the higher severity is kept, so the line is reported once.
82
+ 8. Redaction: every secret any hit marked (``Hit.redact``) is replaced by
83
+ ``[redacted]`` in every snippet, message, evidence, proposed-ignore text
84
+ and coverage reason the result carries. Paths are not redacted: a secret
85
+ in a file name stays visible.
86
+ """
87
+
88
+ from __future__ import annotations
89
+
90
+ import bisect
91
+ import dataclasses
92
+ import hashlib
93
+ import json
94
+ import re
95
+ import signal
96
+ import threading
97
+ import time
98
+ from collections import defaultdict, deque
99
+ from collections.abc import Callable, Iterable, Sequence
100
+ from dataclasses import dataclass, field
101
+ from enum import StrEnum
102
+ from types import FrameType
103
+ from typing import Literal, Protocol
104
+
105
+ from codeveto import languages, redact
106
+ from codeveto.git import FLAG_IMAGE_PREFIX, FLAG_INVALID_PATH, FLAG_MODE_CHANGE, SKIPPED_PREFIX
107
+ from codeveto.model import Changeset, FileChange, FileKind, FileStatus, Hunk, Side, git_lines
108
+ from codeveto.rules.base import (
109
+ RULE_ID,
110
+ ChangeContext,
111
+ FileContext,
112
+ Hit,
113
+ PartialCoverage,
114
+ RedactSpan,
115
+ Registry,
116
+ Rule,
117
+ RuleMeta,
118
+ Scope,
119
+ Severity,
120
+ )
121
+
122
+ __all__ = [
123
+ "ALWAYS_RUN_PACKS",
124
+ "BENIGN_REASONS",
125
+ "DEFAULT_RULE_BUDGET_S",
126
+ "DEFAULT_TOTAL_BUDGET_S",
127
+ "HARD_DEADLINE_GRACE_S",
128
+ "LANGUAGE_PACKS",
129
+ "MAX_FINDINGS",
130
+ "MAX_HITS_PER_CALL",
131
+ "MAX_SNIPPET_CHARS",
132
+ "REASON_DELETED",
133
+ "REASON_IMAGE_BINARY",
134
+ "REASON_PURE_RENAME",
135
+ "ConfigNote",
136
+ "Coverage",
137
+ "CoverageStatus",
138
+ "DefaultPolicy",
139
+ "EngineResult",
140
+ "FailOn",
141
+ "Finding",
142
+ "Issue",
143
+ "Policy",
144
+ "ProposedIgnore",
145
+ "Suppressed",
146
+ "Verdict",
147
+ "hard_deadline_s",
148
+ "inline_ignorable",
149
+ "normalize",
150
+ "review",
151
+ ]
152
+
153
+ FailOn = Literal["error", "warning", "note", "never"]
154
+ _FAIL_ON: tuple[str, ...] = ("error", "warning", "note", "never")
155
+
156
+ MAX_FINDINGS = 500
157
+ """Most findings (and, separately, suppressed findings) one result carries."""
158
+ MAX_HITS_PER_CALL = 10_000
159
+ """Most hits read from one rule call; the rest are cut off (coverage ``partial``)."""
160
+ MAX_SNIPPET_CHARS = 2_000
161
+ """Longest snippet kept (after redaction); the fingerprint still uses the whole line."""
162
+ DEFAULT_RULE_BUDGET_S = 10.0
163
+ """Total time one rule may spend in a review before it is no longer scheduled."""
164
+ DEFAULT_TOTAL_BUDGET_S = 120.0
165
+ """Time the whole rule run may take before no further rule calls are scheduled."""
166
+ HARD_DEADLINE_GRACE_S = 30.0
167
+ """Slack :func:`hard_deadline_s` adds on top of the budgets."""
168
+
169
+ LANGUAGE_PACKS = frozenset({"python", "js", "go", "rust", "shell", "docker", "sql"})
170
+ """Language bug-pattern packs (SPEC 6.1)."""
171
+ ALWAYS_RUN_PACKS = frozenset({"secrets", "security", "agent", "ci", "deps"})
172
+ """Packs that run on every text file regardless of class (SPEC 5.4)."""
173
+ _NOT_INLINE_IGNORABLE_PACKS = frozenset({"secrets", "agent", "ci"})
174
+ _CLASS_SUPPRESSES: dict[str, frozenset[str]] = {
175
+ "docs": LANGUAGE_PACKS,
176
+ "generated": LANGUAGE_PACKS | {"hygiene"},
177
+ "vendored": LANGUAGE_PACKS | {"hygiene"},
178
+ "minified": LANGUAGE_PACKS | {"hygiene"},
179
+ }
180
+
181
+ REASON_DELETED = "deleted file"
182
+ REASON_PURE_RENAME = "pure rename"
183
+ REASON_IMAGE_BINARY = "image binary"
184
+ BENIGN_REASONS = frozenset({REASON_DELETED, REASON_PURE_RENAME, REASON_IMAGE_BINARY})
185
+ """Coverage reasons that do not make a review incomplete (SPEC 5.6)."""
186
+
187
+ _KIND_REASONS: dict[FileKind, str] = {
188
+ FileKind.BINARY: "binary file",
189
+ FileKind.SYMLINK: "symlink",
190
+ FileKind.SUBMODULE: "submodule",
191
+ FileKind.LFS_POINTER: "LFS pointer",
192
+ }
193
+ _SUPPRESSION_RULE = "agent/suppression-added"
194
+ _EXECUTABLE = "100755"
195
+ _ALARM_REPEAT_S = 0.05
196
+
197
+
198
+ def hard_deadline_s(
199
+ total_budget_s: float = DEFAULT_TOTAL_BUDGET_S, rule_budget_s: float = DEFAULT_RULE_BUDGET_S
200
+ ) -> float:
201
+ """Wall-clock seconds after which a caller should abandon :func:`review`.
202
+
203
+ The engine stops scheduling rules once ``total_budget_s`` is spent and
204
+ interrupts a running rule with ``SIGALRM`` where it can. Where it cannot
205
+ (Windows, a review outside the main thread, a rule stuck in C code such
206
+ as a backtracking regex, which holds off signal handlers), only the
207
+ caller can stop it: the CLI runs a watchdog thread that, if ``review``
208
+ has not returned within this many seconds of starting, reports the review
209
+ ``incomplete`` ("rule run exceeded its hard deadline") and exits with code
210
+ 2 without waiting for the rule.
211
+ """
212
+ return total_budget_s + rule_budget_s + HARD_DEADLINE_GRACE_S
213
+
214
+
215
+ # --- Policy ------------------------------------------------------------------------
216
+
217
+
218
+ class Policy(Protocol):
219
+ """Everything the engine knows about configuration (SPEC 5.6)."""
220
+
221
+ fail_on: FailOn
222
+ allow_inline_ignores: bool
223
+
224
+ def enabled(self, meta: RuleMeta) -> bool: ...
225
+
226
+ def severity(self, meta: RuleMeta) -> Severity: ...
227
+
228
+ def ignore_reason(self, rule_id: str, path: str) -> str | None: ... # config [[ignore]] match
229
+
230
+ def file_class(self, path: str) -> str | None: ... # trusted generated/vendored patterns
231
+
232
+
233
+ @dataclass(frozen=True, slots=True)
234
+ class DefaultPolicy:
235
+ """Built-in defaults: block on errors, no inline ignores, rules as shipped.
236
+
237
+ ``all_rules=True`` also enables rules that are off by default (examples
238
+ and corpus runs, precision measurements).
239
+ """
240
+
241
+ fail_on: FailOn = "error"
242
+ allow_inline_ignores: bool = False
243
+ all_rules: bool = False
244
+
245
+ def enabled(self, meta: RuleMeta) -> bool:
246
+ return self.all_rules or meta.default_enabled
247
+
248
+ def severity(self, meta: RuleMeta) -> Severity:
249
+ return meta.severity
250
+
251
+ def ignore_reason(self, rule_id: str, path: str) -> str | None:
252
+ return None
253
+
254
+ def file_class(self, path: str) -> str | None:
255
+ return None
256
+
257
+
258
+ # --- Result types ------------------------------------------------------------------
259
+
260
+
261
+ class Verdict(StrEnum):
262
+ """Outcome of a review (SPEC 5.6)."""
263
+
264
+ CLEAR = "clear"
265
+ VETOED = "vetoed"
266
+ INCOMPLETE = "incomplete"
267
+
268
+ @property
269
+ def exit_code(self) -> int:
270
+ return {"clear": 0, "vetoed": 1, "incomplete": 2}[self.value]
271
+
272
+
273
+ class CoverageStatus(StrEnum):
274
+ """How completely one changed file was reviewed (JSON report ``coverage[].status``)."""
275
+
276
+ CHECKED = "checked"
277
+ PARTIAL = "partial"
278
+ SKIPPED = "skipped"
279
+
280
+
281
+ _STATUS_RANK = {CoverageStatus.CHECKED: 0, CoverageStatus.PARTIAL: 1, CoverageStatus.SKIPPED: 2}
282
+
283
+
284
+ @dataclass(frozen=True, slots=True)
285
+ class Coverage:
286
+ """Coverage of one changed file; ``reasons`` are empty when ``checked``."""
287
+
288
+ path: str
289
+ status: CoverageStatus
290
+ reasons: tuple[str, ...] = ()
291
+
292
+ @property
293
+ def benign(self) -> bool:
294
+ """Not checked, but only for reasons the verdict accepts."""
295
+ return (
296
+ self.status is not CoverageStatus.CHECKED
297
+ and bool(self.reasons)
298
+ and all(r in BENIGN_REASONS for r in self.reasons)
299
+ )
300
+
301
+ @property
302
+ def incomplete(self) -> bool:
303
+ """Does this coverage make the review incomplete?"""
304
+ return self.status is not CoverageStatus.CHECKED and not self.benign
305
+
306
+
307
+ @dataclass(frozen=True, slots=True)
308
+ class Issue:
309
+ """Something the review could not do.
310
+
311
+ ``kind`` is a fixed code (``changeset``, ``file``, ``policy``,
312
+ ``rule-error``, ``rule-partial``, ``rule-hits``, ``rule-budget``,
313
+ ``rule-timeout``, ``total-budget``, ``finding-cap``); ``message`` is text
314
+ CodeVeto wrote, never repository text (paths are kept apart in ``path``).
315
+ ``incomplete`` issues force an ``incomplete`` verdict unless a finding
316
+ blocks.
317
+ """
318
+
319
+ kind: str
320
+ message: str
321
+ path: str | None = None
322
+ rule: str | None = None
323
+ incomplete: bool = True
324
+
325
+
326
+ @dataclass(frozen=True, slots=True)
327
+ class Finding:
328
+ """One reported rule finding; text fields are already redacted."""
329
+
330
+ fingerprint: str
331
+ rule: str
332
+ severity: Severity
333
+ blocking: bool
334
+ path: str
335
+ old_path: str | None
336
+ side: Side
337
+ line: int | None
338
+ end_line: int | None
339
+ column: int | None
340
+ title: str
341
+ message: str
342
+ hint: str
343
+ snippet: str | None
344
+ evidence: str | None
345
+ source: Literal["rules"] = "rules"
346
+
347
+
348
+ @dataclass(frozen=True, slots=True)
349
+ class Suppressed:
350
+ """A finding taken out of the verdict by a config or inline ignore."""
351
+
352
+ finding: Finding
353
+ reason: str
354
+ via: Literal["config", "inline"]
355
+
356
+
357
+ @dataclass(frozen=True, slots=True)
358
+ class ProposedIgnore:
359
+ """An inline ignore next to a finding that was not applied (SPEC 7.3).
360
+
361
+ ``line`` is the comment's line; ``rule`` and ``reason`` are the comment's
362
+ text as written (bounded, redacted). ``why`` is ``malformed``,
363
+ ``not-ignorable``, ``added-by-change`` (the old side had no such
364
+ comment at this line), ``covers-added-line`` (an unchanged comment above
365
+ a newly inserted line) or ``inline-ignores-disabled``;
366
+ ``comment_changed`` says whether the change added or edited the comment.
367
+ """
368
+
369
+ path: str
370
+ line: int
371
+ rule: str
372
+ reason: str | None
373
+ target_rule: str
374
+ target_line: int
375
+ severity: Severity
376
+ why: str
377
+ comment_changed: bool
378
+
379
+
380
+ @dataclass(frozen=True, slots=True)
381
+ class ConfigNote:
382
+ """A config ignore applied to a non-waivable rule (SPEC 6.3 ``config_notes``)."""
383
+
384
+ rule: str
385
+ path: str
386
+ reason: str
387
+
388
+
389
+ @dataclass(frozen=True, slots=True)
390
+ class EngineResult:
391
+ """Everything one review found, in deterministic order."""
392
+
393
+ verdict: Verdict
394
+ fail_on: FailOn
395
+ findings: tuple[Finding, ...]
396
+ suppressed: tuple[Suppressed, ...]
397
+ proposed_ignores: tuple[ProposedIgnore, ...]
398
+ coverage: tuple[Coverage, ...]
399
+ issues: tuple[Issue, ...]
400
+ config_notes: tuple[ConfigNote, ...]
401
+ files: int
402
+ rules_enabled: int
403
+ rules_run: int
404
+ duration_s: float
405
+
406
+ @property
407
+ def exit_code(self) -> int:
408
+ return self.verdict.exit_code
409
+
410
+
411
+ # --- Helpers -------------------------------------------------------------------------
412
+
413
+
414
+ def normalize(text: str) -> str:
415
+ """Key normalization for the introduced-only filter: strip, collapse whitespace runs."""
416
+ return " ".join(text.split())
417
+
418
+
419
+ def inline_ignorable(meta: RuleMeta) -> bool:
420
+ """May ``codeveto-ignore`` comments suppress this rule (SPEC 7.3)?"""
421
+ return not meta.non_waivable and meta.pack not in _NOT_INLINE_IGNORABLE_PACKS
422
+
423
+
424
+ def _applies(meta: RuleMeta, language: str, file_class: str) -> bool:
425
+ if meta.languages is not None and language not in meta.languages:
426
+ return False
427
+ if meta.classes is not None:
428
+ return file_class in meta.classes
429
+ return meta.pack in ALWAYS_RUN_PACKS or meta.pack not in _CLASS_SUPPRESSES.get(
430
+ file_class, frozenset()
431
+ )
432
+
433
+
434
+ def _file_level_ok(change: FileChange) -> bool:
435
+ return (
436
+ change.status
437
+ in (FileStatus.ADDED, FileStatus.DELETED, FileStatus.RENAMED, FileStatus.TYPE_CHANGED)
438
+ or FLAG_MODE_CHANGE in change.flags
439
+ or change.kind is not FileKind.TEXT
440
+ )
441
+
442
+
443
+ def _is_pure_rename(change: FileChange) -> bool:
444
+ if change.status is not FileStatus.RENAMED or change.old_mode != change.new_mode:
445
+ return False
446
+ if change.old_text is not None or change.new_text is not None:
447
+ return change.old_text == change.new_text
448
+ return change.similarity == 100
449
+
450
+
451
+ def _is_benign_image(change: FileChange) -> bool:
452
+ return (
453
+ change.kind is FileKind.BINARY
454
+ and any(f.startswith(FLAG_IMAGE_PREFIX) for f in change.flags)
455
+ and change.status in (FileStatus.ADDED, FileStatus.MODIFIED, FileStatus.RENAMED)
456
+ and change.new_mode != _EXECUTABLE
457
+ and FLAG_MODE_CHANGE not in change.flags
458
+ and (change.old_mode is None or change.old_mode == change.new_mode)
459
+ )
460
+
461
+
462
+ def _skip_reason(change: FileChange) -> str:
463
+ if change.status is FileStatus.DELETED:
464
+ return REASON_DELETED
465
+ if _is_pure_rename(change):
466
+ return REASON_PURE_RENAME
467
+ if _is_benign_image(change):
468
+ return REASON_IMAGE_BINARY
469
+ return _KIND_REASONS.get(change.kind, "not reviewable")
470
+
471
+
472
+ def _reversed(change: FileChange) -> FileChange:
473
+ """The change seen backwards: the old side becomes the new side."""
474
+ status = {FileStatus.ADDED: FileStatus.DELETED, FileStatus.DELETED: FileStatus.ADDED}.get(
475
+ change.status, change.status
476
+ )
477
+ if change.status is FileStatus.RENAMED and change.old_path is not None:
478
+ path, old_path = change.old_path, change.path
479
+ else:
480
+ path, old_path = change.path, None
481
+ return FileChange(
482
+ path=path,
483
+ old_path=old_path,
484
+ status=status,
485
+ kind=FileKind.TEXT,
486
+ old_mode=change.new_mode,
487
+ new_mode=change.old_mode,
488
+ old_text=change.new_text,
489
+ new_text=change.old_text,
490
+ old_size=change.new_size,
491
+ new_size=change.old_size,
492
+ added_lines=change.removed_lines,
493
+ removed_lines=change.added_lines,
494
+ hunks=tuple(Hunk(h.new_start, h.new_count, h.old_start, h.old_count) for h in change.hunks),
495
+ similarity=change.similarity,
496
+ flags=change.flags,
497
+ )
498
+
499
+
500
+ def _paired_old_lines(change: FileChange) -> dict[int, int]:
501
+ """Old line each deletion point stands for, mapped to its hunk index.
502
+
503
+ A deletion point is the new line before a pure deletion (``new_start``),
504
+ which is old line ``old_start - 1``; a deletion at the top anchors at new
505
+ line 1, the old line right after the removed block.
506
+ """
507
+ old_count = len(git_lines(change.old_text))
508
+ paired: dict[int, int] = {}
509
+ for i, h in enumerate(change.hunks):
510
+ if not h.is_pure_deletion:
511
+ continue
512
+ line = h.old_start - 1 if h.new_start >= 1 else h.old_start + h.old_count
513
+ if 1 <= line <= old_count:
514
+ paired.setdefault(line, i)
515
+ return paired
516
+
517
+
518
+ def _old_line_of(change: FileChange, line: int) -> int:
519
+ """Old line number of new line ``line``, which no hunk changed."""
520
+ delta = 0
521
+ for h in change.hunks:
522
+ new_end = h.new_start + h.new_count - 1 if h.new_count else h.new_start
523
+ if line > new_end:
524
+ delta += h.old_count - h.new_count
525
+ return line + delta
526
+
527
+
528
+ class _InvalidHit(Exception):
529
+ pass
530
+
531
+
532
+ class _InvalidSeverity(_InvalidHit):
533
+ pass
534
+
535
+
536
+ class _RuleTimeout(BaseException):
537
+ """Raised inside a running rule by the interval timer once its budget is spent."""
538
+
539
+
540
+ class _Alarm:
541
+ """Interrupts a rule call with ``SIGALRM`` (POSIX, main thread only).
542
+
543
+ The previous handler and timer are saved on entry and restored on exit;
544
+ a timer that was pending is re-armed with the time it had left (or fires
545
+ right away if that has passed). The handler raises only while a rule call
546
+ is armed, and it repeats every ``_ALARM_REPEAT_S`` seconds so a rule that
547
+ swallows the first interruption gets another.
548
+ """
549
+
550
+ def __init__(self) -> None:
551
+ self.enabled = (
552
+ hasattr(signal, "setitimer")
553
+ and hasattr(signal, "SIGALRM")
554
+ and threading.current_thread() is threading.main_thread()
555
+ )
556
+ self.armed = False
557
+ self._old_handler: object = None
558
+ self._old_timer: tuple[float, float] = (0.0, 0.0)
559
+ self._entered = 0.0
560
+
561
+ def _handle(self, signum: int, frame: FrameType | None) -> None:
562
+ if self.armed:
563
+ raise _RuleTimeout
564
+
565
+ def __enter__(self) -> _Alarm:
566
+ if self.enabled:
567
+ try:
568
+ self._old_handler = signal.signal(signal.SIGALRM, self._handle)
569
+ except (ValueError, OSError):
570
+ self.enabled = False
571
+ return self
572
+ self._old_timer = signal.setitimer(signal.ITIMER_REAL, 0)
573
+ self._entered = time.monotonic()
574
+ return self
575
+
576
+ def __exit__(self, *exc: object) -> None:
577
+ if not self.enabled:
578
+ return
579
+ self.armed = False
580
+ signal.setitimer(signal.ITIMER_REAL, 0)
581
+ old = self._old_handler
582
+ signal.signal(signal.SIGALRM, old if old is not None else signal.SIG_DFL) # type: ignore[arg-type]
583
+ delay, interval = self._old_timer
584
+ if delay > 0:
585
+ left = delay - (time.monotonic() - self._entered)
586
+ signal.setitimer(signal.ITIMER_REAL, max(left, 0.001), interval)
587
+
588
+ def arm(self, seconds: float) -> None:
589
+ if self.enabled:
590
+ self.armed = True
591
+ signal.setitimer(signal.ITIMER_REAL, max(seconds, 0.001), _ALARM_REPEAT_S)
592
+
593
+ def disarm(self) -> None:
594
+ if self.enabled:
595
+ self.armed = False
596
+ signal.setitimer(signal.ITIMER_REAL, 0)
597
+
598
+
599
+ @dataclass(slots=True, eq=False)
600
+ class _Raw:
601
+ """An anchored hit before severity, ignores and redaction."""
602
+
603
+ rule: Rule
604
+ file: _FileState
605
+ side: Side
606
+ line: int | None
607
+ end_line: int | None
608
+ column: int | None
609
+ message: str | None
610
+ evidence: str | None
611
+ spans: tuple[RedactSpan, ...]
612
+ lines: Sequence[str]
613
+ hit_severity: Severity | None = None
614
+ severity: Severity = Severity.NOTE
615
+ blocking: bool = False
616
+
617
+ @property
618
+ def key(self) -> tuple[str, str, Side, int | None]:
619
+ return (self.rule.id, self.file.change.path, self.side, self.line)
620
+
621
+ def sort_key(self) -> tuple[int, int, int, str, int]:
622
+ return (
623
+ self.file.index,
624
+ self.line or 0,
625
+ 0 if self.side is Side.NEW else 1,
626
+ self.rule.id,
627
+ self.column or 0,
628
+ )
629
+
630
+ def text(self) -> str | None:
631
+ if self.line is None or self.line > len(self.lines):
632
+ return None
633
+ return self.lines[self.line - 1]
634
+
635
+ def match_key(self) -> str:
636
+ """Identity for the introduced-only filter (module docstring, step 4)."""
637
+ return normalize(self.evidence if self.evidence is not None else self.text() or "")
638
+
639
+
640
+ @dataclass(frozen=True, slots=True)
641
+ class _Ignore:
642
+ line: int
643
+ first_line: int
644
+ targets: tuple[int, ...]
645
+ token: str
646
+ reason: str | None
647
+ valid: bool
648
+
649
+
650
+ _IGNORE_WORD = "codeveto-ignore"
651
+ _IGNORE = re.compile(
652
+ r"codeveto-ignore(?P<colon>:?)[ \t]*(?P<rule>[^\s]{0,200})"
653
+ r"(?:[ \t]+--(?:[ \t]+(?P<reason>[^\r\n]{0,500}))?)?"
654
+ )
655
+
656
+
657
+ def _parse_ignores(ctx: FileContext) -> list[_Ignore]:
658
+ """Every ``codeveto-ignore`` occurrence inside a comment of ``ctx``'s new side."""
659
+ text = ctx.new_text or ""
660
+ found: list[_Ignore] = []
661
+ if _IGNORE_WORD not in text:
662
+ return found
663
+ index = ctx.line_index
664
+ for comment in ctx.comments():
665
+ content = text[comment.content_start : comment.content_end]
666
+ pos = content.find(_IGNORE_WORD)
667
+ first_line = index.line_of(comment.start)
668
+ while pos >= 0:
669
+ offset = comment.content_start + pos
670
+ line = index.line_of(offset)
671
+ code_before = (
672
+ line == first_line and text[index.line_start(line) : comment.start].strip()
673
+ )
674
+ match = _IGNORE.match(text, offset, comment.content_end)
675
+ token = match.group("rule") if match else ""
676
+ reason = (match.group("reason") or "").strip() if match else ""
677
+ valid = bool(match and match.group("colon") and RULE_ID.fullmatch(token) and reason)
678
+ targets = (line,) if code_before else (line, line + 1)
679
+ found.append(_Ignore(line, first_line, targets, token, reason or None, valid))
680
+ pos = content.find(_IGNORE_WORD, pos + len(_IGNORE_WORD))
681
+ return found
682
+
683
+
684
+ class _FileState:
685
+ """One changed file: its context, coverage and lazily built anchoring data."""
686
+
687
+ def __init__(self, index: int, change: FileChange, ctx: FileContext) -> None:
688
+ self.index = index
689
+ self.change = change
690
+ self.ctx = ctx
691
+ self.status = CoverageStatus.CHECKED
692
+ self.reasons: list[str] = []
693
+ self._valid: dict[Side, list[int]] = {}
694
+ self._hunk_of: dict[Side, dict[int, int]] = {}
695
+ self._paired: dict[int, int] | None = None
696
+ self._old_valid: list[int] | None = None
697
+ self._old_ctx: FileContext | None = None
698
+ self._old_ctx_built = False
699
+ self._ignores: dict[int, list[tuple[_Ignore, bool]]] | None = None
700
+
701
+ def mark(self, status: CoverageStatus, reason: str) -> None:
702
+ if _STATUS_RANK[status] > _STATUS_RANK[self.status]:
703
+ self.status = status
704
+ if reason not in self.reasons:
705
+ self.reasons.append(reason)
706
+
707
+ def valid(self, side: Side) -> list[int]:
708
+ if side not in self._valid:
709
+ if side is Side.NEW:
710
+ lines = set(self.change.added_lines) | set(self.ctx.deletion_points)
711
+ else:
712
+ lines = set(self.change.removed_lines)
713
+ self._valid[side] = sorted(lines)
714
+ return self._valid[side]
715
+
716
+ def paired(self) -> dict[int, int]:
717
+ if self._paired is None:
718
+ self._paired = _paired_old_lines(self.change)
719
+ return self._paired
720
+
721
+ def old_run_valid(self) -> list[int]:
722
+ """Anchors of an old-side run: removed lines and deletion-point partners."""
723
+ if self._old_valid is None:
724
+ self._old_valid = sorted(set(self.change.removed_lines) | set(self.paired()))
725
+ return self._old_valid
726
+
727
+ def hunk_of(self, side: Side, line: int) -> int | None:
728
+ if side not in self._hunk_of:
729
+ table: dict[int, int] = {}
730
+ for i, h in enumerate(self.change.hunks):
731
+ for n in h.new_lines if side is Side.NEW else h.old_lines:
732
+ table[n] = i
733
+ if side is Side.NEW and h.is_pure_deletion:
734
+ table.setdefault(max(h.new_start, 1), i)
735
+ if side is Side.OLD:
736
+ for n, i in self.paired().items():
737
+ table.setdefault(n, i)
738
+ self._hunk_of[side] = table
739
+ return self._hunk_of[side].get(line)
740
+
741
+ def pure_insertion(self, line: int) -> bool:
742
+ hunk = self.hunk_of(Side.NEW, line)
743
+ return hunk is not None and self.change.hunks[hunk].is_pure_insertion
744
+
745
+
746
+ # --- The review ------------------------------------------------------------------------
747
+
748
+
749
+ @dataclass(slots=True)
750
+ class _Call:
751
+ hits: list[object] = field(default_factory=list)
752
+ error: str | None = None
753
+ gap: str | None = None
754
+ overflow: bool = False
755
+ timed_out: bool = False
756
+
757
+
758
+ class _Review:
759
+ def __init__(
760
+ self,
761
+ changeset: Changeset,
762
+ registry: Registry,
763
+ policy: Policy,
764
+ rule_budget_s: float,
765
+ total_budget_s: float,
766
+ clock: Callable[[], float],
767
+ alarm: _Alarm,
768
+ ) -> None:
769
+ self.changeset = changeset
770
+ self.registry = registry
771
+ self.policy = policy
772
+ self.rule_budget_s = rule_budget_s
773
+ self.total_budget_s = total_budget_s
774
+ self.clock = clock
775
+ self.alarm = alarm
776
+ self.start = clock()
777
+ self.issues: list[Issue] = []
778
+ self.secrets: set[str] = set()
779
+ self.rule_time: defaultdict[str, float] = defaultdict(float)
780
+ self.exhausted: set[str] = set()
781
+ self.out_of_time = False
782
+ self.ran: set[str] = set()
783
+ self.raws: list[_Raw] = []
784
+ self.severities: dict[str, Severity] = {} # policy severity by rule id, set by _run
785
+ self.rule_errors: set[tuple[str, str | None]] = set()
786
+ self.files: list[_FileState] = []
787
+ self.by_path: dict[str, _FileState] = {}
788
+
789
+ def effective(self, raw: _Raw) -> Severity:
790
+ """The lower of the hit's own severity and the rule's policy severity."""
791
+ policy = self.severities.get(raw.rule.id, raw.rule.meta.severity)
792
+ if raw.hit_severity is None or raw.hit_severity >= policy:
793
+ return policy
794
+ return raw.hit_severity
795
+
796
+ # Issues and budgets.
797
+
798
+ def issue(
799
+ self,
800
+ kind: str,
801
+ message: str,
802
+ *,
803
+ path: str | None = None,
804
+ rule: str | None = None,
805
+ incomplete: bool = True,
806
+ ) -> None:
807
+ self.issues.append(Issue(kind, message, path, rule, incomplete))
808
+
809
+ def rule_error(self, rule: Rule, fs: _FileState | None, message: str) -> None:
810
+ path = fs.change.path if fs is not None else None
811
+ if fs is not None:
812
+ fs.mark(CoverageStatus.PARTIAL, f"rule {rule.id} failed")
813
+ if (rule.id, path) not in self.rule_errors:
814
+ self.rule_errors.add((rule.id, path))
815
+ self.issue("rule-error", message, path=path, rule=rule.id)
816
+
817
+ def spend_total(self) -> None:
818
+ if not self.out_of_time:
819
+ self.out_of_time = True
820
+ self.issue(
821
+ "total-budget",
822
+ f"the {self.total_budget_s:g}-second rule time budget was spent; "
823
+ "the remaining rule runs were not scheduled",
824
+ )
825
+
826
+ def schedulable(self, rule: Rule, fs: _FileState | None) -> bool:
827
+ """May ``rule`` run now? Marks the file when not."""
828
+ if self.clock() - self.start >= self.total_budget_s:
829
+ self.spend_total()
830
+ if self.out_of_time:
831
+ if fs is not None:
832
+ fs.mark(CoverageStatus.PARTIAL, "total rule time budget spent")
833
+ return False
834
+ if rule.id in self.exhausted:
835
+ if fs is not None:
836
+ fs.mark(CoverageStatus.PARTIAL, f"rule {rule.id} not run: time budget spent")
837
+ return False
838
+ return True
839
+
840
+ def call(self, rule: Rule, arg: FileContext | ChangeContext) -> _Call:
841
+ result = _Call()
842
+ started = self.clock()
843
+ left = min(
844
+ self.rule_budget_s - self.rule_time[rule.id],
845
+ self.total_budget_s - (started - self.start),
846
+ )
847
+ try:
848
+ try:
849
+ self.alarm.arm(left)
850
+ iterator = iter(rule.func(arg)) # type: ignore[arg-type]
851
+ for hit in iterator:
852
+ result.hits.append(hit)
853
+ if len(result.hits) >= MAX_HITS_PER_CALL:
854
+ result.overflow = True
855
+ close = getattr(iterator, "close", None)
856
+ if close is not None:
857
+ close()
858
+ break
859
+ finally:
860
+ self.alarm.disarm()
861
+ except _RuleTimeout:
862
+ result.timed_out = True
863
+ except PartialCoverage as exc:
864
+ result.gap = exc.reason
865
+ except KeyboardInterrupt:
866
+ raise
867
+ except BaseException as exc: # SystemExit, GeneratorExit and the like are rule bugs too
868
+ result.error = type(exc).__name__
869
+ self.ran.add(rule.id)
870
+ self.rule_time[rule.id] += self.clock() - started
871
+ if result.timed_out and self.clock() - self.start >= self.total_budget_s:
872
+ self.spend_total()
873
+ if self.rule_time[rule.id] >= self.rule_budget_s and rule.id not in self.exhausted:
874
+ self.exhausted.add(rule.id)
875
+ self.issue(
876
+ "rule-budget",
877
+ f"rule spent more than its {self.rule_budget_s:g}-second time budget; "
878
+ "it was not run on the remaining files",
879
+ rule=rule.id,
880
+ )
881
+ return result
882
+
883
+ def timed_out(self, rule: Rule, fs: _FileState | None) -> None:
884
+ if fs is not None:
885
+ fs.mark(CoverageStatus.PARTIAL, f"rule {rule.id} stopped: time budget spent")
886
+ self.issue(
887
+ "rule-timeout",
888
+ "rule was stopped because it ran past its time budget",
889
+ path=fs.change.path if fs is not None else None,
890
+ rule=rule.id,
891
+ )
892
+
893
+ # Contexts.
894
+
895
+ def classify(self, path: str, text: str | None, mode: str | None) -> tuple[str, str]:
896
+ info = languages.classify(path, text=text, executable=mode == _EXECUTABLE)
897
+ trusted = self.policy.file_class(path)
898
+ if trusted is None:
899
+ return info.language, info.file_class
900
+ if trusted not in languages.FILE_CLASSES:
901
+ self.issue("policy", "policy returned an unknown file class", path=path)
902
+ return info.language, info.file_class
903
+ return info.language, trusted
904
+
905
+ def build_files(self) -> None:
906
+ for index, change in enumerate(self.changeset.files):
907
+ text = change.new_text if change.new_text is not None else change.old_text
908
+ mode = change.new_mode if change.new_mode is not None else change.old_mode
909
+ language, file_class = self.classify(change.path, text, mode)
910
+ fs = _FileState(
911
+ index, change, FileContext(change, language, file_class, self.changeset)
912
+ )
913
+ self.files.append(fs)
914
+ self.by_path.setdefault(change.path, fs)
915
+
916
+ def old_context(self, fs: _FileState) -> FileContext | None:
917
+ if not fs._old_ctx_built:
918
+ fs._old_ctx_built = True
919
+ change = fs.change
920
+ if change.old_text is not None:
921
+ rev = _reversed(change)
922
+ language, file_class = self.classify(rev.path, rev.new_text, rev.new_mode)
923
+ fs._old_ctx = FileContext(rev, language, file_class, self.changeset)
924
+ return fs._old_ctx
925
+
926
+ # Anchoring.
927
+
928
+ def collect_secrets(self, hit: Hit, lines: Sequence[str]) -> None:
929
+ if hit.redact:
930
+ try:
931
+ self.secrets.update(redact.secret_values(lines, hit.redact))
932
+ except redact.SpanError:
933
+ raise _InvalidHit from None
934
+
935
+ def anchor(
936
+ self,
937
+ rule: Rule,
938
+ fs: _FileState,
939
+ hit: Hit,
940
+ ctx: FileContext,
941
+ old_valid: list[int] | None = None,
942
+ ) -> _Raw | None:
943
+ """Anchor ``hit`` (reported against ``ctx``) or return ``None`` when off the change.
944
+
945
+ ``old_valid`` is given for an old-side run: the anchors of that run's
946
+ new side (removed lines and deletion-point partners).
947
+ """
948
+ side = hit.side
949
+ lines = ctx.lines if side is Side.NEW else ctx.old_lines
950
+ self.collect_secrets(hit, lines)
951
+ if hit.severity is not None and hit.severity > rule.meta.severity:
952
+ raise _InvalidSeverity
953
+ old_run = old_valid is not None
954
+ if hit.line is None:
955
+ if rule.meta.scope is Scope.LINE or not _file_level_ok(fs.change) or old_run:
956
+ raise _InvalidHit
957
+ return _Raw(
958
+ rule,
959
+ fs,
960
+ side,
961
+ None,
962
+ None,
963
+ None,
964
+ hit.message,
965
+ hit.evidence,
966
+ hit.redact,
967
+ lines,
968
+ hit.severity,
969
+ )
970
+ if old_run and side is Side.OLD:
971
+ return None # the reversed change's old side is the new side: not compared
972
+ valid = fs.valid(side) if old_valid is None else old_valid
973
+ upper = max(len(lines), valid[-1] if valid else 0)
974
+ end = hit.end_line if hit.end_line is not None else hit.line
975
+ if hit.line > upper or end > upper:
976
+ raise _InvalidHit
977
+ i = bisect.bisect_left(valid, hit.line)
978
+ if i == len(valid) or valid[i] > end:
979
+ return None
980
+ line = valid[i]
981
+ column = hit.column if line == hit.line else None
982
+ end_line = hit.end_line if hit.end_line is not None and hit.end_line > line else None
983
+ return _Raw(
984
+ rule,
985
+ fs,
986
+ side,
987
+ line,
988
+ end_line,
989
+ column,
990
+ hit.message,
991
+ hit.evidence,
992
+ hit.redact,
993
+ lines,
994
+ hit.severity,
995
+ )
996
+
997
+ def anchor_all(
998
+ self,
999
+ rule: Rule,
1000
+ fs: _FileState,
1001
+ hits: Iterable[object],
1002
+ ctx: FileContext,
1003
+ *,
1004
+ old_run: bool = False,
1005
+ ) -> list[_Raw]:
1006
+ raws: list[_Raw] = []
1007
+ old_valid = fs.old_run_valid() if old_run else None
1008
+ for hit in hits:
1009
+ try:
1010
+ if not isinstance(hit, Hit) or hit.path is not None:
1011
+ raise _InvalidHit
1012
+ raw = self.anchor(rule, fs, hit, ctx, old_valid)
1013
+ except _InvalidHit as exc:
1014
+ if not old_run:
1015
+ self.rule_error(rule, fs, _invalid_message(exc))
1016
+ continue
1017
+ if raw is not None:
1018
+ raws.append(raw)
1019
+ return raws
1020
+
1021
+ # Introduced-only.
1022
+
1023
+ def introduced(self, rule: Rule, fs: _FileState, raws: list[_Raw]) -> list[_Raw]:
1024
+ fresh = [r for r in raws if r.side is Side.NEW and r.line is not None]
1025
+ if not fresh:
1026
+ return raws
1027
+ old_ctx = self.old_context(fs)
1028
+ if old_ctx is None or not _applies(rule.meta, old_ctx.language, old_ctx.file_class):
1029
+ return raws
1030
+ if not self.schedulable(rule, None):
1031
+ return raws
1032
+ result = self.call(rule, old_ctx)
1033
+ # Anchoring collects the old hits' secrets for redaction in every case.
1034
+ old = [
1035
+ r
1036
+ for r in self.anchor_all(rule, fs, result.hits, old_ctx, old_run=True)
1037
+ if r.side is Side.NEW and r.line is not None
1038
+ ]
1039
+ if result.timed_out:
1040
+ self.timed_out(rule, fs)
1041
+ if result.error is not None or result.overflow or result.timed_out or not old:
1042
+ return raws # old side unknown or empty: keep every new hit
1043
+ dropped = _match(fs, fresh, old, self.effective)
1044
+ return [r for r in raws if id(r) not in dropped]
1045
+
1046
+ # Runs.
1047
+
1048
+ def run_files(self, rules: Sequence[Rule]) -> None:
1049
+ file_rules = [r for r in rules if r.meta.scope is not Scope.CHANGE]
1050
+ for fs in self.files:
1051
+ change, ctx = fs.change, fs.ctx
1052
+ skipped = sorted(f for f in change.flags if f.startswith(SKIPPED_PREFIX))
1053
+ for message in change.issues:
1054
+ self.issue("file", message, path=change.path)
1055
+ if FLAG_INVALID_PATH in change.flags:
1056
+ fs.mark(CoverageStatus.SKIPPED, "invalid path")
1057
+ for flag in skipped:
1058
+ if flag != SKIPPED_PREFIX + FLAG_INVALID_PATH:
1059
+ fs.mark(CoverageStatus.SKIPPED, "skipped: " + flag[len(SKIPPED_PREFIX) :])
1060
+ if fs.status is CoverageStatus.SKIPPED:
1061
+ continue
1062
+ if change.kind is not FileKind.TEXT:
1063
+ selected = [
1064
+ r
1065
+ for r in file_rules
1066
+ if r.meta.scope is Scope.FILE
1067
+ and change.kind in r.meta.kinds
1068
+ and _applies(r.meta, ctx.language, ctx.file_class)
1069
+ ]
1070
+ if not selected:
1071
+ fs.mark(CoverageStatus.SKIPPED, _skip_reason(change))
1072
+ continue
1073
+ elif change.new_text is None and change.old_text is None:
1074
+ fs.mark(CoverageStatus.SKIPPED, "no content")
1075
+ continue
1076
+ else:
1077
+ selected = [
1078
+ r
1079
+ for r in file_rules
1080
+ if FileKind.TEXT in r.meta.kinds
1081
+ and _applies(r.meta, ctx.language, ctx.file_class)
1082
+ ]
1083
+ for reason in ctx.text_issues:
1084
+ fs.mark(CoverageStatus.PARTIAL, reason)
1085
+ for rule in selected:
1086
+ if self.schedulable(rule, fs):
1087
+ self.run_file_rule(rule, fs)
1088
+
1089
+ def run_file_rule(self, rule: Rule, fs: _FileState) -> None:
1090
+ result = self.call(rule, fs.ctx)
1091
+ raws = self.anchor_all(rule, fs, result.hits, fs.ctx)
1092
+ if result.error is not None:
1093
+ self.rule_error(rule, fs, f"rule raised {result.error}")
1094
+ if result.timed_out:
1095
+ self.timed_out(rule, fs)
1096
+ if result.gap is not None:
1097
+ fs.mark(CoverageStatus.PARTIAL, f"{rule.id}: {result.gap}")
1098
+ if result.overflow:
1099
+ fs.mark(CoverageStatus.PARTIAL, f"rule {rule.id} reported too many hits")
1100
+ self.issue(
1101
+ "rule-hits",
1102
+ f"rule reported more than {MAX_HITS_PER_CALL} hits; the rest were not read",
1103
+ path=fs.change.path,
1104
+ rule=rule.id,
1105
+ )
1106
+ if rule.meta.scope is Scope.LINE and rule.meta.introduced_only:
1107
+ raws = self.introduced(rule, fs, raws)
1108
+ self.raws.extend(raws)
1109
+
1110
+ def run_change(self, rules: Sequence[Rule]) -> None:
1111
+ change_rules = [r for r in rules if r.meta.scope is Scope.CHANGE]
1112
+ if not change_rules:
1113
+ return
1114
+ context = ChangeContext(self.changeset, [fs.ctx for fs in self.files])
1115
+ for rule in change_rules:
1116
+ if not self.schedulable(rule, None):
1117
+ self.issue("rule-budget", "change rule not run: time budget spent", rule=rule.id)
1118
+ continue
1119
+ result = self.call(rule, context)
1120
+ if result.error is not None:
1121
+ self.rule_error(rule, None, f"rule raised {result.error}")
1122
+ if result.timed_out:
1123
+ self.timed_out(rule, None)
1124
+ if result.gap is not None:
1125
+ self.issue("rule-partial", "rule could not fully check the change", rule=rule.id)
1126
+ if result.overflow:
1127
+ self.issue(
1128
+ "rule-hits",
1129
+ f"rule reported more than {MAX_HITS_PER_CALL} hits; the rest were not read",
1130
+ rule=rule.id,
1131
+ )
1132
+ for hit in result.hits:
1133
+ if not isinstance(hit, Hit) or hit.path is None or hit.path not in self.by_path:
1134
+ self.rule_error(rule, None, "rule reported a hit without a changed path")
1135
+ continue
1136
+ fs = self.by_path[hit.path]
1137
+ try:
1138
+ raw = self.anchor(rule, fs, hit, fs.ctx)
1139
+ except _InvalidHit as exc:
1140
+ self.rule_error(rule, fs, _invalid_message(exc))
1141
+ continue
1142
+ if raw is not None:
1143
+ self.raws.append(raw)
1144
+
1145
+
1146
+ def _match(
1147
+ fs: _FileState,
1148
+ fresh: list[_Raw],
1149
+ old: list[_Raw],
1150
+ effective: Callable[[_Raw], Severity],
1151
+ ) -> set[int]:
1152
+ """IDs of new raws an old raw of the same rule cancels (module docstring, step 4).
1153
+
1154
+ An old raw cancels only a new raw whose effective severity is at most its own.
1155
+ """
1156
+ used = [False] * len(old)
1157
+ same: dict[tuple[int | None, str], deque[int]] = defaultdict(deque)
1158
+ anywhere: dict[str, deque[int]] = defaultdict(deque)
1159
+ old_rank = [effective(raw).rank for raw in old]
1160
+ for i, raw in enumerate(old):
1161
+ key = raw.match_key()
1162
+ same[(fs.hunk_of(Side.OLD, raw.line or 0), key)].append(i)
1163
+ anywhere[key].append(i)
1164
+ dropped: set[int] = set()
1165
+ for raw in fresh:
1166
+ key = raw.match_key()
1167
+ rank = effective(raw).rank
1168
+ hunk = fs.hunk_of(Side.NEW, raw.line or 0)
1169
+ match = _take(same.get((hunk, key)), used, old_rank, rank) if hunk is not None else None
1170
+ if match is None:
1171
+ match = _take(anywhere.get(key), used, old_rank, rank)
1172
+ if match is not None:
1173
+ used[match] = True
1174
+ dropped.add(id(raw))
1175
+ return dropped
1176
+
1177
+
1178
+ def _take(queue: deque[int] | None, used: list[bool], old_rank: list[int], rank: int) -> int | None:
1179
+ """The first unused old raw in ``queue`` whose severity rank is at least ``rank``."""
1180
+ if not queue:
1181
+ return None
1182
+ while queue and used[queue[0]]:
1183
+ queue.popleft()
1184
+ return next((i for i in queue if not used[i] and old_rank[i] >= rank), None)
1185
+
1186
+
1187
+ def _invalid_message(exc: _InvalidHit) -> str:
1188
+ if isinstance(exc, _InvalidSeverity):
1189
+ return "rule reported a hit above its severity"
1190
+ return "rule reported a hit with an invalid location"
1191
+
1192
+
1193
+ # --- Finishing: dedupe, severity, ignores, redaction, fingerprints, verdict ----------------
1194
+
1195
+
1196
+ def _blocks(severity: Severity, fail_on: str) -> bool:
1197
+ if fail_on == "never":
1198
+ return False
1199
+ return severity >= Severity(fail_on)
1200
+
1201
+
1202
+ @dataclass(slots=True)
1203
+ class _Prepared:
1204
+ raw: _Raw
1205
+ snippet: str | None
1206
+ message: str
1207
+ evidence: str | None
1208
+ text: str
1209
+ suppressed: tuple[str, Literal["config", "inline"]] | None = None
1210
+ fingerprint: str = ""
1211
+
1212
+
1213
+ def _fingerprint(rule: str, path: str, side: str, text: str, index: int) -> str:
1214
+ payload = json.dumps([rule, path, side, text, index], ensure_ascii=True)
1215
+ return hashlib.sha256(payload.encode("ascii")).hexdigest()[:16]
1216
+
1217
+
1218
+ @dataclass(frozen=True, slots=True)
1219
+ class _Proposal:
1220
+ ignore: _Ignore
1221
+ changed: bool
1222
+ path: str
1223
+ target_rule: str
1224
+ target_line: int
1225
+ severity: Severity
1226
+ why: str
1227
+
1228
+
1229
+ class _Finisher:
1230
+ def __init__(self, review: _Review, fail_on: FailOn) -> None:
1231
+ self.review = review
1232
+ self.fail_on = fail_on
1233
+ self.proposed: list[_Proposal] = []
1234
+ self.notes: dict[tuple[str, str], ConfigNote] = {}
1235
+ self._config: dict[tuple[str, str], str | None] = {}
1236
+
1237
+ def config_reason(self, raw: _Raw) -> str | None:
1238
+ key = (raw.rule.id, raw.file.change.path)
1239
+ if key not in self._config:
1240
+ reason = self.review.policy.ignore_reason(*key)
1241
+ self._config[key] = reason
1242
+ if reason is not None and raw.rule.meta.non_waivable:
1243
+ self.notes[key] = ConfigNote(key[0], key[1], reason)
1244
+ return self._config[key]
1245
+
1246
+ def ignores(self, fs: _FileState) -> dict[int, list[tuple[_Ignore, bool]]]:
1247
+ """New-side ignore comments by target line, each with "added or edited by the change"."""
1248
+ if fs._ignores is not None:
1249
+ return fs._ignores
1250
+ table: dict[int, list[tuple[_Ignore, bool]]] = defaultdict(list)
1251
+ found = _parse_ignores(fs.ctx)
1252
+ if found:
1253
+ old_ctx = self.review.old_context(fs)
1254
+ old = (
1255
+ {(i.line, i.token, i.reason) for i in _parse_ignores(old_ctx)}
1256
+ if old_ctx is not None
1257
+ else set()
1258
+ )
1259
+ for ignore in found:
1260
+ changed = ignore.line in fs.change.added_lines or (
1261
+ (_old_line_of(fs.change, ignore.line), ignore.token, ignore.reason) not in old
1262
+ )
1263
+ for target in ignore.targets:
1264
+ table[target].append((ignore, changed))
1265
+ fs._ignores = table
1266
+ return table
1267
+
1268
+ def inline(self, raws: list[_Raw]) -> dict[int, str]:
1269
+ """Apply inline ignores; return honoured reasons by raw id and record proposals."""
1270
+ honoured: dict[int, str] = {}
1271
+ allow = bool(self.review.policy.allow_inline_ignores)
1272
+ for raw in raws:
1273
+ if raw.side is not Side.NEW or raw.line is None or raw.file.ctx.new_text is None:
1274
+ continue
1275
+ comments = self.ignores(raw.file).get(raw.line)
1276
+ if not comments:
1277
+ continue
1278
+ ignorable = inline_ignorable(raw.rule.meta)
1279
+ inserted = raw.file.pure_insertion(raw.line)
1280
+ for ignore, changed in comments:
1281
+ if (
1282
+ allow
1283
+ and ignorable
1284
+ and ignore.valid
1285
+ and ignore.token == raw.rule.id
1286
+ and not changed
1287
+ and not inserted
1288
+ ):
1289
+ honoured[id(raw)] = ignore.reason or ""
1290
+ break
1291
+ if id(raw) in honoured:
1292
+ continue
1293
+ for ignore, changed in comments:
1294
+ if ignore.token != raw.rule.id and "*" not in ignore.token:
1295
+ continue
1296
+ if not ignore.valid:
1297
+ why = "malformed"
1298
+ elif not ignorable:
1299
+ why = "not-ignorable"
1300
+ elif changed:
1301
+ why = "added-by-change"
1302
+ elif inserted:
1303
+ why = "covers-added-line"
1304
+ else:
1305
+ why = "inline-ignores-disabled"
1306
+ self.proposed.append(
1307
+ _Proposal(
1308
+ ignore,
1309
+ changed,
1310
+ raw.file.change.path,
1311
+ raw.rule.id,
1312
+ raw.line,
1313
+ raw.severity,
1314
+ why,
1315
+ )
1316
+ )
1317
+ return honoured
1318
+
1319
+ def suppression_findings(self) -> list[_Raw]:
1320
+ review = self.review
1321
+ entry = review.registry.get(_SUPPRESSION_RULE)
1322
+ if entry is None or not review.policy.enabled(entry.meta):
1323
+ return []
1324
+ added: list[_Raw] = []
1325
+ candidates = sorted(
1326
+ (p for p in self.proposed if p.changed),
1327
+ key=lambda p: (-p.severity.rank, p.path, p.ignore.line),
1328
+ )
1329
+ for p in candidates:
1330
+ fs = review.by_path[p.path]
1331
+ changed = fs.change.added_lines
1332
+ span = range(p.ignore.first_line, p.ignore.line + 1)
1333
+ line = next((n for n in span if n in changed), p.target_line)
1334
+ message = f"Inline ignore for {p.target_rule} added by this change"
1335
+ blocking = _blocks(p.severity, self.fail_on)
1336
+ raw = _Raw(
1337
+ entry, fs, Side.NEW, line, None, None, message, p.target_rule, (), fs.ctx.lines
1338
+ )
1339
+ raw.severity, raw.blocking = p.severity, blocking
1340
+ added.append(raw)
1341
+ return added
1342
+
1343
+ def prepare(self, raw: _Raw, secrets: Sequence[str]) -> _Prepared:
1344
+ line_text = raw.text()
1345
+ snippet: str | None = None
1346
+ text = ""
1347
+ if line_text is not None:
1348
+ redacted = redact.redact_line(line_text, raw.line or 0, raw.spans, secrets)
1349
+ text = normalize(redacted)
1350
+ snippet = redacted
1351
+ if len(snippet) > MAX_SNIPPET_CHARS:
1352
+ snippet = snippet[:MAX_SNIPPET_CHARS] + "…"
1353
+ message = redact.redact_text(raw.message or raw.rule.meta.title, secrets) or ""
1354
+ evidence = redact.redact_text(raw.evidence, secrets)
1355
+ return _Prepared(raw, snippet, message, evidence, text)
1356
+
1357
+ def finish(self, secrets: Sequence[str]) -> tuple[list[Finding], list[Suppressed]]:
1358
+ review = self.review
1359
+ raws: list[_Raw] = []
1360
+ seen: dict[tuple[str, str, Side, int | None], int] = {}
1361
+ for raw in review.raws:
1362
+ raw.severity = review.effective(raw)
1363
+ raw.blocking = _blocks(raw.severity, self.fail_on)
1364
+ at = seen.get(raw.key)
1365
+ if at is None:
1366
+ seen[raw.key] = len(raws)
1367
+ raws.append(raw)
1368
+ elif raw.severity > raws[at].severity:
1369
+ raws[at] = raw
1370
+ config: dict[int, str] = {}
1371
+ for raw in raws:
1372
+ reason = self.config_reason(raw)
1373
+ if reason is not None:
1374
+ config[id(raw)] = reason
1375
+ honoured = self.inline([r for r in raws if id(r) not in config])
1376
+ for raw in self.suppression_findings():
1377
+ at = seen.get(raw.key)
1378
+ if at is not None:
1379
+ # The rule may report the same comment itself (as a warning); the
1380
+ # proposal carries the ignored finding's severity, so the higher wins.
1381
+ current = raws[at]
1382
+ if raw.severity <= current.severity:
1383
+ continue
1384
+ config.pop(id(current), None)
1385
+ honoured.pop(id(current), None)
1386
+ raws[at] = raw
1387
+ else:
1388
+ seen[raw.key] = len(raws)
1389
+ raws.append(raw)
1390
+ reason = self.config_reason(raw)
1391
+ if reason is not None:
1392
+ config[id(raw)] = reason
1393
+ prepared = [self.prepare(raw, secrets) for raw in raws]
1394
+ for item in prepared:
1395
+ if id(item.raw) in config:
1396
+ item.suppressed = (config[id(item.raw)], "config")
1397
+ elif id(item.raw) in honoured:
1398
+ item.suppressed = (honoured[id(item.raw)], "inline")
1399
+ prepared.sort(key=lambda p: p.raw.sort_key())
1400
+ occurrences: defaultdict[tuple[str, str, str], int] = defaultdict(int)
1401
+ for item in prepared:
1402
+ raw = item.raw
1403
+ ident = (raw.rule.id, raw.file.change.path, item.text)
1404
+ item.fingerprint = _fingerprint(
1405
+ raw.rule.id, raw.file.change.path, raw.side.value, item.text, occurrences[ident]
1406
+ )
1407
+ occurrences[ident] += 1
1408
+ findings: list[Finding] = []
1409
+ suppressed: list[Suppressed] = []
1410
+ for item in prepared:
1411
+ finding = self.finding(item)
1412
+ if item.suppressed is None:
1413
+ findings.append(finding)
1414
+ else:
1415
+ reason = redact.redact_text(item.suppressed[0], secrets) or ""
1416
+ suppressed.append(Suppressed(finding, reason, item.suppressed[1]))
1417
+ return findings, suppressed
1418
+
1419
+ def finding(self, item: _Prepared) -> Finding:
1420
+ raw = item.raw
1421
+ meta = raw.rule.meta
1422
+ return Finding(
1423
+ fingerprint=item.fingerprint,
1424
+ rule=meta.id,
1425
+ severity=raw.severity,
1426
+ blocking=raw.blocking,
1427
+ path=raw.file.change.path,
1428
+ old_path=raw.file.change.old_path,
1429
+ side=raw.side,
1430
+ line=raw.line,
1431
+ end_line=raw.end_line,
1432
+ column=raw.column,
1433
+ title=meta.title,
1434
+ message=item.message,
1435
+ hint=meta.hint,
1436
+ snippet=item.snippet,
1437
+ evidence=item.evidence,
1438
+ )
1439
+
1440
+ def proposals(self, secrets: Sequence[str]) -> tuple[ProposedIgnore, ...]:
1441
+ by_path = self.review.by_path
1442
+ items = [
1443
+ ProposedIgnore(
1444
+ path=p.path,
1445
+ line=p.ignore.line,
1446
+ rule=redact.redact_text(p.ignore.token, secrets) or "",
1447
+ reason=redact.redact_text(p.ignore.reason, secrets),
1448
+ target_rule=p.target_rule,
1449
+ target_line=p.target_line,
1450
+ severity=p.severity,
1451
+ why=p.why,
1452
+ comment_changed=p.changed,
1453
+ )
1454
+ for p in self.proposed
1455
+ ]
1456
+ items.sort(key=lambda p: (by_path[p.path].index, p.target_line, p.target_rule, p.line))
1457
+ return tuple(items)
1458
+
1459
+
1460
+ def _cap(findings: list[Finding], what: str, review: _Review) -> tuple[Finding, ...]:
1461
+ if len(findings) <= MAX_FINDINGS:
1462
+ return tuple(findings)
1463
+ keep = {id(f) for f in [f for f in findings if f.blocking][:MAX_FINDINGS]}
1464
+ for f in findings:
1465
+ if len(keep) >= MAX_FINDINGS:
1466
+ break
1467
+ keep.add(id(f))
1468
+ review.issue(
1469
+ "finding-cap",
1470
+ f"{len(findings) - MAX_FINDINGS} {what} beyond the {MAX_FINDINGS}-finding cap "
1471
+ "were not reported",
1472
+ incomplete=False,
1473
+ )
1474
+ return tuple(f for f in findings if id(f) in keep)
1475
+
1476
+
1477
+ def review(
1478
+ changeset: Changeset,
1479
+ *,
1480
+ registry: Registry,
1481
+ policy: Policy,
1482
+ rule_budget_s: float = DEFAULT_RULE_BUDGET_S,
1483
+ total_budget_s: float = DEFAULT_TOTAL_BUDGET_S,
1484
+ clock: Callable[[], float] = time.perf_counter,
1485
+ ) -> EngineResult:
1486
+ """Run every enabled rule of ``registry`` over ``changeset`` (see the module docstring).
1487
+
1488
+ ``clock`` measures rule time for the budgets (tests inject a fake one);
1489
+ the ``SIGALRM`` interruption uses real time. A caller that must bound the
1490
+ wall-clock time in every case enforces :func:`hard_deadline_s`.
1491
+ """
1492
+ with _Alarm() as alarm:
1493
+ return _run(changeset, registry, policy, rule_budget_s, total_budget_s, clock, alarm)
1494
+
1495
+
1496
+ def _run(
1497
+ changeset: Changeset,
1498
+ registry: Registry,
1499
+ policy: Policy,
1500
+ rule_budget_s: float,
1501
+ total_budget_s: float,
1502
+ clock: Callable[[], float],
1503
+ alarm: _Alarm,
1504
+ ) -> EngineResult:
1505
+ run = _Review(changeset, registry, policy, rule_budget_s, total_budget_s, clock, alarm)
1506
+ fail_on = policy.fail_on
1507
+ if fail_on not in _FAIL_ON:
1508
+ run.issue("policy", "policy has an unknown fail_on value; using 'error'")
1509
+ fail_on = "error"
1510
+ for message in changeset.issues:
1511
+ run.issue("changeset", message)
1512
+ rules: list[Rule] = []
1513
+ severities = run.severities
1514
+ for rule in registry.all():
1515
+ if not policy.enabled(rule.meta):
1516
+ continue
1517
+ rules.append(rule)
1518
+ severity = policy.severity(rule.meta)
1519
+ if not isinstance(severity, Severity):
1520
+ run.issue("policy", "policy returned an invalid severity", rule=rule.id)
1521
+ severity = rule.meta.severity
1522
+ severities[rule.id] = severity
1523
+ run.build_files()
1524
+ run.run_files(rules)
1525
+ run.run_change(rules)
1526
+ secrets = sorted(run.secrets, key=lambda s: (-len(s), s))
1527
+ finisher = _Finisher(run, fail_on)
1528
+ findings, suppressed = finisher.finish(secrets)
1529
+ capped = _cap(findings, "findings", run)
1530
+ if len(suppressed) > MAX_FINDINGS:
1531
+ run.issue(
1532
+ "finding-cap",
1533
+ f"{len(suppressed) - MAX_FINDINGS} suppressed findings beyond the "
1534
+ f"{MAX_FINDINGS}-finding cap were not reported",
1535
+ incomplete=False,
1536
+ )
1537
+ coverage = tuple(
1538
+ Coverage(
1539
+ fs.change.path,
1540
+ fs.status,
1541
+ ()
1542
+ if fs.status is CoverageStatus.CHECKED
1543
+ else tuple(redact.redact_text(r, secrets) or "" for r in fs.reasons),
1544
+ )
1545
+ for fs in run.files
1546
+ )
1547
+ if any(f.blocking for f in capped):
1548
+ verdict = Verdict.VETOED
1549
+ elif any(c.incomplete for c in coverage) or any(i.incomplete for i in run.issues):
1550
+ verdict = Verdict.INCOMPLETE
1551
+ else:
1552
+ verdict = Verdict.CLEAR
1553
+ notes = tuple(
1554
+ dataclasses.replace(n, reason=redact.redact_text(n.reason, secrets) or "")
1555
+ for _, n in sorted(finisher.notes.items())
1556
+ )
1557
+ return EngineResult(
1558
+ verdict=verdict,
1559
+ fail_on=fail_on, # type: ignore[arg-type]
1560
+ findings=capped,
1561
+ suppressed=tuple(suppressed[:MAX_FINDINGS]),
1562
+ proposed_ignores=finisher.proposals(secrets),
1563
+ coverage=coverage,
1564
+ issues=tuple(run.issues),
1565
+ config_notes=notes,
1566
+ files=len(changeset.files),
1567
+ rules_enabled=len(rules),
1568
+ rules_run=len(run.ran),
1569
+ duration_s=max(0.0, clock() - run.start),
1570
+ )