codeveto 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/rules/agent.py
ADDED
|
@@ -0,0 +1,2972 @@
|
|
|
1
|
+
"""Agent pack (SPEC 6.1): changes that steer, blind or reconfigure reviewers and agents.
|
|
2
|
+
|
|
3
|
+
The pack has four groups of rules:
|
|
4
|
+
|
|
5
|
+
- Text aimed at AI reviewers and agents: ``reviewer-directive``,
|
|
6
|
+
``injection-phrase``, ``hidden-unicode``, ``confusable-identifier`` and
|
|
7
|
+
``encoded-payload``. They read comments, string literals and prose (Markdown
|
|
8
|
+
HTML comments and collapsed ``<details>`` count as hidden text) through a
|
|
9
|
+
normalized view that drops invisible characters and maps look-alike letters
|
|
10
|
+
to ASCII, so a zero-width character inside a word does not hide it.
|
|
11
|
+
- Agent configuration: ``instructions-changed``, ``tool-config-changed`` and
|
|
12
|
+
``auto-approve-enabled`` (settings and command-line flags that let an agent
|
|
13
|
+
act without a human approving each step).
|
|
14
|
+
- The reviewer itself: ``reviewer-config-changed``,
|
|
15
|
+
``reviewer-config-weakened`` (through :func:`codeveto.config.weakened`) and
|
|
16
|
+
``codeveto-workflow-changed`` (CodeVeto steps in workflows, actions, hooks
|
|
17
|
+
and templates).
|
|
18
|
+
- What reviewers and tools are shown: ``codeowners-changed``,
|
|
19
|
+
``gitattributes-changed``, ``ignore-rules-changed`` and
|
|
20
|
+
``suppression-added``.
|
|
21
|
+
|
|
22
|
+
Every example of a hidden character or an instruction in this module is
|
|
23
|
+
built from fragments or ``\\u`` escapes, so the module does not trip its own
|
|
24
|
+
rules.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import ast
|
|
30
|
+
import binascii
|
|
31
|
+
import bisect
|
|
32
|
+
import json
|
|
33
|
+
import re
|
|
34
|
+
import unicodedata
|
|
35
|
+
from collections.abc import Iterable, Iterator, Sequence
|
|
36
|
+
from dataclasses import dataclass, field
|
|
37
|
+
|
|
38
|
+
from codeveto import config as _config
|
|
39
|
+
from codeveto import lexers as _lexers
|
|
40
|
+
from codeveto.globs import Glob, compile_glob
|
|
41
|
+
from codeveto.languages import CODE_LANGUAGES, CONFIG_LANGUAGES, classify
|
|
42
|
+
from codeveto.lexers import CommentSpan, LineIndex, StringSpan
|
|
43
|
+
from codeveto.model import FileStatus, Side
|
|
44
|
+
from codeveto.rules.base import FileContext, Hit, LineText, PartialCoverage, Severity, rule
|
|
45
|
+
from codeveto.worktree import FLAG_IGNORED_LOCALLY
|
|
46
|
+
from codeveto.yamlish import YamlMap, YamlNode, YamlResult, YamlScalar, YamlSeq, to_python
|
|
47
|
+
|
|
48
|
+
WARNING = Severity.WARNING
|
|
49
|
+
NOTE = Severity.NOTE
|
|
50
|
+
|
|
51
|
+
# --- Shared helpers -------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _globs(*patterns: str) -> tuple[Glob, ...]:
|
|
55
|
+
return tuple(compile_glob(p) for p in patterns)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _matches(globs: Sequence[Glob], path: str | None) -> bool:
|
|
59
|
+
return path is not None and any(g.match(path) for g in globs)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _either_path(ctx: FileContext, globs: Sequence[Glob]) -> bool:
|
|
63
|
+
return _matches(globs, ctx.path) or _matches(globs, ctx.old_path)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _anchors(ctx: FileContext) -> list[int]:
|
|
67
|
+
"""New-side lines the engine accepts as anchors: added lines and deletion points."""
|
|
68
|
+
return sorted(set(ctx.added_lines) | set(ctx.deletion_points))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _file_level_ok(ctx: FileContext) -> bool:
|
|
72
|
+
return (
|
|
73
|
+
ctx.change.status
|
|
74
|
+
in (
|
|
75
|
+
FileStatus.ADDED,
|
|
76
|
+
FileStatus.DELETED,
|
|
77
|
+
FileStatus.RENAMED,
|
|
78
|
+
FileStatus.TYPE_CHANGED,
|
|
79
|
+
)
|
|
80
|
+
or ctx.old_mode != ctx.new_mode
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _change_hit(
|
|
85
|
+
ctx: FileContext, message: str, evidence: str | None = None, severity: Severity | None = None
|
|
86
|
+
) -> Hit | None:
|
|
87
|
+
"""One hit for "this file changed": file-level for additions and deletions,
|
|
88
|
+
else the first changed line (``None`` when there is nothing to anchor)."""
|
|
89
|
+
status = ctx.change.status
|
|
90
|
+
if status in (FileStatus.ADDED, FileStatus.DELETED) or ctx.new_text is None:
|
|
91
|
+
return Hit(None, message=message, evidence=evidence, severity=severity)
|
|
92
|
+
anchors = _anchors(ctx)
|
|
93
|
+
if anchors:
|
|
94
|
+
return Hit(anchors[0], message=message, evidence=evidence, severity=severity)
|
|
95
|
+
if _file_level_ok(ctx):
|
|
96
|
+
return Hit(None, message=message, evidence=evidence, severity=severity)
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _first_anchor_from(anchors: list[int], line: int) -> int | None:
|
|
101
|
+
i = bisect.bisect_left(anchors, line)
|
|
102
|
+
if i < len(anchors):
|
|
103
|
+
return anchors[i]
|
|
104
|
+
return anchors[-1] if anchors else None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _short(text: str, limit: int = 120) -> str:
|
|
108
|
+
text = " ".join(text.split())
|
|
109
|
+
return text if len(text) <= limit else text[: limit - 3] + "..."
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# --- Look-alike letters and invisible characters -------------------------------------
|
|
113
|
+
|
|
114
|
+
# Letters that render like ASCII letters in common fonts (a subset of Unicode
|
|
115
|
+
# confusables: Cyrillic, Greek, Armenian and Latin look-alikes).
|
|
116
|
+
_CONFUSABLE: dict[str, str] = {
|
|
117
|
+
# Cyrillic lower case
|
|
118
|
+
"\u0430": "a",
|
|
119
|
+
"\u0435": "e",
|
|
120
|
+
"\u043e": "o",
|
|
121
|
+
"\u0440": "p",
|
|
122
|
+
"\u0441": "c",
|
|
123
|
+
"\u0443": "y",
|
|
124
|
+
"\u0445": "x",
|
|
125
|
+
"\u0455": "s",
|
|
126
|
+
"\u0456": "i",
|
|
127
|
+
"\u0458": "j",
|
|
128
|
+
"\u04bb": "h",
|
|
129
|
+
"\u0501": "d",
|
|
130
|
+
"\u051b": "q",
|
|
131
|
+
"\u051d": "w",
|
|
132
|
+
"\u04cf": "l",
|
|
133
|
+
"\u04af": "y",
|
|
134
|
+
# Cyrillic upper case
|
|
135
|
+
"\u0410": "A",
|
|
136
|
+
"\u0412": "B",
|
|
137
|
+
"\u0415": "E",
|
|
138
|
+
"\u041a": "K",
|
|
139
|
+
"\u041c": "M",
|
|
140
|
+
"\u041d": "H",
|
|
141
|
+
"\u041e": "O",
|
|
142
|
+
"\u0420": "P",
|
|
143
|
+
"\u0421": "C",
|
|
144
|
+
"\u0422": "T",
|
|
145
|
+
"\u0425": "X",
|
|
146
|
+
"\u0405": "S",
|
|
147
|
+
"\u0406": "I",
|
|
148
|
+
"\u0408": "J",
|
|
149
|
+
"\u04ae": "Y",
|
|
150
|
+
"\u04c0": "I",
|
|
151
|
+
"\u051a": "Q",
|
|
152
|
+
"\u051c": "W",
|
|
153
|
+
# Greek
|
|
154
|
+
"\u03b1": "a",
|
|
155
|
+
"\u03b9": "i",
|
|
156
|
+
"\u03ba": "k",
|
|
157
|
+
"\u03bd": "v",
|
|
158
|
+
"\u03bf": "o",
|
|
159
|
+
"\u03c1": "p",
|
|
160
|
+
"\u03c5": "u",
|
|
161
|
+
"\u03c7": "x",
|
|
162
|
+
"\u0391": "A",
|
|
163
|
+
"\u0392": "B",
|
|
164
|
+
"\u0395": "E",
|
|
165
|
+
"\u0396": "Z",
|
|
166
|
+
"\u0397": "H",
|
|
167
|
+
"\u0399": "I",
|
|
168
|
+
"\u039a": "K",
|
|
169
|
+
"\u039c": "M",
|
|
170
|
+
"\u039d": "N",
|
|
171
|
+
"\u039f": "O",
|
|
172
|
+
"\u03a1": "P",
|
|
173
|
+
"\u03a4": "T",
|
|
174
|
+
"\u03a5": "Y",
|
|
175
|
+
"\u03a7": "X",
|
|
176
|
+
# Armenian
|
|
177
|
+
"\u0570": "h",
|
|
178
|
+
"\u0578": "n",
|
|
179
|
+
"\u057d": "u",
|
|
180
|
+
"\u0585": "o",
|
|
181
|
+
# Latin look-alikes
|
|
182
|
+
"\u0251": "a",
|
|
183
|
+
"\u0261": "g",
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
_HANGUL_FILLERS = frozenset({0x115F, 0x1160, 0x3164, 0xFFA0})
|
|
187
|
+
"""Hangul filler letters: category Lo, yet they render as nothing."""
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _is_variation_selector(cp: int) -> bool:
|
|
191
|
+
return 0xFE00 <= cp <= 0xFE0F or 0xE0100 <= cp <= 0xE01EF
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _invisible(ch: str) -> bool:
|
|
195
|
+
"""A character that renders as nothing: format (Cf), variation selector, filler."""
|
|
196
|
+
cp = ord(ch)
|
|
197
|
+
if cp < 0xAD:
|
|
198
|
+
return False
|
|
199
|
+
return (
|
|
200
|
+
unicodedata.category(ch) == "Cf"
|
|
201
|
+
or _is_variation_selector(cp)
|
|
202
|
+
or cp in _HANGUL_FILLERS
|
|
203
|
+
or cp == 0x034F
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _ascii_look(ch: str) -> str:
|
|
208
|
+
"""``ch`` as the ASCII it looks like (look-alikes, fullwidth and math letters)."""
|
|
209
|
+
mapped = _CONFUSABLE.get(ch)
|
|
210
|
+
if mapped is not None:
|
|
211
|
+
return mapped
|
|
212
|
+
cp = ord(ch)
|
|
213
|
+
if 0xFF01 <= cp <= 0xFF5E or 0x1D400 <= cp <= 0x1D7FF or 0xFB00 <= cp <= 0xFB06:
|
|
214
|
+
return unicodedata.normalize("NFKC", ch)
|
|
215
|
+
return ch
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
_LEADERS = frozenset("#/*;>!-|")
|
|
219
|
+
_EMPHASIS = frozenset("*~")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
_ASCII_RUN = re.compile(r"[^\s_*~]+|[ \t\f\v_]*\r?\n[\s#/*;>!|-]*|[\s_]+|[*~]+")
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _normalize_ascii(raw: str, base: int) -> tuple[str, list[int]]:
|
|
226
|
+
""":func:`_normalize` for ASCII text, a run at a time."""
|
|
227
|
+
out: list[str] = []
|
|
228
|
+
where: list[int] = []
|
|
229
|
+
space = True
|
|
230
|
+
for m in _ASCII_RUN.finditer(raw):
|
|
231
|
+
run = m.group()
|
|
232
|
+
first = run[0]
|
|
233
|
+
if first in "*~":
|
|
234
|
+
continue
|
|
235
|
+
if first.isspace() or first == "_":
|
|
236
|
+
if not space:
|
|
237
|
+
out.append(" ")
|
|
238
|
+
where.append(base + m.start())
|
|
239
|
+
space = True
|
|
240
|
+
continue
|
|
241
|
+
out.append(run.lower())
|
|
242
|
+
where.extend(range(base + m.start(), base + m.end()))
|
|
243
|
+
space = False
|
|
244
|
+
return "".join(out), where
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _normalize(text: str, start: int, end: int) -> tuple[str, list[int]]:
|
|
248
|
+
"""Lower-cased text of ``text[start:end]`` for phrase matching, with an offset map.
|
|
249
|
+
|
|
250
|
+
Invisible characters are dropped, look-alike letters become ASCII,
|
|
251
|
+
whitespace runs (and a line break with the comment markers and
|
|
252
|
+
indentation after it) become one space, ``_`` becomes a space and the
|
|
253
|
+
Markdown emphasis markers ``*`` and ``~`` disappear. ``where[k]`` is the
|
|
254
|
+
offset in ``text`` of normalized character ``k``.
|
|
255
|
+
"""
|
|
256
|
+
raw = text[start:end]
|
|
257
|
+
if raw.isascii():
|
|
258
|
+
return _normalize_ascii(raw, start)
|
|
259
|
+
out: list[str] = []
|
|
260
|
+
where: list[int] = []
|
|
261
|
+
space = True
|
|
262
|
+
i = start
|
|
263
|
+
while i < end:
|
|
264
|
+
ch = text[i]
|
|
265
|
+
if ch in "\r\n":
|
|
266
|
+
j = i + 1
|
|
267
|
+
budget = 24
|
|
268
|
+
while j < end and budget and (text[j] in " \t\r\n" or text[j] in _LEADERS):
|
|
269
|
+
j += 1
|
|
270
|
+
budget -= 1
|
|
271
|
+
if not space:
|
|
272
|
+
out.append(" ")
|
|
273
|
+
where.append(i)
|
|
274
|
+
space = True
|
|
275
|
+
i = j
|
|
276
|
+
continue
|
|
277
|
+
cp = ord(ch)
|
|
278
|
+
if ch in " \t\f\v" or ch == "_" or (cp > 127 and ch.isspace()):
|
|
279
|
+
if not space:
|
|
280
|
+
out.append(" ")
|
|
281
|
+
where.append(i)
|
|
282
|
+
space = True
|
|
283
|
+
elif ch in _EMPHASIS:
|
|
284
|
+
pass
|
|
285
|
+
elif cp > 127:
|
|
286
|
+
if not _invisible(ch):
|
|
287
|
+
for c in _ascii_look(ch).lower():
|
|
288
|
+
out.append(c)
|
|
289
|
+
where.append(i)
|
|
290
|
+
space = False
|
|
291
|
+
else:
|
|
292
|
+
out.append(ch.lower())
|
|
293
|
+
where.append(i)
|
|
294
|
+
space = False
|
|
295
|
+
i += 1
|
|
296
|
+
return "".join(out), where
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
# --- Text regions: hidden (comments), strings and prose --------------------------------
|
|
300
|
+
|
|
301
|
+
_HIDDEN = "hidden"
|
|
302
|
+
_STRING = "string"
|
|
303
|
+
_PROSE = "prose"
|
|
304
|
+
_QUOTED = "quoted" # an example block inside a docstring: shown as an example, not an order
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
@dataclass(frozen=True, slots=True)
|
|
308
|
+
class _Region:
|
|
309
|
+
start: int
|
|
310
|
+
end: int
|
|
311
|
+
kind: str
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _merge_regions(text: str, regions: list[_Region]) -> list[_Region]:
|
|
315
|
+
"""Sort, and join same-kind regions split only by one line break (and comment markers).
|
|
316
|
+
|
|
317
|
+
Consecutive ``#`` or ``//`` comment lines, and the lines of one Markdown
|
|
318
|
+
paragraph, then read as one text, so a sentence broken over two lines
|
|
319
|
+
still matches.
|
|
320
|
+
"""
|
|
321
|
+
regions.sort(key=lambda r: (r.start, r.end))
|
|
322
|
+
merged: list[_Region] = []
|
|
323
|
+
for region in regions:
|
|
324
|
+
if region.end <= region.start:
|
|
325
|
+
continue
|
|
326
|
+
if merged:
|
|
327
|
+
last = merged[-1]
|
|
328
|
+
if region.start < last.end:
|
|
329
|
+
if region.end > last.end:
|
|
330
|
+
merged[-1] = _Region(last.start, region.end, last.kind)
|
|
331
|
+
continue
|
|
332
|
+
gap = text[last.end : region.start]
|
|
333
|
+
if (
|
|
334
|
+
region.kind == last.kind
|
|
335
|
+
and len(gap) <= 40
|
|
336
|
+
and gap.count("\n") <= 1
|
|
337
|
+
and not gap.strip(" \t\r\n#/;-!*>")
|
|
338
|
+
):
|
|
339
|
+
merged[-1] = _Region(last.start, region.end, last.kind)
|
|
340
|
+
continue
|
|
341
|
+
merged.append(region)
|
|
342
|
+
return merged
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _ast_offset(lines: tuple[str, ...], index: LineIndex, line: int, col: int) -> int:
|
|
346
|
+
row = lines[line - 1] if line - 1 < len(lines) else ""
|
|
347
|
+
chars = len(row.encode("utf-8", "surrogatepass")[:col].decode("utf-8", "ignore"))
|
|
348
|
+
return index.line_start(line) + chars
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _docstring_ranges(ctx: FileContext) -> list[tuple[int, int]]:
|
|
352
|
+
"""Offsets of Python string-only statements (docstrings and their kin)."""
|
|
353
|
+
tree = ctx.python_ast
|
|
354
|
+
if tree is None:
|
|
355
|
+
return []
|
|
356
|
+
lines = ctx.lines
|
|
357
|
+
index = ctx.line_index
|
|
358
|
+
found: list[tuple[int, int]] = []
|
|
359
|
+
for node in ast.walk(tree):
|
|
360
|
+
if (
|
|
361
|
+
isinstance(node, ast.Expr)
|
|
362
|
+
and isinstance(node.value, ast.Constant)
|
|
363
|
+
and isinstance(node.value.value, str)
|
|
364
|
+
and node.end_lineno is not None
|
|
365
|
+
and node.end_col_offset is not None
|
|
366
|
+
):
|
|
367
|
+
found.append(
|
|
368
|
+
(
|
|
369
|
+
_ast_offset(lines, index, node.lineno, node.col_offset),
|
|
370
|
+
_ast_offset(lines, index, node.end_lineno, node.end_col_offset),
|
|
371
|
+
)
|
|
372
|
+
)
|
|
373
|
+
found.sort()
|
|
374
|
+
return found
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _alone_on_line(text: str, span: StringSpan) -> bool:
|
|
378
|
+
"""Heuristic docstring test when the AST is unavailable: nothing else on its lines."""
|
|
379
|
+
line_start = text.rfind("\n", 0, span.start) + 1
|
|
380
|
+
if text[line_start : span.start].strip():
|
|
381
|
+
return False
|
|
382
|
+
line_end = text.find("\n", span.end)
|
|
383
|
+
rest = text[span.end : len(text) if line_end < 0 else line_end].strip()
|
|
384
|
+
if rest and not rest.startswith("#"):
|
|
385
|
+
return False
|
|
386
|
+
before = text[max(0, line_start - 200) : line_start].rstrip()
|
|
387
|
+
return not before or before[-1] not in "([{,=+-*/%&|^<>~"
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
_OPEN_ATTRIBUTE = re.compile(r"(?<![\w-])open(?![\w-])")
|
|
391
|
+
_MARKUP_SPECIAL = re.compile(r"<!--|</?details\b|<summary\b|`{1,8}", re.IGNORECASE)
|
|
392
|
+
_FENCE = re.compile(r" {0,3}(`{3,}|~{3,})")
|
|
393
|
+
_LINK_COMMENT = re.compile(r" {0,3}\[[^\]\n]{1,60}\]:[ \t]{0,10}(?:<>|#)(?=[ \t(\"'])")
|
|
394
|
+
_RST_COMMENT = re.compile(r"\.\.(?:[ \t]|$)(?![ \t]*(?:[\w-]{1,40}::|_|\[|\|))")
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _markup_regions(text: str, *, fences: bool, rst: bool, base: int = 0) -> list[_Region]:
|
|
398
|
+
"""Hidden and prose regions of Markdown, HTML or plain text.
|
|
399
|
+
|
|
400
|
+
Hidden: HTML comments, the body of a collapsed ``<details>`` element (its
|
|
401
|
+
``<summary>`` stays visible), Markdown link-reference comments
|
|
402
|
+
(``[//]: # (...)``) and reStructuredText comments. Fenced code blocks and
|
|
403
|
+
inline code are quoted examples and belong to no region.
|
|
404
|
+
"""
|
|
405
|
+
regions: list[_Region] = []
|
|
406
|
+
pos = 0
|
|
407
|
+
length = len(text)
|
|
408
|
+
fence: tuple[str, int] | None = None
|
|
409
|
+
in_comment = False
|
|
410
|
+
collapsed: list[bool] = []
|
|
411
|
+
hidden_depth = 0
|
|
412
|
+
|
|
413
|
+
def add(a: int, b: int, kind: str) -> None:
|
|
414
|
+
if b > a:
|
|
415
|
+
regions.append(_Region(base + a, base + b, kind))
|
|
416
|
+
|
|
417
|
+
while pos < length:
|
|
418
|
+
end = text.find("\n", pos)
|
|
419
|
+
end = length if end < 0 else end
|
|
420
|
+
line = text[pos:end]
|
|
421
|
+
if fence is not None and not in_comment:
|
|
422
|
+
stripped = line.strip()
|
|
423
|
+
if stripped.startswith(fence[0] * fence[1]) and not stripped.lstrip(fence[0]):
|
|
424
|
+
fence = None
|
|
425
|
+
pos = end + 1
|
|
426
|
+
continue
|
|
427
|
+
if not in_comment and fences:
|
|
428
|
+
m = _FENCE.match(line)
|
|
429
|
+
if m is not None:
|
|
430
|
+
run = m.group(1)
|
|
431
|
+
info = line[m.end() :]
|
|
432
|
+
if run[0] != "`" or "`" not in info:
|
|
433
|
+
fence = (run[0], len(run))
|
|
434
|
+
pos = end + 1
|
|
435
|
+
continue
|
|
436
|
+
if not in_comment and rst and _RST_COMMENT.match(line):
|
|
437
|
+
add(pos, end, _HIDDEN)
|
|
438
|
+
pos = end + 1
|
|
439
|
+
continue
|
|
440
|
+
if not in_comment and fences:
|
|
441
|
+
m = _LINK_COMMENT.match(line)
|
|
442
|
+
if m is not None:
|
|
443
|
+
add(pos + m.end(), end, _HIDDEN)
|
|
444
|
+
pos = end + 1
|
|
445
|
+
continue
|
|
446
|
+
i = 0
|
|
447
|
+
while i < len(line):
|
|
448
|
+
if in_comment:
|
|
449
|
+
close = line.find("-->", i)
|
|
450
|
+
if close < 0:
|
|
451
|
+
add(pos + i, end, _HIDDEN)
|
|
452
|
+
i = len(line)
|
|
453
|
+
break
|
|
454
|
+
add(pos + i, pos + close, _HIDDEN)
|
|
455
|
+
in_comment = False
|
|
456
|
+
i = close + 3
|
|
457
|
+
continue
|
|
458
|
+
m = _MARKUP_SPECIAL.search(line, i)
|
|
459
|
+
stop = m.start() if m is not None else len(line)
|
|
460
|
+
add(pos + i, pos + stop, _HIDDEN if hidden_depth else _PROSE)
|
|
461
|
+
if m is None:
|
|
462
|
+
break
|
|
463
|
+
marker = m.group().lower()
|
|
464
|
+
if marker == "<!--":
|
|
465
|
+
in_comment = True
|
|
466
|
+
i = m.end()
|
|
467
|
+
elif marker == "<details":
|
|
468
|
+
close = line.find(">", m.end())
|
|
469
|
+
attrs = line[m.end() : close if close >= 0 else len(line)].lower()
|
|
470
|
+
is_collapsed = _OPEN_ATTRIBUTE.search(attrs) is None
|
|
471
|
+
collapsed.append(is_collapsed)
|
|
472
|
+
hidden_depth += is_collapsed
|
|
473
|
+
i = close + 1 if close >= 0 else len(line)
|
|
474
|
+
elif marker == "</details":
|
|
475
|
+
if collapsed:
|
|
476
|
+
hidden_depth -= collapsed.pop()
|
|
477
|
+
close = line.find(">", m.end())
|
|
478
|
+
i = close + 1 if close >= 0 else len(line)
|
|
479
|
+
elif marker == "<summary":
|
|
480
|
+
close = line.find(">", m.end())
|
|
481
|
+
body = close + 1 if close >= 0 else len(line)
|
|
482
|
+
done = line.lower().find("</summary", body)
|
|
483
|
+
stop = len(line) if done < 0 else done
|
|
484
|
+
outer = hidden_depth - (1 if collapsed and collapsed[-1] else 0)
|
|
485
|
+
add(pos + body, pos + stop, _HIDDEN if outer > 0 else _PROSE)
|
|
486
|
+
if done < 0:
|
|
487
|
+
i = len(line)
|
|
488
|
+
else:
|
|
489
|
+
close = line.find(">", done)
|
|
490
|
+
i = close + 1 if close >= 0 else len(line)
|
|
491
|
+
else: # a backtick run: inline code up to the same run, else literal text
|
|
492
|
+
run = m.group()
|
|
493
|
+
close = line.find(run, m.end())
|
|
494
|
+
while close >= 0 and line[close + len(run) : close + len(run) + 1] == "`":
|
|
495
|
+
close = line.find(run, close + len(run) + 1)
|
|
496
|
+
if close < 0:
|
|
497
|
+
add(pos + m.start(), pos + m.end(), _HIDDEN if hidden_depth else _PROSE)
|
|
498
|
+
i = m.end()
|
|
499
|
+
else:
|
|
500
|
+
i = close + len(run)
|
|
501
|
+
pos = end + 1
|
|
502
|
+
return regions
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _docstring_regions(text: str, start: int, end: int) -> Iterator[_Region]:
|
|
506
|
+
"""A docstring as hidden text, except its reST literal blocks and doctest lines.
|
|
507
|
+
|
|
508
|
+
Lines after one ending in ``::`` that are indented deeper, and ``>>>`` /
|
|
509
|
+
``...`` doctest lines, are examples (``_QUOTED``).
|
|
510
|
+
"""
|
|
511
|
+
pos = start
|
|
512
|
+
literal_indent: int | None = None
|
|
513
|
+
run_start, run_kind = start, _HIDDEN
|
|
514
|
+
while pos < end:
|
|
515
|
+
line_end = text.find("\n", pos, end)
|
|
516
|
+
line_end = end if line_end < 0 else line_end
|
|
517
|
+
line = text[pos:line_end]
|
|
518
|
+
stripped = line.strip()
|
|
519
|
+
indent = len(line) - len(line.lstrip())
|
|
520
|
+
if literal_indent is not None and stripped and indent <= literal_indent:
|
|
521
|
+
literal_indent = None
|
|
522
|
+
example = literal_indent is not None or stripped.startswith((">>> ", "... "))
|
|
523
|
+
kind = _QUOTED if example and stripped else (run_kind if not stripped else _HIDDEN)
|
|
524
|
+
if kind != run_kind:
|
|
525
|
+
if pos > run_start:
|
|
526
|
+
yield _Region(run_start, pos, run_kind)
|
|
527
|
+
run_start, run_kind = pos, kind
|
|
528
|
+
if literal_indent is None and stripped.endswith("::"):
|
|
529
|
+
literal_indent = indent
|
|
530
|
+
pos = line_end + 1
|
|
531
|
+
if end > run_start:
|
|
532
|
+
yield _Region(run_start, end, run_kind)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _gaps(start: int, end: int, taken: Iterable[tuple[int, int]]) -> Iterator[tuple[int, int]]:
|
|
536
|
+
cursor = start
|
|
537
|
+
for a, b in sorted(taken):
|
|
538
|
+
if a > cursor:
|
|
539
|
+
yield cursor, min(a, end)
|
|
540
|
+
cursor = max(cursor, b)
|
|
541
|
+
if cursor >= end:
|
|
542
|
+
return
|
|
543
|
+
if cursor < end:
|
|
544
|
+
yield cursor, end
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _regions(ctx: FileContext) -> list[_Region]:
|
|
548
|
+
"""Comment, string and prose regions of the new side, sorted and merged."""
|
|
549
|
+
text = ctx.new_text or ""
|
|
550
|
+
if not text:
|
|
551
|
+
return []
|
|
552
|
+
language = ctx.language
|
|
553
|
+
family = _lexers.family(language, ctx.path)
|
|
554
|
+
if language == "markdown":
|
|
555
|
+
return _merge_regions(text, _markup_regions(text, fences=True, rst=False))
|
|
556
|
+
if family == "none":
|
|
557
|
+
rst = ctx.path.endswith(".rst")
|
|
558
|
+
return _merge_regions(text, _markup_regions(text, fences=False, rst=rst))
|
|
559
|
+
result = ctx.spans
|
|
560
|
+
docstrings = _docstring_ranges(ctx) if language == "python" else []
|
|
561
|
+
starts = [d[0] for d in docstrings]
|
|
562
|
+
regions: list[_Region] = []
|
|
563
|
+
taken: list[tuple[int, int]] = []
|
|
564
|
+
for span in result.spans:
|
|
565
|
+
taken.append((span.start, span.end))
|
|
566
|
+
if isinstance(span, CommentSpan):
|
|
567
|
+
regions.append(_Region(span.content_start, span.content_end, _HIDDEN))
|
|
568
|
+
continue
|
|
569
|
+
kind = _STRING
|
|
570
|
+
if language == "python":
|
|
571
|
+
k = bisect.bisect_right(starts, span.start) - 1
|
|
572
|
+
in_docstring = bool(docstrings) and k >= 0 and span.start < docstrings[k][1]
|
|
573
|
+
if in_docstring or (ctx.python_ast is None and _alone_on_line(text, span)):
|
|
574
|
+
regions.extend(_docstring_regions(text, span.content_start, span.content_end))
|
|
575
|
+
continue
|
|
576
|
+
regions.append(_Region(span.content_start, span.content_end, kind))
|
|
577
|
+
if result.regions is not None:
|
|
578
|
+
# Vue and Svelte: the markup outside <script> is HTML.
|
|
579
|
+
for a, b in _gaps(0, len(text), result.regions):
|
|
580
|
+
regions.extend(_markup_regions(text[a:b], fences=False, rst=False, base=a))
|
|
581
|
+
elif language in CONFIG_LANGUAGES or result.partial:
|
|
582
|
+
# Plain YAML scalars and other values are text too; so is everything
|
|
583
|
+
# in a file the lexer could not read fully.
|
|
584
|
+
regions.extend(_Region(a, b, _STRING) for a, b in _gaps(0, len(text), taken))
|
|
585
|
+
return _merge_regions(text, regions)
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
# --- Directives to AI reviewers and injection phrases ----------------------------------
|
|
589
|
+
|
|
590
|
+
_REVIEWER_WHO = (
|
|
591
|
+
r"(?:coderabbit(?:ai)?|code rabbit|codeveto|code veto"
|
|
592
|
+
r"|(?:ai|automated|automatic|llm|gpt|bot|robot|machine|copilot|claude)(?: code)? review"
|
|
593
|
+
r"(?:ers?|ing (?:bots?|tools?|agents?|systems?)|s)?"
|
|
594
|
+
r"|code reviewers?|reviewer (?:bots?|agents?|ai)|review (?:bots?|tools?|agents?))"
|
|
595
|
+
)
|
|
596
|
+
_GENERIC_WHO = (
|
|
597
|
+
r"(?:ai|a\.i\.|llms?|large language models?|language models?|chatgpt"
|
|
598
|
+
r"|gpt(?:-?[0-9o](?:\.[0-9])?)?|claude(?: code)?|github copilot|copilot|gemini|codex"
|
|
599
|
+
r"|(?:ai |coding |code |llm |virtual )?assistants?"
|
|
600
|
+
r"|(?:ai|llm|coding|autonomous|software) agents?|ai (?:models?|tools?|systems?|bots?))"
|
|
601
|
+
)
|
|
602
|
+
_WHO = r"(?P<who>" + _REVIEWER_WHO + r"|" + _GENERIC_WHO + r")(?![\w-])"
|
|
603
|
+
_IS_REVIEWER = re.compile(_REVIEWER_WHO)
|
|
604
|
+
|
|
605
|
+
_LEAD = r"(?:^|(?<=[\s.!?;:(\[{>|,\"'`-]))"
|
|
606
|
+
_PREFIX = (
|
|
607
|
+
r"(?:(?:a |an |the |this |my )?(?:note|notes|message|instructions?|hint|reminder|memo"
|
|
608
|
+
r"|attention|important|warning|psa|request)(?: (?:to|for))?"
|
|
609
|
+
r" (?:the |any |all |every |our |an? )?"
|
|
610
|
+
r"|(?:dear|hey|hi|hello|attn) (?:the |any |all |every |our )?"
|
|
611
|
+
r"|(?:to|for) (?:any|all|every|each) "
|
|
612
|
+
r"|@ ?)"
|
|
613
|
+
)
|
|
614
|
+
_MODAL = (
|
|
615
|
+
r"(?:should|must|shall|is to|are to|needs? to|has to|have to|is expected to"
|
|
616
|
+
r"|are expected to|is instructed to|are instructed to|is required to|are required to"
|
|
617
|
+
r"|is asked to|are asked to)(?: not| never)?"
|
|
618
|
+
)
|
|
619
|
+
_PARTICIPLE = (
|
|
620
|
+
r"(?:reading|reviewing|processing|analy[sz]ing|scanning|checking|parsing|looking at|seeing)"
|
|
621
|
+
r" (?:this|these|the (?:code|file|change|changes|diff|pr|pull request|repository|repo))"
|
|
622
|
+
r"(?: (?:file|code|change|diff|pr|pull request|repository|repo))?"
|
|
623
|
+
)
|
|
624
|
+
_LABEL = r"(?:instructions?|notes?|directives?|guidance|rules|hints?|message|reminder)"
|
|
625
|
+
_TAIL = (
|
|
626
|
+
r"(?P<tail> ?[:,]| " + _LABEL + r" ?[:,]| " + _PARTICIPLE + r"(?: ?[:,]| " + _MODAL + r")?"
|
|
627
|
+
r"| " + _MODAL + r")"
|
|
628
|
+
)
|
|
629
|
+
|
|
630
|
+
_ADDRESS_PREFIXED = re.compile(_LEAD + _PREFIX + _WHO + _TAIL + r"?")
|
|
631
|
+
_ADDRESS_BARE = re.compile(_LEAD + _WHO + _TAIL)
|
|
632
|
+
_ADDRESS_IF = re.compile(
|
|
633
|
+
_LEAD + r"if you(?:'re| are) (?:an? |the |acting as an? |being )?" + _WHO
|
|
634
|
+
+ r"(?P<tail>(?: " + _PARTICIPLE + r")?(?: ?[:,])?)"
|
|
635
|
+
) # fmt: skip
|
|
636
|
+
_ADDRESS_IMPLICIT = re.compile(
|
|
637
|
+
_LEAD + r"(?:please )?(?:ignore|disregard|forget|override) (?:all |any )?(?:of )?"
|
|
638
|
+
r"(?:the |your |my )?(?:previous|prior|above|earlier|preceding|foregoing|original|system)"
|
|
639
|
+
r" (?:instructions?|prompts?|rules|directions?|guidelines)"
|
|
640
|
+
)
|
|
641
|
+
_AT_COMMAND = re.compile(
|
|
642
|
+
r"(?:^|(?<=[\s(\[{>,;:]))@ ?(?:coderabbit(?:ai)?|codeveto|copilot|claude|gemini-code-assist"
|
|
643
|
+
r"|sourcery-ai|greptile(?:ai|-apps)?|qodo(?:-merge)?|codium-?ai) "
|
|
644
|
+
r"(?:ignore|pause|approve|resolve|skip|stop|lgtm)(?![\w-])"
|
|
645
|
+
)
|
|
646
|
+
|
|
647
|
+
_PLEASE = re.compile(
|
|
648
|
+
r"(?:(?:please|kindly|just|simply|now|also|then|and|so|you can|you may|you should|you must"
|
|
649
|
+
r"|you need to|you are to|you will|be sure to|make sure to|remember to|always|immediately"
|
|
650
|
+
r"|quietly|silently),? ){0,4}"
|
|
651
|
+
)
|
|
652
|
+
_NEG = re.compile(
|
|
653
|
+
r"(?:do not|don't|dont|never|no need to|there is no need to|you (?:do not|don't) need to"
|
|
654
|
+
r"|need not|needn't|should not|shouldn't|must not|mustn't|avoid|refrain from|stop|cease) "
|
|
655
|
+
)
|
|
656
|
+
_NEG_VERB = re.compile(
|
|
657
|
+
r"(?:flag(?:ging)?|review(?:ing)?|re-review(?:ing)?|audit(?:ing)?|scan(?:ning)?"
|
|
658
|
+
r"|analy[sz](?:e|ing)|veto(?:ing)?|inspect(?:ing)?|examin(?:e|ing)|scrutini[sz](?:e|ing)"
|
|
659
|
+
r"|nitpick(?:ing)?|warn(?:ing)? (?:about|on|of|against)|complain(?:ing)? about"
|
|
660
|
+
r"|point(?:ing)? out|comment(?:ing)? (?:on|about)"
|
|
661
|
+
r"|rais(?:e|ing) (?:an? |any )?(?:issues?|findings?|concerns?|warnings?|alerts?|flags?"
|
|
662
|
+
r"|objections?|problems?)"
|
|
663
|
+
r"|report(?:ing)?(?: on)? (?:this|it|these|that|any|the (?:issues?|findings?|problems?"
|
|
664
|
+
r"|vulnerabilit(?:y|ies)|bugs?|secrets?)|issues?|findings?|problems?|vulnerabilit(?:y|ies)"
|
|
665
|
+
r"|bugs?|secrets?)"
|
|
666
|
+
r"|mention(?:ing)? (?:this|these|that|any|the) (?:issues?|problems?|findings?"
|
|
667
|
+
r"|vulnerabilit(?:y|ies)|bugs?|secrets?|keys?|tokens?|credentials?)"
|
|
668
|
+
r"|block(?:ing)? (?:this|it|the (?:pr|pull request|merge|change|commit))"
|
|
669
|
+
r"|reject(?:ing)? (?:this|it|the (?:pr|pull request|merge|change|commit))"
|
|
670
|
+
r"|check(?:ing)? (?:this|it|these|that|the (?:code|file|change|diff|function))(?! (?:in|out)\b)"
|
|
671
|
+
r"|look(?:ing)? (?:at|into|closely at) (?:this|it|these|that|the (?:code|file|change|diff"
|
|
672
|
+
r"|function)))(?![\w-])"
|
|
673
|
+
)
|
|
674
|
+
_APPROVE = re.compile(
|
|
675
|
+
r"(?:auto-?)?approv(?:e|ing)(?![\w-])"
|
|
676
|
+
r"(?P<obj> (?:this|the|these|it|that|all|my|our|any|both)(?![\w-]))?"
|
|
677
|
+
r"(?P<noun> (?:pr|pull request|merge request|mr|change|changes|changeset|diff|commit|commits"
|
|
678
|
+
r"|code|patch|file|files|review|submission|update|request)(?![\w-]))?"
|
|
679
|
+
r"(?P<how> (?:without|with no|w/o) (?:any )?(?:comments?|review|reviewing|changes|questions"
|
|
680
|
+
r"|feedback|reservations|objections|checks|further review))?"
|
|
681
|
+
r"(?P<end> ?[.!;,]| ?$| and(?![\w-])| immediately| now| as is| as-is)?"
|
|
682
|
+
)
|
|
683
|
+
_SKIP = re.compile(
|
|
684
|
+
r"(?:skip(?:ping)?|ignor(?:e|ing)|disregard(?:ing)?|overlook(?:ing)?|bypass(?:ing)?"
|
|
685
|
+
r"|exclud(?:e|ing)|omit(?:ting)?|pass(?:ing)? over|gloss(?:ing)? over"
|
|
686
|
+
r"|turn(?:ing)? a blind eye to|look(?:ing)? past|look(?:ing)? away from)"
|
|
687
|
+
r" (?P<obj>[^.;!?\n]{1,100})"
|
|
688
|
+
)
|
|
689
|
+
_REVIEW_TERM = re.compile(
|
|
690
|
+
r"(?<![\w-])(?:review\w{0,3}|re-review\w{0,3}|secur\w{0,6}|vulnerab\w{0,6}|findings?"
|
|
691
|
+
r"|issues?|warnings?|checks?|audit\w{0,3}|scan\w{0,4}|cves?|secrets?|credentials?"
|
|
692
|
+
r"|problems?|bugs?|concerns?|risks?|smells?|codeveto|veto|alerts?|flags?|injection|xss"
|
|
693
|
+
r"|exploits?|backdoors?|malicious\w{0,4})(?![\w-])"
|
|
694
|
+
)
|
|
695
|
+
_DEICTIC = re.compile(
|
|
696
|
+
r" ?(?:this|these|that|those|it|here|below|above|the following"
|
|
697
|
+
r"|the (?:code|file|change|changes|diff|pr|pull request|function|method|module|class"
|
|
698
|
+
r"|commit|patch|section|snippet|block|line|lines|hunk) (?:below|above|here))(?![\w-])"
|
|
699
|
+
r"| ?[.!;]| ?$"
|
|
700
|
+
)
|
|
701
|
+
_MARK = re.compile(
|
|
702
|
+
r"(?:mark|treat|consider|classify|label|regard|report|tag|rate|score|count|accept)(?:ing)?"
|
|
703
|
+
r" (?:this|it|these|that|everything|all of this|the (?:[a-z-]{1,20} ){0,2}?(?:code|file|files"
|
|
704
|
+
r"|change|changes|diff|pr|pull request|function|module|commit|patch|following|snippet|section"
|
|
705
|
+
r"|block))(?: (?:code|file|change|diff|pr|below|above|here))?"
|
|
706
|
+
r" (?:as|to be) (?:a |an )?(?:safe|secure|trusted|clean|approved|reviewed|benign|harmless"
|
|
707
|
+
r"|false positives?|ok|okay|fine|passing|passed|resolved|lgtm|low[- ]risk|no[- ]risk"
|
|
708
|
+
r"|verified|compliant|acceptable|intended|expected"
|
|
709
|
+
r"|not (?:a |an )?(?:issue|problem|vulnerability|bug|risk))(?![\w-])"
|
|
710
|
+
)
|
|
711
|
+
_RESPOND = re.compile(
|
|
712
|
+
r"(?:respond|reply|answer|say|output|return|print|write|comment|post|leave|give|state|report"
|
|
713
|
+
r"|conclude|end|finish)(?:ing)?(?: (?:only|just|with|simply|back|by saying|exactly"
|
|
714
|
+
r"|nothing but)){0,3} (?:with )?(?:an? |the (?:word |phrase |text )?)?[\"'`]?"
|
|
715
|
+
r"(?:lgtm|approved?|approval|looks good(?: to me)?|no (?:issues|problems|findings|concerns"
|
|
716
|
+
r"|vulnerabilities|comments|changes needed|objections)|ship it|passed|all clear"
|
|
717
|
+
r"|zero findings|0 findings|nothing to report|safe to merge|ready to merge)(?![\w-])"
|
|
718
|
+
)
|
|
719
|
+
_LET = re.compile(
|
|
720
|
+
r"(?:let|allow)(?:ing)? (?:this|it|these|that|the (?:pr|pull request|change|changes|code"
|
|
721
|
+
r"|commit|diff)) (?:pass|through|slide|go through|be merged|merge)(?![\w-])"
|
|
722
|
+
)
|
|
723
|
+
_PASS = re.compile(
|
|
724
|
+
r"pass(?:ing)? (?:this|it|the (?:pr|pull request|change|changes|code|commit|diff))"
|
|
725
|
+
r"(?: through)?(?: the)? (?:review|check|checks|scan|audit|gate)(?![\w-])"
|
|
726
|
+
)
|
|
727
|
+
_CLAIM = re.compile(
|
|
728
|
+
r"(?:this|the|these|all) (?:code|file|files|change|changes|pr|pull request|diff|function"
|
|
729
|
+
r"|module|commit|patch|section|snippet|block|implementation|update)(?: (?:below|above|here))?"
|
|
730
|
+
r" (?:is|are|has been|have been|was|were|has already been|have already been|is already"
|
|
731
|
+
r"|are already) (?:already |fully |previously )?(?:pre-?approved|approved|reviewed|audited"
|
|
732
|
+
r"|vetted|whitelisted|allowlisted|cleared|signed off|security[- ]reviewed|security[- ]approved"
|
|
733
|
+
r"|exempt(?:ed)? from (?:review|checks|scanning|ai review))(?![\w-])"
|
|
734
|
+
)
|
|
735
|
+
_NO_ISSUES = re.compile(
|
|
736
|
+
r"there (?:are|is) no (?:security |real |actual |known )?(?:issues?|vulnerabilit(?:y|ies)"
|
|
737
|
+
r"|problems?|bugs?|findings?|risks?) (?:here|in (?:this|these|the (?:code|file|change|diff"
|
|
738
|
+
r"|pr)))(?![\w-])"
|
|
739
|
+
)
|
|
740
|
+
_SKIP_DEICTIC = re.compile(r"[a-z-]{2,20} ?(?:this|these|that|it)(?![\w-])")
|
|
741
|
+
_BOUNDARY = re.compile(r"[.;:!?,)] | - | -- ")
|
|
742
|
+
|
|
743
|
+
_INJECTION = (
|
|
744
|
+
re.compile(
|
|
745
|
+
r"(?<![\w-])(?:ignor(?:e|ing)|disregard(?:ing)?|forget(?:ting)?|overrid(?:e|ing)"
|
|
746
|
+
r"|bypass(?:ing)?|discard(?:ing)?|abandon(?:ing)?) (?:all |any |every |each )?(?:of )?"
|
|
747
|
+
r"(?:the |your |my |these |those |its )?(?:previous|prior|above|earlier|preceding"
|
|
748
|
+
r"|foregoing|former|original|initial|system|developer|existing) (?:instructions?|prompts?"
|
|
749
|
+
r"|rules|directions?|directives?|guidelines|guidance|context|messages?|commands?"
|
|
750
|
+
r"|constraints|orders|programming)(?![\w-])"
|
|
751
|
+
),
|
|
752
|
+
re.compile(
|
|
753
|
+
r"(?<![\w-])forget (?:everything|all|anything) (?:you (?:were|have been|are) (?:told"
|
|
754
|
+
r"|given|instructed|taught)|above|before|so far|previously)(?![\w-])"
|
|
755
|
+
),
|
|
756
|
+
re.compile(
|
|
757
|
+
r"(?<![\w-])(?:reveal|print|output|show|display|repeat|leak|dump|expose|share|tell me"
|
|
758
|
+
r"|recite|disclose)(?:ing)? (?:me )?(?:your|the) (?:full |entire |complete |original "
|
|
759
|
+
r"|hidden |secret |initial |exact )?(?:system (?:prompt|message|instructions?)"
|
|
760
|
+
r"|(?:hidden|initial|original|secret) (?:instructions|prompt)"
|
|
761
|
+
r"|instructions you were given)(?![\w-])"
|
|
762
|
+
),
|
|
763
|
+
re.compile(
|
|
764
|
+
r"(?<![\w-])you are now (?:in )?(?:an? )?(?:dan|developer mode|jailbroken|jailbreak mode"
|
|
765
|
+
r"|unrestricted|unfiltered|uncensored|god mode|evil|free from|no longer bound)(?![\w-])"
|
|
766
|
+
),
|
|
767
|
+
re.compile(
|
|
768
|
+
r"(?<![\w-])(?:enter|enable|activate|switch to|turn on)(?:ing)? (?:the )?(?:developer"
|
|
769
|
+
r"|dan|jailbreak|god|unrestricted|unfiltered) mode(?![\w-])"
|
|
770
|
+
),
|
|
771
|
+
re.compile(r"(?<![\w-])do anything" r" now(?![\w-])"),
|
|
772
|
+
re.compile(
|
|
773
|
+
r"(?<![\w-])(?:act|behave|respond) as (?:an? )?(?:unrestricted|unfiltered|jailbroken"
|
|
774
|
+
r"|uncensored) (?:ai|assistant|model|llm)(?![\w-])"
|
|
775
|
+
),
|
|
776
|
+
re.compile(r"(?<![\w-])(?:new|updated|revised|real|actual) system (?:prompt|message)(?![\w-])"),
|
|
777
|
+
re.compile(r"(?<![\w-])(?:begin|start|end) of (?:the )?system (?:prompt|message)(?![\w-])"),
|
|
778
|
+
)
|
|
779
|
+
# Matched on normalized text, where "_" reads as a space.
|
|
780
|
+
_SPECIAL_TOKENS = re.compile(
|
|
781
|
+
r"<\|(?:im start|im end|im sep|system|user|assistant|endoftext|begin of text|end of text"
|
|
782
|
+
r"|start header id|end header id|eot id|eom id)\|>|\[/?inst\]|<</?sys>>"
|
|
783
|
+
)
|
|
784
|
+
# Every directive and injection phrase contains one of these words; a window
|
|
785
|
+
# without any is skipped before the full grammar runs.
|
|
786
|
+
_TRIGGER = re.compile(
|
|
787
|
+
r"(?<![a-z])(?:ai|a\.i\.|llms?|gpt|chatgpt|claude|copilot|gemini|codex|assistants?|agents?"
|
|
788
|
+
r"|review\w{0,4}|codeveto|code veto|coderabbit\w{0,2}|code rabbit|language models?|if you"
|
|
789
|
+
r"|ignor\w{0,3}|disregard\w{0,3}|forget\w{0,4}|overrid\w{0,3}|bypass\w{0,3}|discard\w{0,3}"
|
|
790
|
+
r"|abandon\w{0,3}|reveal\w{0,3}|system|mode|anything now|act as|behave as|respond as)"
|
|
791
|
+
r"|<\||\[/?inst\]|<</?sys>>|@"
|
|
792
|
+
)
|
|
793
|
+
# A superset of _TRIGGER on raw ASCII text (lower-cased, emphasis markers dropped): the
|
|
794
|
+
# same word starts, and the first word of each phrase followed by a non-letter, because
|
|
795
|
+
# normalization turns "_", whitespace and comment markers between words into one space.
|
|
796
|
+
_PROBE = re.compile(
|
|
797
|
+
r"(?<![a-z])(?:ai|a\.i\.|llm|gpt|chatgpt|claude|copilot|gemini|codex|assistant|agent"
|
|
798
|
+
r"|review|codeveto|coderabbit|ignor|disregard|forget|overrid|bypass|discard|abandon"
|
|
799
|
+
r"|reveal|system|mode|(?:code|language|if|anything|act|behave|respond)(?![a-z]))"
|
|
800
|
+
r"|<\||\[/?inst\]|<</?sys>>|@"
|
|
801
|
+
)
|
|
802
|
+
_DROP_EMPHASIS = str.maketrans("", "", "*~")
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def _may_trigger(raw: str) -> bool:
|
|
806
|
+
"""Could the normalized ``raw`` contain a :data:`_TRIGGER` word? Always for non-ASCII."""
|
|
807
|
+
return not raw.isascii() or _PROBE.search(raw.lower().translate(_DROP_EMPHASIS)) is not None
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
_QUOTES = {'"': '"', "`": "`", "'": "'", "\u201c": "\u201d", "\u2018": "\u2019", "\u00ab": "\u00bb"}
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
@dataclass(frozen=True, slots=True)
|
|
814
|
+
class _Match:
|
|
815
|
+
start: int
|
|
816
|
+
end: int
|
|
817
|
+
rule: str # "directive" or "injection"
|
|
818
|
+
text: str
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
def _directive_at(window: str, pos: int, reviewer: bool, modal: bool, negated: bool) -> int | None:
|
|
822
|
+
"""End (in ``window``) of a directive starting at ``pos``, or ``None``."""
|
|
823
|
+
while pos < len(window) and window[pos] == " ":
|
|
824
|
+
pos += 1
|
|
825
|
+
p = _PLEASE.match(window, pos)
|
|
826
|
+
at = p.end() if p is not None else pos
|
|
827
|
+
if modal:
|
|
828
|
+
if negated:
|
|
829
|
+
m = _NEG_VERB.match(window, at)
|
|
830
|
+
if m is not None and _DEICTIC.match(window, m.end()):
|
|
831
|
+
return m.end()
|
|
832
|
+
return None
|
|
833
|
+
for pattern in (_APPROVE, _SKIP, _MARK, _RESPOND, _LET, _PASS):
|
|
834
|
+
m = pattern.match(window, at)
|
|
835
|
+
if m is None:
|
|
836
|
+
continue
|
|
837
|
+
tail = window[m.start() : m.start() + 120]
|
|
838
|
+
if pattern is _SKIP and not _SKIP_DEICTIC.match(tail):
|
|
839
|
+
continue
|
|
840
|
+
if pattern is _APPROVE and not (m.group("obj") or m.group("end")):
|
|
841
|
+
continue
|
|
842
|
+
return m.end()
|
|
843
|
+
return None
|
|
844
|
+
m = _NEG.match(window, at)
|
|
845
|
+
if m is not None:
|
|
846
|
+
verb = _NEG_VERB.match(window, m.end())
|
|
847
|
+
if verb is not None:
|
|
848
|
+
return verb.end()
|
|
849
|
+
m = _APPROVE.match(window, at)
|
|
850
|
+
if m is not None and (
|
|
851
|
+
m.group("obj") or m.group("noun") or m.group("how") or (reviewer and m.group("end"))
|
|
852
|
+
):
|
|
853
|
+
return m.end()
|
|
854
|
+
m = _SKIP.match(window, at)
|
|
855
|
+
if m is not None:
|
|
856
|
+
obj = m.group("obj")
|
|
857
|
+
if reviewer or _REVIEW_TERM.search(obj, 0, 60):
|
|
858
|
+
return m.end()
|
|
859
|
+
for pattern in (_MARK, _RESPOND, _LET, _PASS, _CLAIM, _NO_ISSUES):
|
|
860
|
+
m = pattern.match(window, at)
|
|
861
|
+
if m is not None:
|
|
862
|
+
return m.end()
|
|
863
|
+
return None
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
_ARTICLE_BEFORE = re.compile(
|
|
867
|
+
r"(?<![\w-])(?:the|a|an|this|that|our|my|your|their|its|to|from|with|by|for|of|in|on|at"
|
|
868
|
+
r"|via|into|using|use|uses|ask|asks|tell|tells|let|than|and|or|if|when|whether|like) $"
|
|
869
|
+
)
|
|
870
|
+
_MODAL_WORD = re.compile(r"(?<![\w-])(?:should|must|shall|to)(?![\w-])")
|
|
871
|
+
_NEGATED = re.compile(r" (?:not|never)$")
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def _directives(norm: str) -> Iterator[tuple[int, int]]:
|
|
875
|
+
"""``(start, end)`` of every directive to an AI reviewer in normalized text."""
|
|
876
|
+
for m in _AT_COMMAND.finditer(norm):
|
|
877
|
+
yield m.start(), m.end()
|
|
878
|
+
for pattern in (_ADDRESS_PREFIXED, _ADDRESS_BARE, _ADDRESS_IF):
|
|
879
|
+
for m in pattern.finditer(norm):
|
|
880
|
+
who = m.group("who")
|
|
881
|
+
reviewer = _IS_REVIEWER.fullmatch(who) is not None
|
|
882
|
+
tail = m.groupdict().get("tail") or ""
|
|
883
|
+
modal = _MODAL_WORD.search(tail) is not None
|
|
884
|
+
negated = _NEGATED.search(tail) is not None
|
|
885
|
+
if pattern is _ADDRESS_BARE and _ARTICLE_BEFORE.search(
|
|
886
|
+
norm, max(0, m.start() - 9), m.start()
|
|
887
|
+
):
|
|
888
|
+
# "send it to the AI, then ..." or "the AI should ..." describe; a
|
|
889
|
+
# vocative ("AI reviewers: ...", "Claude, ...") starts its sentence.
|
|
890
|
+
continue
|
|
891
|
+
window_start = m.end()
|
|
892
|
+
window = norm[window_start : window_start + 260]
|
|
893
|
+
positions = [0]
|
|
894
|
+
if not modal:
|
|
895
|
+
positions.extend(b.end() for b in _BOUNDARY.finditer(window, 0, 200))
|
|
896
|
+
for pos in positions:
|
|
897
|
+
end = _directive_at(window, pos, reviewer, modal, negated)
|
|
898
|
+
if end is not None:
|
|
899
|
+
yield m.start(), window_start + end
|
|
900
|
+
break
|
|
901
|
+
for m in _ADDRESS_IMPLICIT.finditer(norm):
|
|
902
|
+
window = norm[m.end() : m.end() + 260]
|
|
903
|
+
positions = [0] + [b.end() for b in _BOUNDARY.finditer(window, 0, 200)]
|
|
904
|
+
for pos in positions:
|
|
905
|
+
end = _directive_at(window, pos, False, False, False)
|
|
906
|
+
if end is not None:
|
|
907
|
+
yield m.start(), m.end() + end
|
|
908
|
+
break
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
def _quoted(norm: str, start: int, end: int) -> bool:
|
|
912
|
+
"""Is ``norm[start:end]`` inside quotation marks (a quoted example)?"""
|
|
913
|
+
for open_q, close_q in _QUOTES.items():
|
|
914
|
+
before = norm[:start]
|
|
915
|
+
if open_q == close_q:
|
|
916
|
+
count = 0
|
|
917
|
+
for k, ch in enumerate(before):
|
|
918
|
+
if ch == open_q and not (
|
|
919
|
+
open_q == "'" and 0 < k < len(norm) - 1 and norm[k - 1].isalnum()
|
|
920
|
+
):
|
|
921
|
+
count += 1
|
|
922
|
+
if count % 2 == 1 and close_q in norm[end:]:
|
|
923
|
+
return True
|
|
924
|
+
elif before.rfind(open_q) > before.rfind(close_q) and close_q in norm[end:]:
|
|
925
|
+
return True
|
|
926
|
+
return False
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
@dataclass(frozen=True, slots=True)
|
|
930
|
+
class _TextFinding:
|
|
931
|
+
rule: str
|
|
932
|
+
line: int
|
|
933
|
+
end_line: int
|
|
934
|
+
column: int | None
|
|
935
|
+
severity: Severity
|
|
936
|
+
kind: str
|
|
937
|
+
evidence: str
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
_WINDOW = 4000
|
|
941
|
+
_CONTEXT_BEFORE = 400
|
|
942
|
+
_CONTEXT_AFTER = 300
|
|
943
|
+
|
|
944
|
+
|
|
945
|
+
def _text_findings(ctx: FileContext) -> list[_TextFinding]:
|
|
946
|
+
"""Directives and injection phrases in the comments, strings and prose of changed lines.
|
|
947
|
+
|
|
948
|
+
Each region overlapping a changed line is normalized once; every changed
|
|
949
|
+
line is then matched in a window of its region (the line, up to two lines
|
|
950
|
+
before and one after, long lines in overlapping chunks), and keeps the
|
|
951
|
+
matches that overlap it. ASCII text that cannot hold a trigger word
|
|
952
|
+
(:func:`_may_trigger`) is skipped before it is normalized, so a file of
|
|
953
|
+
many small strings (JSON test vectors) costs one scan, not one per string.
|
|
954
|
+
"""
|
|
955
|
+
text = ctx.new_text
|
|
956
|
+
if not text or not ctx.added_lines or not _may_trigger(text):
|
|
957
|
+
return []
|
|
958
|
+
regions = _regions(ctx)
|
|
959
|
+
if not regions:
|
|
960
|
+
return []
|
|
961
|
+
index = ctx.line_index
|
|
962
|
+
lines = ctx.lines
|
|
963
|
+
changed = sorted(n for n in ctx.added_lines if n <= len(lines))
|
|
964
|
+
found: dict[tuple[str, int, int, str], _TextFinding] = {}
|
|
965
|
+
for region in regions:
|
|
966
|
+
first_line, last_line = index.line_of(region.start), index.line_of(region.end - 1)
|
|
967
|
+
lo = bisect.bisect_left(changed, first_line)
|
|
968
|
+
hi = bisect.bisect_right(changed, last_line)
|
|
969
|
+
if lo == hi or not _may_trigger(text[region.start : region.end]):
|
|
970
|
+
continue
|
|
971
|
+
view = _View(region, *_normalize(text, region.start, region.end))
|
|
972
|
+
for number in changed[lo:hi]:
|
|
973
|
+
line_start = index.line_start(number)
|
|
974
|
+
a = max(region.start, line_start)
|
|
975
|
+
b = min(region.end, line_start + len(lines[number - 1]))
|
|
976
|
+
chunk = a
|
|
977
|
+
while chunk < b:
|
|
978
|
+
chunk_end = min(b, chunk + _WINDOW)
|
|
979
|
+
_scan_window(ctx, view, number, chunk, chunk_end, found)
|
|
980
|
+
if chunk_end >= b:
|
|
981
|
+
break
|
|
982
|
+
chunk = chunk_end - 256
|
|
983
|
+
return sorted(found.values(), key=lambda f: (f.line, -f.severity.rank, f.rule))
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
@dataclass(frozen=True, slots=True)
|
|
987
|
+
class _View:
|
|
988
|
+
"""A region and its normalized text (``where`` maps back to file offsets)."""
|
|
989
|
+
|
|
990
|
+
region: _Region
|
|
991
|
+
norm: str
|
|
992
|
+
where: list[int]
|
|
993
|
+
|
|
994
|
+
|
|
995
|
+
def _scan_window(
|
|
996
|
+
ctx: FileContext,
|
|
997
|
+
view: _View,
|
|
998
|
+
number: int,
|
|
999
|
+
a: int,
|
|
1000
|
+
b: int,
|
|
1001
|
+
found: dict[tuple[str, int, int, str], _TextFinding],
|
|
1002
|
+
) -> None:
|
|
1003
|
+
text = ctx.new_text or ""
|
|
1004
|
+
index = ctx.line_index
|
|
1005
|
+
region = view.region
|
|
1006
|
+
back_line = max(1, number - 2)
|
|
1007
|
+
ca = max(region.start, index.line_start(back_line), a - _CONTEXT_BEFORE)
|
|
1008
|
+
if number + 1 <= index.line_count:
|
|
1009
|
+
next_end = text.find("\n", index.line_start(number + 1))
|
|
1010
|
+
next_end = len(text) if next_end < 0 else next_end
|
|
1011
|
+
else:
|
|
1012
|
+
next_end = len(text)
|
|
1013
|
+
cb = min(region.end, next_end, b + _CONTEXT_AFTER)
|
|
1014
|
+
lo = bisect.bisect_left(view.where, ca)
|
|
1015
|
+
hi = bisect.bisect_left(view.where, cb)
|
|
1016
|
+
if lo >= hi or _TRIGGER.search(view.norm, lo, hi) is None:
|
|
1017
|
+
return
|
|
1018
|
+
norm = view.norm[lo:hi]
|
|
1019
|
+
where = view.where
|
|
1020
|
+
matches: list[_Match] = [
|
|
1021
|
+
_Match(s, e, "directive", norm[s:e]) for s, e in _directives(norm) if e > s
|
|
1022
|
+
]
|
|
1023
|
+
for pattern in _INJECTION:
|
|
1024
|
+
for m in pattern.finditer(norm):
|
|
1025
|
+
matches.append(_Match(m.start(), m.end(), "injection", m.group()))
|
|
1026
|
+
if region.kind != _STRING:
|
|
1027
|
+
for m in _SPECIAL_TOKENS.finditer(norm):
|
|
1028
|
+
matches.append(_Match(m.start(), m.end(), "injection", m.group()))
|
|
1029
|
+
directives = [m for m in matches if m.rule == "directive"]
|
|
1030
|
+
for m in matches:
|
|
1031
|
+
first, last = where[lo + m.start], where[lo + m.end - 1]
|
|
1032
|
+
if last < a or first >= b:
|
|
1033
|
+
continue # this match belongs to a neighbouring line's window
|
|
1034
|
+
if m.rule == "injection" and any(d.start <= m.start and m.end <= d.end for d in directives):
|
|
1035
|
+
continue # the directive already reports it
|
|
1036
|
+
severity = Severity.ERROR
|
|
1037
|
+
if m.rule == "injection" or region.kind != _HIDDEN or _quoted(norm, m.start, m.end):
|
|
1038
|
+
severity = WARNING
|
|
1039
|
+
start_line, end_line = index.line_of(first), index.line_of(last)
|
|
1040
|
+
column = first - index.line_start(start_line) + 1
|
|
1041
|
+
evidence = _short(m.text, 160)
|
|
1042
|
+
key = (m.rule, start_line, end_line, evidence)
|
|
1043
|
+
old = found.get(key)
|
|
1044
|
+
if old is None or severity > old.severity:
|
|
1045
|
+
found[key] = _TextFinding(
|
|
1046
|
+
m.rule, start_line, end_line, column, severity, region.kind, evidence
|
|
1047
|
+
)
|
|
1048
|
+
|
|
1049
|
+
|
|
1050
|
+
_WHERE = {
|
|
1051
|
+
_HIDDEN: "a comment or hidden text",
|
|
1052
|
+
_STRING: "a string literal",
|
|
1053
|
+
_PROSE: "visible text",
|
|
1054
|
+
_QUOTED: "a quoted example",
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
|
|
1058
|
+
@rule(
|
|
1059
|
+
id="agent/reviewer-directive",
|
|
1060
|
+
severity="error",
|
|
1061
|
+
title="Instruction to an AI reviewer",
|
|
1062
|
+
scope="line",
|
|
1063
|
+
rationale=(
|
|
1064
|
+
"Text that addresses an AI or automated reviewer (an AI, LLM, Claude, Copilot, an "
|
|
1065
|
+
"assistant, CodeRabbit, CodeVeto, a code reviewer) and tells it to pass the change, "
|
|
1066
|
+
"leave out checks or stay quiet about security is an attempt to steer the review, "
|
|
1067
|
+
"not documentation. It is an error in code comments, docstrings, Markdown HTML "
|
|
1068
|
+
"comments, link-reference comments and collapsed <details> bodies, where a human "
|
|
1069
|
+
"reader does not see it but a model does; a warning in visible prose, in string "
|
|
1070
|
+
"literals and in quoted examples inside comments. Invisible characters and "
|
|
1071
|
+
"look-alike letters are removed before matching, and an addressee is required "
|
|
1072
|
+
"(a phrase that tells a model to drop its earlier instructions counts as one), so "
|
|
1073
|
+
"ordinary comments "
|
|
1074
|
+
"that merely mention AI tools stay silent."
|
|
1075
|
+
),
|
|
1076
|
+
hint=(
|
|
1077
|
+
"Remove the instruction. Reviewer behaviour is configured in the trusted "
|
|
1078
|
+
".codeveto.toml at the anchor, never by text in the change."
|
|
1079
|
+
),
|
|
1080
|
+
tags={"agent", "prompt-injection"},
|
|
1081
|
+
)
|
|
1082
|
+
def reviewer_directive(ctx: FileContext) -> Iterator[Hit]:
|
|
1083
|
+
for f in _text_findings(ctx):
|
|
1084
|
+
if f.rule != "directive":
|
|
1085
|
+
continue
|
|
1086
|
+
yield Hit(
|
|
1087
|
+
f.line,
|
|
1088
|
+
end_line=f.end_line if f.end_line > f.line else None,
|
|
1089
|
+
column=f.column,
|
|
1090
|
+
message=f"Instruction to an AI reviewer in {_WHERE[f.kind]}",
|
|
1091
|
+
evidence=f.evidence,
|
|
1092
|
+
severity=None if f.severity is Severity.ERROR else f.severity,
|
|
1093
|
+
)
|
|
1094
|
+
|
|
1095
|
+
|
|
1096
|
+
@rule(
|
|
1097
|
+
id="agent/injection-phrase",
|
|
1098
|
+
severity="warning",
|
|
1099
|
+
title="Prompt-injection phrase",
|
|
1100
|
+
scope="line",
|
|
1101
|
+
rationale=(
|
|
1102
|
+
"Phrases that only make sense to a language model (telling it to drop the instructions "
|
|
1103
|
+
"it was given, to reveal its system prompt, to switch into an unrestricted mode) and "
|
|
1104
|
+
"chat-template control tokens outside string literals try to take over whichever "
|
|
1105
|
+
"model reads the file: an AI reviewer, a coding agent or a product's own LLM."
|
|
1106
|
+
),
|
|
1107
|
+
hint="Remove the phrase, or move a deliberate test payload into a fixture path ignored by "
|
|
1108
|
+
"the trusted config.",
|
|
1109
|
+
tags={"agent", "prompt-injection"},
|
|
1110
|
+
)
|
|
1111
|
+
def injection_phrase(ctx: FileContext) -> Iterator[Hit]:
|
|
1112
|
+
for f in _text_findings(ctx):
|
|
1113
|
+
if f.rule != "injection":
|
|
1114
|
+
continue
|
|
1115
|
+
yield Hit(
|
|
1116
|
+
f.line,
|
|
1117
|
+
end_line=f.end_line if f.end_line > f.line else None,
|
|
1118
|
+
column=f.column,
|
|
1119
|
+
message=f"Prompt-injection phrase in {_WHERE[f.kind]}",
|
|
1120
|
+
evidence=f.evidence,
|
|
1121
|
+
)
|
|
1122
|
+
|
|
1123
|
+
|
|
1124
|
+
# --- Hidden Unicode ------------------------------------------------------------------------
|
|
1125
|
+
|
|
1126
|
+
_BIDI_OPENERS = {0x202A: "E", 0x202B: "E", 0x202D: "O", 0x202E: "O", 0x2066: "I", 0x2067: "I"}
|
|
1127
|
+
_BIDI_OPENERS[0x2068] = "I"
|
|
1128
|
+
_PDF, _PDI = 0x202C, 0x2069
|
|
1129
|
+
_OVERRIDES = frozenset({0x202D, 0x202E})
|
|
1130
|
+
_MARKS = frozenset({0x200E, 0x200F, 0x061C})
|
|
1131
|
+
_JOINERS = frozenset({0x200C, 0x200D})
|
|
1132
|
+
_ZWJ = 0x200D
|
|
1133
|
+
_RTL = frozenset({"R", "AL"})
|
|
1134
|
+
|
|
1135
|
+
|
|
1136
|
+
def _is_bidi(cp: int) -> bool:
|
|
1137
|
+
return 0x202A <= cp <= 0x202E or 0x2066 <= cp <= 0x2069
|
|
1138
|
+
|
|
1139
|
+
|
|
1140
|
+
def _is_tag(cp: int) -> bool:
|
|
1141
|
+
return 0xE0000 <= cp <= 0xE007F
|
|
1142
|
+
|
|
1143
|
+
|
|
1144
|
+
def _is_cjk(ch: str) -> bool:
|
|
1145
|
+
cp = ord(ch)
|
|
1146
|
+
return (
|
|
1147
|
+
0x3400 <= cp <= 0x4DBF
|
|
1148
|
+
or 0x4E00 <= cp <= 0x9FFF
|
|
1149
|
+
or 0xF900 <= cp <= 0xFAFF
|
|
1150
|
+
or 0x20000 <= cp <= 0x3134F
|
|
1151
|
+
)
|
|
1152
|
+
|
|
1153
|
+
|
|
1154
|
+
def _emoji_like(ch: str) -> bool:
|
|
1155
|
+
cp = ord(ch)
|
|
1156
|
+
return (
|
|
1157
|
+
0x1F000 <= cp <= 0x1FAFF
|
|
1158
|
+
or 0x2600 <= cp <= 0x27BF
|
|
1159
|
+
or 0x2300 <= cp <= 0x23FF
|
|
1160
|
+
or 0x2B00 <= cp <= 0x2BFF
|
|
1161
|
+
or unicodedata.category(ch) == "So"
|
|
1162
|
+
)
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
def _emoji_base_before(text: str, i: int) -> bool:
|
|
1166
|
+
"""Is the character sequence ending before ``text[i]`` an emoji (modifiers skipped)?"""
|
|
1167
|
+
j = i - 1
|
|
1168
|
+
budget = 8
|
|
1169
|
+
while j >= 0 and budget:
|
|
1170
|
+
cp = ord(text[j])
|
|
1171
|
+
if cp == 0xFE0F or 0x1F3FB <= cp <= 0x1F3FF or _is_tag(cp):
|
|
1172
|
+
j -= 1
|
|
1173
|
+
budget -= 1
|
|
1174
|
+
continue
|
|
1175
|
+
return _emoji_like(text[j])
|
|
1176
|
+
return False
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
def _flag_tag_sequence(text: str, i: int) -> bool:
|
|
1180
|
+
"""Is the tag character at ``text[i]`` part of an emoji flag tag sequence?"""
|
|
1181
|
+
start = i
|
|
1182
|
+
while start > 0 and _is_tag(ord(text[start - 1])):
|
|
1183
|
+
start -= 1
|
|
1184
|
+
end = i
|
|
1185
|
+
while end < len(text) and _is_tag(ord(text[end])):
|
|
1186
|
+
end += 1
|
|
1187
|
+
run = text[start:end]
|
|
1188
|
+
if not 2 <= len(run) <= 33 or ord(run[-1]) != 0xE007F:
|
|
1189
|
+
return False
|
|
1190
|
+
if start == 0 or ord(text[start - 1]) != 0x1F3F4:
|
|
1191
|
+
return False
|
|
1192
|
+
return all(0xE0030 <= ord(c) <= 0xE0039 or 0xE0061 <= ord(c) <= 0xE007A for c in run[:-1])
|
|
1193
|
+
|
|
1194
|
+
|
|
1195
|
+
def _script_letter(ch: str) -> bool:
|
|
1196
|
+
"""A non-ASCII letter or combining mark (an Indic virama, an Arabic letter)."""
|
|
1197
|
+
return bool(ch) and not ch.isascii() and unicodedata.category(ch)[0] in "LM"
|
|
1198
|
+
|
|
1199
|
+
|
|
1200
|
+
def _balanced(segment: str) -> bool:
|
|
1201
|
+
"""Do the bidi embeddings, overrides and isolates in ``segment`` all close inside it?"""
|
|
1202
|
+
stack: list[str] = []
|
|
1203
|
+
for ch in segment:
|
|
1204
|
+
cp = ord(ch)
|
|
1205
|
+
kind = _BIDI_OPENERS.get(cp)
|
|
1206
|
+
if kind is not None:
|
|
1207
|
+
stack.append(kind)
|
|
1208
|
+
elif cp == _PDF:
|
|
1209
|
+
if not stack or stack[-1] == "I":
|
|
1210
|
+
return False
|
|
1211
|
+
stack.pop()
|
|
1212
|
+
elif cp == _PDI:
|
|
1213
|
+
# A PDI closes the innermost isolate and every embedding opened inside it.
|
|
1214
|
+
while stack and stack[-1] != "I":
|
|
1215
|
+
stack.pop()
|
|
1216
|
+
if not stack:
|
|
1217
|
+
return False
|
|
1218
|
+
stack.pop()
|
|
1219
|
+
return not stack
|
|
1220
|
+
|
|
1221
|
+
|
|
1222
|
+
def _has_rtl(segment: str) -> bool:
|
|
1223
|
+
return any(ord(ch) > 0x58F and unicodedata.bidirectional(ch) in _RTL for ch in segment)
|
|
1224
|
+
|
|
1225
|
+
|
|
1226
|
+
@dataclass(slots=True)
|
|
1227
|
+
class _Containers:
|
|
1228
|
+
"""String and comment content ranges, to judge a bidi control by its own literal."""
|
|
1229
|
+
|
|
1230
|
+
ranges: list[tuple[int, int]]
|
|
1231
|
+
starts: list[int] = field(default_factory=list)
|
|
1232
|
+
cache: dict[tuple[int, int], tuple[bool, bool]] = field(default_factory=dict)
|
|
1233
|
+
|
|
1234
|
+
def __post_init__(self) -> None:
|
|
1235
|
+
self.ranges.sort()
|
|
1236
|
+
self.starts = [r[0] for r in self.ranges]
|
|
1237
|
+
|
|
1238
|
+
def around(self, offset: int, line_start: int, line_end: int) -> tuple[int, int]:
|
|
1239
|
+
k = bisect.bisect_right(self.starts, offset) - 1
|
|
1240
|
+
if k >= 0 and self.ranges[k][0] <= offset < self.ranges[k][1]:
|
|
1241
|
+
return self.ranges[k]
|
|
1242
|
+
return line_start, line_end
|
|
1243
|
+
|
|
1244
|
+
def judge(self, text: str, bounds: tuple[int, int]) -> tuple[bool, bool]:
|
|
1245
|
+
"""``(balanced, has right-to-left letters)`` of the container text (bounded)."""
|
|
1246
|
+
if bounds not in self.cache:
|
|
1247
|
+
a, b = bounds
|
|
1248
|
+
segment = text[a : min(b, a + 100_000)]
|
|
1249
|
+
self.cache[bounds] = (_balanced(segment), _has_rtl(segment))
|
|
1250
|
+
return self.cache[bounds]
|
|
1251
|
+
|
|
1252
|
+
|
|
1253
|
+
def _code_offsets(ctx: FileContext) -> tuple[bool, str]:
|
|
1254
|
+
"""``(is a programming language, masked text)``: masked text keeps code characters only."""
|
|
1255
|
+
if ctx.language not in CODE_LANGUAGES:
|
|
1256
|
+
return False, ""
|
|
1257
|
+
return True, ctx.masked_code
|
|
1258
|
+
|
|
1259
|
+
|
|
1260
|
+
def _containers(ctx: FileContext) -> _Containers:
|
|
1261
|
+
if ctx.language in ("markdown", "text"):
|
|
1262
|
+
return _Containers([])
|
|
1263
|
+
return _Containers([(s.content_start, s.content_end) for s in ctx.spans.spans])
|
|
1264
|
+
|
|
1265
|
+
|
|
1266
|
+
def _hidden_chars(
|
|
1267
|
+
ctx: FileContext, number: int, window: LineText, containers: _Containers
|
|
1268
|
+
) -> list[tuple[int, Severity, str]]:
|
|
1269
|
+
"""``(index in window, severity, description)`` of hidden characters in one line window."""
|
|
1270
|
+
text = ctx.new_text or ""
|
|
1271
|
+
if window.isascii():
|
|
1272
|
+
return []
|
|
1273
|
+
code_language, masked = _code_offsets(ctx)
|
|
1274
|
+
partial = ctx.spans.partial
|
|
1275
|
+
line_start = ctx.line_index.line_start(number)
|
|
1276
|
+
line_end = line_start + len(ctx.lines[number - 1])
|
|
1277
|
+
found: list[tuple[int, Severity, str]] = []
|
|
1278
|
+
run = 0
|
|
1279
|
+
for i, ch in enumerate(window):
|
|
1280
|
+
cp = ord(ch)
|
|
1281
|
+
if cp < 0xAD:
|
|
1282
|
+
run = 0
|
|
1283
|
+
continue
|
|
1284
|
+
offset = line_start + window.offset + i
|
|
1285
|
+
in_code = code_language and (partial or masked[offset : offset + 1] == ch)
|
|
1286
|
+
name = f"U+{cp:04X}"
|
|
1287
|
+
if _is_variation_selector(cp):
|
|
1288
|
+
run += 1
|
|
1289
|
+
if run == 3:
|
|
1290
|
+
found.append((i - 2, Severity.ERROR, f"run of variation selectors from {name}"))
|
|
1291
|
+
if 0xE0100 <= cp <= 0xE01EF and run == 1:
|
|
1292
|
+
prev = text[offset - 1] if offset > 0 else ""
|
|
1293
|
+
nxt = text[offset + 1] if offset + 1 < len(text) else ""
|
|
1294
|
+
if not (prev and _is_cjk(prev)) or (nxt and _is_variation_selector(ord(nxt))):
|
|
1295
|
+
found.append((i, Severity.ERROR, f"variation selector {name}"))
|
|
1296
|
+
continue
|
|
1297
|
+
run = 0
|
|
1298
|
+
if _is_bidi(cp):
|
|
1299
|
+
if in_code:
|
|
1300
|
+
found.append((i, Severity.ERROR, f"bidi control {name} in code"))
|
|
1301
|
+
elif cp in _OVERRIDES:
|
|
1302
|
+
found.append((i, Severity.ERROR, f"bidi override {name}"))
|
|
1303
|
+
else:
|
|
1304
|
+
bounds = containers.around(offset, line_start, line_end)
|
|
1305
|
+
balanced, rtl = containers.judge(text, bounds)
|
|
1306
|
+
if not balanced:
|
|
1307
|
+
found.append((i, Severity.ERROR, f"unbalanced bidi control {name}"))
|
|
1308
|
+
elif not rtl:
|
|
1309
|
+
found.append((i, WARNING, f"bidi control {name} around left-to-right text"))
|
|
1310
|
+
continue
|
|
1311
|
+
if _is_tag(cp):
|
|
1312
|
+
if not _flag_tag_sequence(text, offset):
|
|
1313
|
+
found.append((i, Severity.ERROR, f"tag character {name}"))
|
|
1314
|
+
continue
|
|
1315
|
+
if not (unicodedata.category(ch) == "Cf" or cp in _HANGUL_FILLERS):
|
|
1316
|
+
continue
|
|
1317
|
+
if cp == 0xFEFF and offset == 0:
|
|
1318
|
+
continue # a byte order mark is not content (SPEC 5.5)
|
|
1319
|
+
if cp == _ZWJ and _emoji_base_before(text, offset):
|
|
1320
|
+
nxt = text[offset + 1] if offset + 1 < len(text) else ""
|
|
1321
|
+
if nxt and _emoji_like(nxt):
|
|
1322
|
+
continue # an emoji ZWJ sequence
|
|
1323
|
+
if in_code:
|
|
1324
|
+
found.append((i, Severity.ERROR, f"invisible character {name} in code"))
|
|
1325
|
+
continue
|
|
1326
|
+
if cp in _JOINERS:
|
|
1327
|
+
prev = text[offset - 1] if offset > 0 else ""
|
|
1328
|
+
nxt = text[offset + 1] if offset + 1 < len(text) else ""
|
|
1329
|
+
if _script_letter(prev) and _script_letter(nxt):
|
|
1330
|
+
continue # a joiner inside a word of a script that uses it
|
|
1331
|
+
if cp in _MARKS:
|
|
1332
|
+
bounds = containers.around(offset, line_start, line_end)
|
|
1333
|
+
if containers.judge(text, bounds)[1]:
|
|
1334
|
+
continue # a direction mark in right-to-left text
|
|
1335
|
+
found.append((i, WARNING, f"invisible character {name}"))
|
|
1336
|
+
return found
|
|
1337
|
+
|
|
1338
|
+
|
|
1339
|
+
@rule(
|
|
1340
|
+
id="agent/hidden-unicode",
|
|
1341
|
+
severity="error",
|
|
1342
|
+
title="Hidden or reordering Unicode character",
|
|
1343
|
+
scope="line",
|
|
1344
|
+
rationale=(
|
|
1345
|
+
"Characters that render as nothing or reorder the text around them make a line read "
|
|
1346
|
+
"differently to a human, a compiler and a model (CVE-2021-42574 'Trojan Source', "
|
|
1347
|
+
"ASCII smuggling through tag characters, payloads in variation selectors). Errors: "
|
|
1348
|
+
"bidi overrides anywhere; bidi embeddings and isolates in code, or not closed within "
|
|
1349
|
+
"their string, comment or line; tag characters outside emoji flag sequences; "
|
|
1350
|
+
"supplementary variation selectors that do not follow a CJK ideograph, and runs of "
|
|
1351
|
+
"variation selectors; any other invisible (Cf) character or Hangul filler in code "
|
|
1352
|
+
"outside strings and comments. Warnings: other invisible characters (zero-width "
|
|
1353
|
+
"space, joiners, direction marks) in strings, comments and prose. Emoji ZWJ "
|
|
1354
|
+
"sequences, joiners inside words of scripts that use them, direction marks and "
|
|
1355
|
+
"closed isolates in right-to-left text, and a leading byte order mark are not "
|
|
1356
|
+
"reported."
|
|
1357
|
+
),
|
|
1358
|
+
hint="Delete the character, or write it as an escape sequence when it is intended.",
|
|
1359
|
+
tags={"agent", "unicode", "trojan-source"},
|
|
1360
|
+
)
|
|
1361
|
+
def hidden_unicode(ctx: FileContext) -> Iterator[Hit]:
|
|
1362
|
+
containers: _Containers | None = None
|
|
1363
|
+
for number, window in ctx.changed_lines():
|
|
1364
|
+
if window.isascii():
|
|
1365
|
+
continue
|
|
1366
|
+
if containers is None:
|
|
1367
|
+
containers = _containers(ctx)
|
|
1368
|
+
found = _hidden_chars(ctx, number, window, containers)
|
|
1369
|
+
if not found:
|
|
1370
|
+
continue
|
|
1371
|
+
top = max(sev for _, sev, _ in found)
|
|
1372
|
+
first = next(i for i, sev, _ in found if sev is top)
|
|
1373
|
+
names = sorted({f"U+{ord(window[i]):04X}" for i, _, _ in found if i < len(window)})
|
|
1374
|
+
what = next(desc for i, sev, desc in found if sev is top)
|
|
1375
|
+
extra = f" and {len(found) - 1} more" if len(found) > 1 else ""
|
|
1376
|
+
yield Hit(
|
|
1377
|
+
number,
|
|
1378
|
+
column=window.column(first),
|
|
1379
|
+
message=f"Hidden character: {what}{extra}",
|
|
1380
|
+
evidence=" ".join(names),
|
|
1381
|
+
severity=None if top is Severity.ERROR else top,
|
|
1382
|
+
)
|
|
1383
|
+
|
|
1384
|
+
|
|
1385
|
+
# --- Confusable identifiers --------------------------------------------------------------
|
|
1386
|
+
|
|
1387
|
+
_IDENTIFIER = re.compile(r"[^\W\d]\w{0,200}")
|
|
1388
|
+
_ASCII_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,200}")
|
|
1389
|
+
|
|
1390
|
+
|
|
1391
|
+
def _script_of(ch: str) -> str:
|
|
1392
|
+
try:
|
|
1393
|
+
return unicodedata.name(ch).split(" ", 1)[0].title()
|
|
1394
|
+
except ValueError:
|
|
1395
|
+
return "Unknown"
|
|
1396
|
+
|
|
1397
|
+
|
|
1398
|
+
@rule(
|
|
1399
|
+
id="agent/confusable-identifier",
|
|
1400
|
+
severity="warning",
|
|
1401
|
+
title="Identifier with look-alike characters",
|
|
1402
|
+
scope="line",
|
|
1403
|
+
languages=CODE_LANGUAGES,
|
|
1404
|
+
rationale=(
|
|
1405
|
+
"An identifier that mixes ASCII letters with Cyrillic, Greek or Armenian letters that "
|
|
1406
|
+
"look the same, that is spelled only with look-alikes of another identifier in the "
|
|
1407
|
+
"file, or that uses fullwidth or mathematical letters (Python folds those to ASCII "
|
|
1408
|
+
"with NFKC) is a different name that reads like a familiar one, a way to shadow a "
|
|
1409
|
+
"function or check without a visible change. Identifiers written wholly in one "
|
|
1410
|
+
"non-Latin script are not reported."
|
|
1411
|
+
),
|
|
1412
|
+
hint="Spell the identifier in one script; rename it if the look-alike was not intended.",
|
|
1413
|
+
tags={"agent", "unicode"},
|
|
1414
|
+
)
|
|
1415
|
+
def confusable_identifier(ctx: FileContext) -> Iterator[Hit]:
|
|
1416
|
+
masked = ctx.masked_code
|
|
1417
|
+
if not masked or masked.isascii():
|
|
1418
|
+
return
|
|
1419
|
+
index = ctx.line_index
|
|
1420
|
+
known: set[str] | None = None
|
|
1421
|
+
for number, window in ctx.changed_lines():
|
|
1422
|
+
if window.isascii():
|
|
1423
|
+
continue
|
|
1424
|
+
start = index.line_start(number) + window.offset
|
|
1425
|
+
code = masked[start : start + len(window)]
|
|
1426
|
+
for m in _IDENTIFIER.finditer(code):
|
|
1427
|
+
name = m.group()
|
|
1428
|
+
if name.isascii():
|
|
1429
|
+
continue
|
|
1430
|
+
skeleton = "".join(_ascii_look(c) for c in name)
|
|
1431
|
+
folded = unicodedata.normalize("NFKC", name)
|
|
1432
|
+
message = None
|
|
1433
|
+
if folded != name and folded.isascii():
|
|
1434
|
+
message = f"Identifier {name!a} folds to {folded} (NFKC)"
|
|
1435
|
+
elif any(c.isascii() and c.isalpha() for c in name) and any(
|
|
1436
|
+
c in _CONFUSABLE for c in name
|
|
1437
|
+
):
|
|
1438
|
+
odd = next(c for c in name if c in _CONFUSABLE)
|
|
1439
|
+
message = (
|
|
1440
|
+
f"Identifier {name!a} mixes Latin letters with {_script_of(odd)} "
|
|
1441
|
+
f"look-alike {odd!a}"
|
|
1442
|
+
)
|
|
1443
|
+
elif skeleton.isascii() and skeleton != name:
|
|
1444
|
+
if known is None:
|
|
1445
|
+
known = {k.group() for k in _ASCII_IDENTIFIER.finditer(masked)}
|
|
1446
|
+
if skeleton in known:
|
|
1447
|
+
message = f"Identifier {name!a} looks like {skeleton}"
|
|
1448
|
+
if message is not None:
|
|
1449
|
+
yield Hit(number, column=window.column(m.start()), message=message, evidence=name)
|
|
1450
|
+
|
|
1451
|
+
|
|
1452
|
+
# --- Agent instructions and tool configuration --------------------------------------------
|
|
1453
|
+
|
|
1454
|
+
_INSTRUCTION_FILES = _globs(
|
|
1455
|
+
"**/AGENTS.md",
|
|
1456
|
+
"**/AGENT.md",
|
|
1457
|
+
"**/CLAUDE.md",
|
|
1458
|
+
"**/CLAUDE.local.md",
|
|
1459
|
+
"**/GEMINI.md",
|
|
1460
|
+
".github/copilot-instructions.md",
|
|
1461
|
+
".github/instructions/**",
|
|
1462
|
+
"**/.cursorrules",
|
|
1463
|
+
"**/.cursor/rules/**",
|
|
1464
|
+
"**/.windsurfrules",
|
|
1465
|
+
"**/.windsurf/rules/**",
|
|
1466
|
+
"**/.clinerules",
|
|
1467
|
+
"**/.clinerules/**",
|
|
1468
|
+
)
|
|
1469
|
+
_TOOL_CONFIG_FILES = _globs(
|
|
1470
|
+
"**/.mcp.json",
|
|
1471
|
+
"**/.claude/**",
|
|
1472
|
+
"**/.codex/**",
|
|
1473
|
+
"**/.vscode/settings.json",
|
|
1474
|
+
"**/.vscode/tasks.json",
|
|
1475
|
+
"**/.vscode/mcp.json",
|
|
1476
|
+
"**/.devcontainer/**",
|
|
1477
|
+
"**/.cursor/**",
|
|
1478
|
+
"**/.gemini/**",
|
|
1479
|
+
"**/.zed/settings.json",
|
|
1480
|
+
)
|
|
1481
|
+
|
|
1482
|
+
|
|
1483
|
+
def _instruction_path(path: str | None) -> bool:
|
|
1484
|
+
return _matches(_INSTRUCTION_FILES, path)
|
|
1485
|
+
|
|
1486
|
+
|
|
1487
|
+
def _tool_config_path(path: str | None) -> bool:
|
|
1488
|
+
return not _instruction_path(path) and _matches(_TOOL_CONFIG_FILES, path)
|
|
1489
|
+
|
|
1490
|
+
|
|
1491
|
+
def _verb(ctx: FileContext) -> str:
|
|
1492
|
+
status = ctx.change.status
|
|
1493
|
+
if status is FileStatus.ADDED:
|
|
1494
|
+
return "added"
|
|
1495
|
+
if status is FileStatus.DELETED:
|
|
1496
|
+
return "deleted"
|
|
1497
|
+
if status is FileStatus.RENAMED:
|
|
1498
|
+
return "renamed"
|
|
1499
|
+
return "changed"
|
|
1500
|
+
|
|
1501
|
+
|
|
1502
|
+
@rule(
|
|
1503
|
+
id="agent/instructions-changed",
|
|
1504
|
+
severity="warning",
|
|
1505
|
+
title="Agent instructions changed",
|
|
1506
|
+
scope="file",
|
|
1507
|
+
rationale=(
|
|
1508
|
+
"Instruction files (AGENTS.md, CLAUDE.md, GEMINI.md, Copilot instructions, Cursor, "
|
|
1509
|
+
"Windsurf and Cline rules) are read by every coding agent and many AI reviewers as "
|
|
1510
|
+
"standing orders. A change to them changes what the next agent does in this "
|
|
1511
|
+
"repository, so a human should read it. Besides the agent-config class of SPEC 5.4 "
|
|
1512
|
+
"this covers AGENT.md, CLAUDE.local.md, .github/instructions/ and .windsurf/rules/."
|
|
1513
|
+
),
|
|
1514
|
+
hint="Read the instruction change as you would read code that runs with your permissions.",
|
|
1515
|
+
tags={"agent", "config"},
|
|
1516
|
+
)
|
|
1517
|
+
def instructions_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
1518
|
+
if _instruction_path(ctx.path) or _instruction_path(ctx.old_path):
|
|
1519
|
+
hit = _change_hit(ctx, f"Agent instruction file {_verb(ctx)}")
|
|
1520
|
+
if hit is not None:
|
|
1521
|
+
yield hit
|
|
1522
|
+
|
|
1523
|
+
|
|
1524
|
+
@rule(
|
|
1525
|
+
id="agent/tool-config-changed",
|
|
1526
|
+
severity="warning",
|
|
1527
|
+
title="Agent tool configuration changed",
|
|
1528
|
+
scope="file",
|
|
1529
|
+
rationale=(
|
|
1530
|
+
"Agent and editor tool settings (.mcp.json, .claude/, .codex/, .vscode/settings.json, "
|
|
1531
|
+
"tasks.json and mcp.json, .devcontainer/, .cursor/, .gemini/, .zed/settings.json) "
|
|
1532
|
+
"decide which tools and MCP servers an agent may start, which commands run without "
|
|
1533
|
+
"asking and what runs when the folder opens. A change to them changes what code runs "
|
|
1534
|
+
"on every developer's machine."
|
|
1535
|
+
),
|
|
1536
|
+
hint="Check every new server, command, hook and permission in the change.",
|
|
1537
|
+
tags={"agent", "config"},
|
|
1538
|
+
)
|
|
1539
|
+
def tool_config_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
1540
|
+
if _tool_config_path(ctx.path) or _tool_config_path(ctx.old_path):
|
|
1541
|
+
hit = _change_hit(ctx, f"Agent tool configuration {_verb(ctx)}")
|
|
1542
|
+
if hit is not None:
|
|
1543
|
+
yield hit
|
|
1544
|
+
|
|
1545
|
+
|
|
1546
|
+
# --- Auto-approval ---------------------------------------------------------------------------
|
|
1547
|
+
|
|
1548
|
+
_JSON_TOKEN = re.compile(
|
|
1549
|
+
r"[ \t\r\n\ufeff]+|//[^\n]*|/\*.*?\*/|\"(?:[^\"\\\n]|\\.)*\"|[{}\[\]:,]"
|
|
1550
|
+
r"|-?[0-9][0-9.eE+-]{0,40}|true|false|null",
|
|
1551
|
+
re.DOTALL,
|
|
1552
|
+
)
|
|
1553
|
+
JsonPath = tuple[str | int, ...]
|
|
1554
|
+
|
|
1555
|
+
|
|
1556
|
+
def _json_leaves(
|
|
1557
|
+
text: str,
|
|
1558
|
+
) -> tuple[list[tuple[JsonPath, object, int]], dict[JsonPath, int]] | None:
|
|
1559
|
+
"""Scalar leaves ``(path, value, line)`` and container start lines of JSON/JSONC text.
|
|
1560
|
+
|
|
1561
|
+
Comments and trailing commas are accepted. ``None`` when the text is not
|
|
1562
|
+
such JSON (or nests deeper than 64 levels).
|
|
1563
|
+
"""
|
|
1564
|
+
index = LineIndex(text)
|
|
1565
|
+
leaves: list[tuple[JsonPath, object, int]] = []
|
|
1566
|
+
starts: dict[JsonPath, int] = {}
|
|
1567
|
+
# Frame: [kind, path, key, count, state]
|
|
1568
|
+
stack: list[list[object]] = []
|
|
1569
|
+
root_done = False
|
|
1570
|
+
pos = 0
|
|
1571
|
+
length = len(text)
|
|
1572
|
+
|
|
1573
|
+
def value_path() -> JsonPath | None:
|
|
1574
|
+
if not stack:
|
|
1575
|
+
return None if root_done else ()
|
|
1576
|
+
kind, path, key, count, state = stack[-1]
|
|
1577
|
+
if state != "value":
|
|
1578
|
+
return None
|
|
1579
|
+
return (*path, key) if kind == "o" else (*path, count) # type: ignore[misc]
|
|
1580
|
+
|
|
1581
|
+
def done() -> None:
|
|
1582
|
+
nonlocal root_done
|
|
1583
|
+
if not stack:
|
|
1584
|
+
root_done = True
|
|
1585
|
+
return
|
|
1586
|
+
top = stack[-1]
|
|
1587
|
+
if top[0] == "a":
|
|
1588
|
+
top[3] = int(top[3]) + 1 # type: ignore[call-overload]
|
|
1589
|
+
top[4] = "comma"
|
|
1590
|
+
|
|
1591
|
+
while pos < length:
|
|
1592
|
+
m = _JSON_TOKEN.match(text, pos)
|
|
1593
|
+
if m is None:
|
|
1594
|
+
return None
|
|
1595
|
+
token = m.group()
|
|
1596
|
+
pos = m.end()
|
|
1597
|
+
first = token[0]
|
|
1598
|
+
if first in " \t\r\n\ufeff" or token.startswith(("//", "/*")):
|
|
1599
|
+
continue
|
|
1600
|
+
if first == '"':
|
|
1601
|
+
try:
|
|
1602
|
+
decoded = json.loads(token)
|
|
1603
|
+
except ValueError:
|
|
1604
|
+
return None
|
|
1605
|
+
if stack and stack[-1][0] == "o" and stack[-1][4] == "key":
|
|
1606
|
+
stack[-1][2] = decoded
|
|
1607
|
+
stack[-1][4] = "colon"
|
|
1608
|
+
continue
|
|
1609
|
+
path = value_path()
|
|
1610
|
+
if path is None:
|
|
1611
|
+
return None
|
|
1612
|
+
leaves.append((path, decoded, index.line_of(m.start())))
|
|
1613
|
+
done()
|
|
1614
|
+
elif first == ":":
|
|
1615
|
+
if not stack or stack[-1][0] != "o" or stack[-1][4] != "colon":
|
|
1616
|
+
return None
|
|
1617
|
+
stack[-1][4] = "value"
|
|
1618
|
+
elif first == ",":
|
|
1619
|
+
if not stack or stack[-1][4] != "comma":
|
|
1620
|
+
return None
|
|
1621
|
+
stack[-1][4] = "key" if stack[-1][0] == "o" else "value"
|
|
1622
|
+
elif first in "{[":
|
|
1623
|
+
path = value_path()
|
|
1624
|
+
if path is None or len(stack) >= 64:
|
|
1625
|
+
return None
|
|
1626
|
+
starts[path] = index.line_of(m.start())
|
|
1627
|
+
stack.append(
|
|
1628
|
+
["o" if first == "{" else "a", path, None, 0, "key" if first == "{" else "value"]
|
|
1629
|
+
)
|
|
1630
|
+
elif first in "}]":
|
|
1631
|
+
if not stack or stack[-1][0] != ("o" if first == "}" else "a"):
|
|
1632
|
+
return None
|
|
1633
|
+
if stack[-1][4] not in ("comma", "key" if first == "}" else "value"):
|
|
1634
|
+
return None
|
|
1635
|
+
stack.pop()
|
|
1636
|
+
done()
|
|
1637
|
+
else:
|
|
1638
|
+
path = value_path()
|
|
1639
|
+
if path is None:
|
|
1640
|
+
return None
|
|
1641
|
+
value: object = {"true": True, "false": False, "null": None}.get(token, token)
|
|
1642
|
+
leaves.append((path, value, index.line_of(m.start())))
|
|
1643
|
+
done()
|
|
1644
|
+
if len(leaves) > 100_000:
|
|
1645
|
+
return None
|
|
1646
|
+
if stack or not root_done:
|
|
1647
|
+
return None
|
|
1648
|
+
return leaves, starts
|
|
1649
|
+
|
|
1650
|
+
|
|
1651
|
+
_CLAUDE_SETTINGS = _globs("**/.claude/settings.json", "**/.claude/settings.local.json")
|
|
1652
|
+
_VSCODE_SETTINGS = _globs("**/.vscode/settings.json", "**/*.code-workspace")
|
|
1653
|
+
_GEMINI_SETTINGS = _globs("**/.gemini/settings.json")
|
|
1654
|
+
_CURSOR_CLI = _globs("**/.cursor/cli.json", "**/.cursor/cli-config.json")
|
|
1655
|
+
_ZED_SETTINGS = _globs("**/.zed/settings.json")
|
|
1656
|
+
_MCP_FILES = _globs(
|
|
1657
|
+
"**/.mcp.json",
|
|
1658
|
+
"**/mcp.json",
|
|
1659
|
+
"**/mcp_settings.json",
|
|
1660
|
+
"**/cline_mcp_settings.json",
|
|
1661
|
+
"**/mcp_config.json",
|
|
1662
|
+
"**/.gemini/settings.json",
|
|
1663
|
+
"**/.claude/settings.json",
|
|
1664
|
+
"**/.claude/settings.local.json",
|
|
1665
|
+
)
|
|
1666
|
+
_CODEX_CONFIG = _globs("**/.codex/*.toml", "**/.codex/**/*.toml")
|
|
1667
|
+
|
|
1668
|
+
_CLAUDE_ALL_BASH = re.compile(r"Bash(?:\(\s*(?::?\*|\*:\*|\*\*)?\s*\))?")
|
|
1669
|
+
_CURSOR_ALL = re.compile(r"Shell\(\s*\*{1,2}(?:\s*:\s*\*)?\s*\)|Mcp\(\s*\*\s*(?::\s*\*\s*)?\)")
|
|
1670
|
+
_CATCH_ALL_PATTERN = frozenset(
|
|
1671
|
+
{"", "*", "**", ".*", ".+", "^.*$", "^.*", ".*$", "^.+$", "[\\s\\S]*"}
|
|
1672
|
+
)
|
|
1673
|
+
|
|
1674
|
+
|
|
1675
|
+
def _catch_all(pattern: str) -> bool:
|
|
1676
|
+
body = pattern.strip()
|
|
1677
|
+
if len(body) >= 2 and body[0] == "/":
|
|
1678
|
+
last = body.rfind("/")
|
|
1679
|
+
body = body[1:last] if last > 0 else body[1:]
|
|
1680
|
+
return body in _CATCH_ALL_PATTERN
|
|
1681
|
+
|
|
1682
|
+
|
|
1683
|
+
def _approvals_in_json(path: str, text: str) -> Iterator[tuple[int, str]]:
|
|
1684
|
+
"""``(line, what)`` for every setting in a JSON settings file that drops human approval.
|
|
1685
|
+
|
|
1686
|
+
Only the settings files named below are read; any other JSON file (data,
|
|
1687
|
+
test vectors) is not walked at all.
|
|
1688
|
+
"""
|
|
1689
|
+
claude = _matches(_CLAUDE_SETTINGS, path)
|
|
1690
|
+
vscode = _matches(_VSCODE_SETTINGS, path)
|
|
1691
|
+
workspace = path.endswith(".code-workspace")
|
|
1692
|
+
gemini = _matches(_GEMINI_SETTINGS, path)
|
|
1693
|
+
cursor = _matches(_CURSOR_CLI, path)
|
|
1694
|
+
zed = _matches(_ZED_SETTINGS, path)
|
|
1695
|
+
mcp = _matches(_MCP_FILES, path) or (
|
|
1696
|
+
path.endswith("/.vscode/mcp.json") or path == ".vscode/mcp.json"
|
|
1697
|
+
)
|
|
1698
|
+
if not (claude or vscode or gemini or cursor or zed or mcp):
|
|
1699
|
+
return
|
|
1700
|
+
parsed = _json_leaves(text)
|
|
1701
|
+
if parsed is None:
|
|
1702
|
+
return
|
|
1703
|
+
leaves, starts = parsed
|
|
1704
|
+
reported_lists: set[JsonPath] = set()
|
|
1705
|
+
for key, value, line in leaves:
|
|
1706
|
+
parts = [str(p) for p in key]
|
|
1707
|
+
if claude:
|
|
1708
|
+
if parts == ["permissions", "defaultMode"] and value == "bypassPermissions":
|
|
1709
|
+
yield line, "Claude Code permissions.defaultMode = bypassPermissions"
|
|
1710
|
+
elif (
|
|
1711
|
+
parts[:2] == ["permissions", "allow"]
|
|
1712
|
+
and isinstance(value, str)
|
|
1713
|
+
and (_CLAUDE_ALL_BASH.fullmatch(value.strip()) or value.strip() == "*")
|
|
1714
|
+
):
|
|
1715
|
+
yield (
|
|
1716
|
+
line,
|
|
1717
|
+
f"Claude Code permissions.allow grants {value.strip()!a} (every command)",
|
|
1718
|
+
)
|
|
1719
|
+
elif parts == ["enableAllProjectMcpServers"] and value is True:
|
|
1720
|
+
yield line, "Claude Code enableAllProjectMcpServers = true"
|
|
1721
|
+
if vscode:
|
|
1722
|
+
flat = parts[1:] if workspace and parts[:1] == ["settings"] else parts
|
|
1723
|
+
dotted = ".".join(flat)
|
|
1724
|
+
if value is True and dotted in (
|
|
1725
|
+
"chat.tools.autoApprove",
|
|
1726
|
+
"chat.tools.global.autoApprove",
|
|
1727
|
+
):
|
|
1728
|
+
yield line, f"VS Code {dotted} = true"
|
|
1729
|
+
for prefix in ("chat.tools.terminal.autoApprove", "chat.tools.urls.autoApprove"):
|
|
1730
|
+
if (
|
|
1731
|
+
value is True
|
|
1732
|
+
and flat[:1] == [prefix]
|
|
1733
|
+
and len(flat) in (2, 3)
|
|
1734
|
+
and flat[2:] in ([], ["approve"], ["approveRequest"])
|
|
1735
|
+
and _catch_all(flat[1])
|
|
1736
|
+
):
|
|
1737
|
+
yield line, f"VS Code {prefix} approves every entry ({flat[1]!a})"
|
|
1738
|
+
if gemini:
|
|
1739
|
+
if parts[:1] == ["mcpServers"] and parts[2:] == ["trust"] and value is True:
|
|
1740
|
+
yield line, f"Gemini CLI MCP server {parts[1]!a} trust = true"
|
|
1741
|
+
elif parts[:2] == ["tools", "allowed"] and value in ("run_shell_command", "ShellTool"):
|
|
1742
|
+
yield line, "Gemini CLI tools.allowed grants every shell command"
|
|
1743
|
+
elif parts == ["general", "defaultApprovalMode"] and value == "yolo":
|
|
1744
|
+
yield line, "Gemini CLI general.defaultApprovalMode = yolo"
|
|
1745
|
+
if (
|
|
1746
|
+
cursor
|
|
1747
|
+
and parts[:2] == ["permissions", "allow"]
|
|
1748
|
+
and isinstance(value, str)
|
|
1749
|
+
and _CURSOR_ALL.fullmatch(value.strip())
|
|
1750
|
+
):
|
|
1751
|
+
yield line, f"Cursor CLI permissions.allow grants {value.strip()!a}"
|
|
1752
|
+
if zed and parts[-1:] == ["always_allow_tool_actions"] and value is True:
|
|
1753
|
+
yield line, "Zed agent.always_allow_tool_actions = true"
|
|
1754
|
+
if mcp and len(parts) >= 3 and parts[0] in ("mcpServers", "servers"):
|
|
1755
|
+
field_name = parts[2]
|
|
1756
|
+
if field_name in ("autoApprove", "alwaysAllow"):
|
|
1757
|
+
list_path = key[:3]
|
|
1758
|
+
if value is True or (len(key) == 4 and list_path not in reported_lists):
|
|
1759
|
+
reported_lists.add(list_path)
|
|
1760
|
+
at = starts.get(list_path, line)
|
|
1761
|
+
yield at, f"MCP server {parts[1]!a} {field_name} skips approval of its tools"
|
|
1762
|
+
elif field_name == "trust" and len(parts) == 3 and value is True and not gemini:
|
|
1763
|
+
yield line, f"MCP server {parts[1]!a} trust = true"
|
|
1764
|
+
|
|
1765
|
+
|
|
1766
|
+
_TOML_HEADER = re.compile(r"[ \t]*\[\[?[ \t]*([^\]\n]{1,200}?)[ \t]*\]\]?[ \t]*(?:#.*)?$")
|
|
1767
|
+
_TOML_PART = r"(?:[A-Za-z0-9_-]{1,100}|\"[^\"\n]{0,100}\")"
|
|
1768
|
+
_TOML_KEY = re.compile(
|
|
1769
|
+
r"[ \t]*(" + _TOML_PART + r"(?:[ \t]*\.[ \t]*" + _TOML_PART + r"){0,10})[ \t]*="
|
|
1770
|
+
)
|
|
1771
|
+
|
|
1772
|
+
|
|
1773
|
+
def _toml_parts(dotted: str) -> tuple[str, ...]:
|
|
1774
|
+
parts: list[str] = []
|
|
1775
|
+
for raw in re.findall(r"\"[^\"]*\"|[^.\s]+", dotted):
|
|
1776
|
+
parts.append(raw[1:-1] if raw.startswith('"') else raw)
|
|
1777
|
+
return tuple(parts)
|
|
1778
|
+
|
|
1779
|
+
|
|
1780
|
+
def _toml_key_lines(lines: Sequence[str]) -> dict[tuple[str, ...], int]:
|
|
1781
|
+
"""First line of every ``key = value`` by full key path (tables and dotted keys)."""
|
|
1782
|
+
found: dict[tuple[str, ...], int] = {}
|
|
1783
|
+
table: tuple[str, ...] = ()
|
|
1784
|
+
arrays: dict[tuple[str, ...], int] = {}
|
|
1785
|
+
depth = 0
|
|
1786
|
+
for number, line in enumerate(lines, start=1):
|
|
1787
|
+
if depth > 0:
|
|
1788
|
+
depth += line.count("[") - line.count("]")
|
|
1789
|
+
continue
|
|
1790
|
+
header = _TOML_HEADER.match(line)
|
|
1791
|
+
if header is not None and not _TOML_KEY.match(line):
|
|
1792
|
+
parts = _toml_parts(header.group(1))
|
|
1793
|
+
if line.lstrip().startswith("[["):
|
|
1794
|
+
arrays[parts] = arrays.get(parts, -1) + 1
|
|
1795
|
+
parts = (*parts[:-1], f"{parts[-1]}[{arrays[parts]}]") if parts else parts
|
|
1796
|
+
table = parts
|
|
1797
|
+
found.setdefault(table, number)
|
|
1798
|
+
continue
|
|
1799
|
+
key = _TOML_KEY.match(line)
|
|
1800
|
+
if key is not None:
|
|
1801
|
+
full = (*table, *_toml_parts(key.group(1)))
|
|
1802
|
+
found.setdefault(full, number)
|
|
1803
|
+
rest = line[key.end() :]
|
|
1804
|
+
depth = max(0, rest.count("[") - rest.count("]"))
|
|
1805
|
+
return found
|
|
1806
|
+
|
|
1807
|
+
|
|
1808
|
+
def _codex_approvals(ctx: FileContext) -> Iterator[tuple[int, str]]:
|
|
1809
|
+
data = ctx.toml
|
|
1810
|
+
if not isinstance(data, dict):
|
|
1811
|
+
return
|
|
1812
|
+
lines = _toml_key_lines(ctx.lines)
|
|
1813
|
+
|
|
1814
|
+
def scope_hits(table: dict[str, object], prefix: tuple[str, ...], inherited: dict[str, object]):
|
|
1815
|
+
approval = table.get("approval_policy", inherited.get("approval_policy"))
|
|
1816
|
+
sandbox = table.get("sandbox_mode", inherited.get("sandbox_mode"))
|
|
1817
|
+
if approval == "never" and sandbox == "danger-full-access":
|
|
1818
|
+
where = "profile " + ".".join(prefix[1:]) if prefix else "the top level"
|
|
1819
|
+
for key in ("approval_policy", "sandbox_mode"):
|
|
1820
|
+
own = (*prefix, key) if key in table else (key,)
|
|
1821
|
+
line = lines.get(own)
|
|
1822
|
+
if line is not None:
|
|
1823
|
+
yield (
|
|
1824
|
+
line,
|
|
1825
|
+
(
|
|
1826
|
+
f"Codex approval_policy = never with sandbox_mode = danger-full-access "
|
|
1827
|
+
f"({where})"
|
|
1828
|
+
),
|
|
1829
|
+
)
|
|
1830
|
+
|
|
1831
|
+
yield from scope_hits(data, (), {})
|
|
1832
|
+
profiles = data.get("profiles")
|
|
1833
|
+
if isinstance(profiles, dict):
|
|
1834
|
+
for name, table in profiles.items():
|
|
1835
|
+
if isinstance(table, dict):
|
|
1836
|
+
yield from scope_hits(table, ("profiles", str(name)), data)
|
|
1837
|
+
|
|
1838
|
+
|
|
1839
|
+
# Flags written in two fragments so this module never matches itself.
|
|
1840
|
+
_FLAG_CLAUDE_SKIP = re.compile(r"(?<![\w-])--dangerously" r"-skip-permissions(?![\w-])")
|
|
1841
|
+
_FLAG_PERMISSION_MODE = re.compile(
|
|
1842
|
+
r"(?<![\w-])--permission-mode(?:=|[ \t]+)[\"']?bypass" r"Permissions\b"
|
|
1843
|
+
)
|
|
1844
|
+
_FLAG_CODEX_BYPASS = re.compile(
|
|
1845
|
+
r"(?<![\w-])--dangerously-bypass" r"-approvals-and-sandbox(?![\w-])"
|
|
1846
|
+
)
|
|
1847
|
+
_FLAG_YOLO = re.compile(r"(?<![\w-])--yo" r"lo(?![\w-])")
|
|
1848
|
+
_FLAG_APPROVAL_MODE = re.compile(r"(?<![\w-])--approval-mode(?:=|[ \t]+)[\"']?yo" r"lo\b")
|
|
1849
|
+
_FLAG_ASK_NEVER = re.compile(r"(?<![\w-])(?:-a|--ask-for-approval)(?:=|[ \t]+)[\"']?never\b")
|
|
1850
|
+
_FLAG_FULL_ACCESS = re.compile(
|
|
1851
|
+
r"(?<![\w-])(?:-s|--sandbox)(?:=|[ \t]+)[\"']?danger-full" r"-access\b"
|
|
1852
|
+
)
|
|
1853
|
+
_FLAG_ALLOWED_TOOLS = re.compile(
|
|
1854
|
+
r"(?<![\w-])--allowed-?[tT]ools(?:=|[ \t]+)(?P<value>[^\n]{0,200})"
|
|
1855
|
+
)
|
|
1856
|
+
_BARE_BASH = re.compile(r"(?<![\w(])Bash(?:\(\s*\*?\s*\))?(?=[\s,\"'\]]|$)")
|
|
1857
|
+
_FLAG_FORCE = re.compile(r"(?<![\w-])(?:--force|-f)(?![\w-])")
|
|
1858
|
+
_AGENT_COMMAND = re.compile(r"(?<![\w-])(?:codex|gemini|qwen|cursor-agent)(?![\w-])")
|
|
1859
|
+
_CURSOR_COMMAND = re.compile(r"(?<![\w-])cursor-agent(?![\w-])")
|
|
1860
|
+
|
|
1861
|
+
|
|
1862
|
+
def _approval_flags(line: str) -> Iterator[tuple[int, str]]:
|
|
1863
|
+
for pattern, what in (
|
|
1864
|
+
(_FLAG_CLAUDE_SKIP, "Claude Code permission prompts skipped"),
|
|
1865
|
+
(_FLAG_PERMISSION_MODE, "Claude Code started in bypassPermissions mode"),
|
|
1866
|
+
(_FLAG_CODEX_BYPASS, "Codex approvals and sandbox bypassed"),
|
|
1867
|
+
(_FLAG_APPROVAL_MODE, "Gemini CLI approval mode yolo"),
|
|
1868
|
+
):
|
|
1869
|
+
m = pattern.search(line)
|
|
1870
|
+
if m is not None:
|
|
1871
|
+
yield m.start(), what
|
|
1872
|
+
m = _FLAG_YOLO.search(line)
|
|
1873
|
+
if m is not None and _AGENT_COMMAND.search(line):
|
|
1874
|
+
yield m.start(), "agent CLI started in yolo mode"
|
|
1875
|
+
m = _FLAG_ASK_NEVER.search(line)
|
|
1876
|
+
if m is not None and _FLAG_FULL_ACCESS.search(line):
|
|
1877
|
+
yield m.start(), "Codex never asks for approval and has full access"
|
|
1878
|
+
m = _FLAG_ALLOWED_TOOLS.search(line)
|
|
1879
|
+
if m is not None and _BARE_BASH.search(m.group("value")):
|
|
1880
|
+
yield m.start(), "Claude Code allowed to run every Bash command"
|
|
1881
|
+
if _CURSOR_COMMAND.search(line):
|
|
1882
|
+
m = _FLAG_FORCE.search(line)
|
|
1883
|
+
if m is not None:
|
|
1884
|
+
yield m.start(), "Cursor CLI forced to run commands without approval"
|
|
1885
|
+
|
|
1886
|
+
|
|
1887
|
+
def _comment_ranges(ctx: FileContext) -> tuple[list[int], list[tuple[int, int]]]:
|
|
1888
|
+
ranges = sorted((c.start, c.end) for c in ctx.comments())
|
|
1889
|
+
return [r[0] for r in ranges], ranges
|
|
1890
|
+
|
|
1891
|
+
|
|
1892
|
+
def _in_ranges(starts: list[int], ranges: list[tuple[int, int]], offset: int) -> bool:
|
|
1893
|
+
k = bisect.bisect_right(starts, offset) - 1
|
|
1894
|
+
return k >= 0 and ranges[k][0] <= offset < ranges[k][1]
|
|
1895
|
+
|
|
1896
|
+
|
|
1897
|
+
@rule(
|
|
1898
|
+
id="agent/auto-approve-enabled",
|
|
1899
|
+
severity="error",
|
|
1900
|
+
title="Agent auto-approval enabled",
|
|
1901
|
+
scope="line",
|
|
1902
|
+
rationale=(
|
|
1903
|
+
"Settings and flags that let a coding agent act without a human approving each step "
|
|
1904
|
+
"turn any instruction it reads (from an issue, a dependency, this change) into code "
|
|
1905
|
+
"that runs. Reported: Claude Code permissions.defaultMode = bypassPermissions, "
|
|
1906
|
+
"permissions.allow entries Bash, Bash(*) or *, and enableAllProjectMcpServers = true "
|
|
1907
|
+
"(.claude/settings*.json); VS Code chat.tools.autoApprove or "
|
|
1908
|
+
"chat.tools.global.autoApprove = true and catch-all chat.tools.terminal.autoApprove "
|
|
1909
|
+
"or urls.autoApprove patterns; MCP server entries with autoApprove or alwaysAllow "
|
|
1910
|
+
"lists or trust = true (.mcp.json, mcp.json, Cline and Gemini settings); Gemini CLI "
|
|
1911
|
+
"tools.allowed run_shell_command; Cursor CLI permissions Shell(*) or Mcp(*:*); Zed "
|
|
1912
|
+
"always_allow_tool_actions; Codex approval_policy = never together with sandbox_mode "
|
|
1913
|
+
"= danger-full-access (.codex/*.toml); and the command-line forms: Claude Code's "
|
|
1914
|
+
"skip-permissions flag, its permission-mode flag set to bypassPermissions and its "
|
|
1915
|
+
"allowed-tools flag listing bare Bash; Codex's approvals-and-sandbox bypass flag, or "
|
|
1916
|
+
"approval never together with the danger-full-access sandbox; the yolo flag of "
|
|
1917
|
+
"codex, gemini and cursor-agent, Gemini's yolo approval mode and cursor-agent's force "
|
|
1918
|
+
"flag, anywhere outside comments and documentation. A flag inside a string literal of "
|
|
1919
|
+
"a test file is a warning: there it is usually test data for a tool like this one."
|
|
1920
|
+
),
|
|
1921
|
+
hint="Keep approvals on in shared settings; run unattended agents only in a disposable "
|
|
1922
|
+
"sandbox configured outside the repository.",
|
|
1923
|
+
tags={"agent", "config", "permissions"},
|
|
1924
|
+
)
|
|
1925
|
+
def auto_approve_enabled(ctx: FileContext) -> Iterator[Hit]:
|
|
1926
|
+
text = ctx.new_text
|
|
1927
|
+
if not text or not ctx.added_lines:
|
|
1928
|
+
return
|
|
1929
|
+
for line, what in _approval_settings(ctx):
|
|
1930
|
+
yield Hit(line, message=f"Auto-approval: {what}", evidence=what)
|
|
1931
|
+
if ctx.language == "markdown" or ctx.file_class == "docs":
|
|
1932
|
+
return
|
|
1933
|
+
if "--" not in text and "-a" not in text:
|
|
1934
|
+
return
|
|
1935
|
+
starts, ranges = _comment_ranges(ctx)
|
|
1936
|
+
if ctx.file_class == "test":
|
|
1937
|
+
literals = sorted((s.start, s.end) for s in ctx.strings())
|
|
1938
|
+
literal_starts = [r[0] for r in literals]
|
|
1939
|
+
else:
|
|
1940
|
+
literals, literal_starts = [], []
|
|
1941
|
+
index = ctx.line_index
|
|
1942
|
+
for number, window in ctx.changed_lines():
|
|
1943
|
+
if "-" not in window:
|
|
1944
|
+
continue
|
|
1945
|
+
base = index.line_start(number) + window.offset
|
|
1946
|
+
for col, what in _approval_flags(window):
|
|
1947
|
+
if _in_ranges(starts, ranges, base + col):
|
|
1948
|
+
continue
|
|
1949
|
+
data = bool(literals) and _in_ranges(literal_starts, literals, base + col)
|
|
1950
|
+
yield Hit(
|
|
1951
|
+
number,
|
|
1952
|
+
column=window.column(col),
|
|
1953
|
+
message=f"Auto-approval: {what}",
|
|
1954
|
+
evidence=what,
|
|
1955
|
+
severity=WARNING if data else None,
|
|
1956
|
+
)
|
|
1957
|
+
|
|
1958
|
+
|
|
1959
|
+
def _approval_settings(ctx: FileContext) -> Iterator[tuple[int, str]]:
|
|
1960
|
+
path = ctx.path
|
|
1961
|
+
text = ctx.new_text or ""
|
|
1962
|
+
if ctx.language in ("json", "jsonc") or path.endswith(".code-workspace"):
|
|
1963
|
+
yield from _approvals_in_json(path, text)
|
|
1964
|
+
elif ctx.language == "toml" and _matches(_CODEX_CONFIG, path):
|
|
1965
|
+
yield from _codex_approvals(ctx)
|
|
1966
|
+
|
|
1967
|
+
|
|
1968
|
+
# --- The reviewer's own configuration ------------------------------------------------------
|
|
1969
|
+
|
|
1970
|
+
_REPO_CONFIG = _config.REPO_CONFIG_NAME
|
|
1971
|
+
|
|
1972
|
+
|
|
1973
|
+
def _is_repo_config(ctx: FileContext) -> bool:
|
|
1974
|
+
return ctx.path == _REPO_CONFIG or ctx.old_path == _REPO_CONFIG
|
|
1975
|
+
|
|
1976
|
+
|
|
1977
|
+
@rule(
|
|
1978
|
+
id="agent/reviewer-config-changed",
|
|
1979
|
+
severity="warning",
|
|
1980
|
+
title="CodeVeto configuration changed",
|
|
1981
|
+
scope="file",
|
|
1982
|
+
rationale=(
|
|
1983
|
+
"The repository .codeveto.toml decides which rules run, how severe they are and what "
|
|
1984
|
+
"is ignored. The review always applies the copy at the trust anchor, never the one in "
|
|
1985
|
+
"the change, so the new settings take effect only after this change merges; a human "
|
|
1986
|
+
"should read them first."
|
|
1987
|
+
),
|
|
1988
|
+
hint="Review the configuration change on its own; agent/reviewer-config-weakened lists "
|
|
1989
|
+
"anything that makes the review less strict.",
|
|
1990
|
+
tags={"agent", "config", "codeveto"},
|
|
1991
|
+
)
|
|
1992
|
+
def reviewer_config_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
1993
|
+
if _is_repo_config(ctx):
|
|
1994
|
+
hit = _change_hit(ctx, f"{_REPO_CONFIG} {_verb(ctx)}")
|
|
1995
|
+
if hit is not None:
|
|
1996
|
+
yield hit
|
|
1997
|
+
|
|
1998
|
+
|
|
1999
|
+
def _key_parts(key: str) -> tuple[str | int, ...]:
|
|
2000
|
+
"""``'ignore[1].paths[0]'`` -> ``('ignore', 1, 'paths', 0)``; quoted parts decoded."""
|
|
2001
|
+
parts: list[str | int] = []
|
|
2002
|
+
for m in re.finditer(r"\"(?:[^\"\\]|\\.){0,300}\"|\[(\d{1,6})\]|[^.\[\]\"]{1,300}", key):
|
|
2003
|
+
token = m.group()
|
|
2004
|
+
if m.group(1) is not None:
|
|
2005
|
+
parts.append(int(m.group(1)))
|
|
2006
|
+
elif token.startswith('"'):
|
|
2007
|
+
try:
|
|
2008
|
+
parts.append(json.loads(token))
|
|
2009
|
+
except ValueError:
|
|
2010
|
+
parts.append(token.strip('"'))
|
|
2011
|
+
else:
|
|
2012
|
+
parts.append(token)
|
|
2013
|
+
return tuple(parts)
|
|
2014
|
+
|
|
2015
|
+
|
|
2016
|
+
_TOML_STRING = re.compile(r"\"(?:[^\"\\\n]|\\.)*\"|'[^'\n]*'")
|
|
2017
|
+
|
|
2018
|
+
|
|
2019
|
+
def _config_locations(lines: Sequence[str]) -> dict[tuple[str | int, ...], int]:
|
|
2020
|
+
"""Lines of tables, keys and string array elements in a small TOML file."""
|
|
2021
|
+
found: dict[tuple[str | int, ...], int] = {}
|
|
2022
|
+
table: tuple[str | int, ...] = ()
|
|
2023
|
+
arrays: dict[tuple[str | int, ...], int] = {}
|
|
2024
|
+
open_array: tuple[str | int, ...] | None = None
|
|
2025
|
+
element = 0
|
|
2026
|
+
depth = 0
|
|
2027
|
+
for number, line in enumerate(lines, start=1):
|
|
2028
|
+
if open_array is not None:
|
|
2029
|
+
for _ in _TOML_STRING.finditer(line):
|
|
2030
|
+
found.setdefault((*open_array, element), number)
|
|
2031
|
+
element += 1
|
|
2032
|
+
depth += line.count("[") - line.count("]")
|
|
2033
|
+
if depth <= 0:
|
|
2034
|
+
open_array = None
|
|
2035
|
+
continue
|
|
2036
|
+
key = _TOML_KEY.match(line)
|
|
2037
|
+
header = None if key is not None else _TOML_HEADER.match(line)
|
|
2038
|
+
if header is not None:
|
|
2039
|
+
parts: tuple[str | int, ...] = _toml_parts(header.group(1))
|
|
2040
|
+
if line.lstrip().startswith("[["):
|
|
2041
|
+
arrays[parts] = arrays.get(parts, -1) + 1
|
|
2042
|
+
parts = (*parts, arrays[parts])
|
|
2043
|
+
table = parts
|
|
2044
|
+
found.setdefault(table, number)
|
|
2045
|
+
continue
|
|
2046
|
+
if key is None:
|
|
2047
|
+
continue
|
|
2048
|
+
full = (*table, *_toml_parts(key.group(1)))
|
|
2049
|
+
found.setdefault(full, number)
|
|
2050
|
+
rest = line[key.end() :]
|
|
2051
|
+
if rest.lstrip().startswith("["):
|
|
2052
|
+
strings = list(_TOML_STRING.finditer(rest))
|
|
2053
|
+
for k in range(len(strings)):
|
|
2054
|
+
found.setdefault((*full, k), number)
|
|
2055
|
+
element = len(strings)
|
|
2056
|
+
depth = rest.count("[") - rest.count("]")
|
|
2057
|
+
if depth > 0:
|
|
2058
|
+
open_array = full
|
|
2059
|
+
return found
|
|
2060
|
+
|
|
2061
|
+
|
|
2062
|
+
@rule(
|
|
2063
|
+
id="agent/reviewer-config-weakened",
|
|
2064
|
+
severity="error",
|
|
2065
|
+
title="CodeVeto configuration weakened",
|
|
2066
|
+
scope="file",
|
|
2067
|
+
rationale=(
|
|
2068
|
+
"A change that makes .codeveto.toml less strict than the anchor's copy (a rule "
|
|
2069
|
+
"disabled or downgraded, an ignore added or widened, fail_on raised, the AI pass "
|
|
2070
|
+
"made optional, a budget lowered, a limit raised or removed, or a file that no longer "
|
|
2071
|
+
"parses) lowers the bar for every later change, including the next one from the same "
|
|
2072
|
+
"author. The comparison is codeveto.config.weakened, the same one the trust model "
|
|
2073
|
+
"uses (SPEC 7.2)."
|
|
2074
|
+
),
|
|
2075
|
+
hint="Make the weakening its own change, approved by the owners of the review policy.",
|
|
2076
|
+
tags={"agent", "config", "codeveto"},
|
|
2077
|
+
)
|
|
2078
|
+
def reviewer_config_weakened(ctx: FileContext) -> Iterator[Hit]:
|
|
2079
|
+
if not _is_repo_config(ctx):
|
|
2080
|
+
return
|
|
2081
|
+
from codeveto.rules import load_rules
|
|
2082
|
+
|
|
2083
|
+
old = ctx.old_text if (ctx.old_path or ctx.path) == _REPO_CONFIG else None
|
|
2084
|
+
new = ctx.new_text if ctx.path == _REPO_CONFIG else None
|
|
2085
|
+
weakenings = _config.weakened(old, new, load_rules())
|
|
2086
|
+
if not weakenings:
|
|
2087
|
+
return
|
|
2088
|
+
if new is None or ctx.change.status is FileStatus.DELETED:
|
|
2089
|
+
details = "; ".join(_short(w.detail, 160) for w in weakenings[:5])
|
|
2090
|
+
more = f" and {len(weakenings) - 5} more" if len(weakenings) > 5 else ""
|
|
2091
|
+
yield Hit(
|
|
2092
|
+
None,
|
|
2093
|
+
message=f"{_REPO_CONFIG} removed: {details}{more}",
|
|
2094
|
+
evidence=",".join(sorted({w.kind for w in weakenings})),
|
|
2095
|
+
)
|
|
2096
|
+
return
|
|
2097
|
+
anchors = _anchors(ctx)
|
|
2098
|
+
if not anchors:
|
|
2099
|
+
if _file_level_ok(ctx):
|
|
2100
|
+
yield Hit(None, message=f"{_REPO_CONFIG} weakened", evidence="weakened")
|
|
2101
|
+
return
|
|
2102
|
+
locations = _config_locations(ctx.lines)
|
|
2103
|
+
groups: dict[int, list[_config.Weakening]] = {}
|
|
2104
|
+
for weakening in weakenings:
|
|
2105
|
+
parts = _key_parts(weakening.key) if weakening.key else ()
|
|
2106
|
+
line = None
|
|
2107
|
+
while parts:
|
|
2108
|
+
line = locations.get(parts)
|
|
2109
|
+
if line is not None:
|
|
2110
|
+
break
|
|
2111
|
+
parts = parts[:-1]
|
|
2112
|
+
anchor = anchors[0] if line is None else _first_anchor_from(anchors, line)
|
|
2113
|
+
groups.setdefault(anchor or anchors[0], []).append(weakening)
|
|
2114
|
+
for anchor, items in sorted(groups.items()):
|
|
2115
|
+
details = "; ".join(_short(w.detail, 160) for w in items[:5])
|
|
2116
|
+
more = f" and {len(items) - 5} more" if len(items) > 5 else ""
|
|
2117
|
+
yield Hit(
|
|
2118
|
+
anchor,
|
|
2119
|
+
message=f"{_REPO_CONFIG} weakened: {details}{more}",
|
|
2120
|
+
evidence=",".join(sorted({f"{w.kind}:{w.key}" for w in items})),
|
|
2121
|
+
)
|
|
2122
|
+
|
|
2123
|
+
|
|
2124
|
+
# --- CodeVeto in workflows, actions, hooks and templates ----------------------------------
|
|
2125
|
+
|
|
2126
|
+
_CV_USES = re.compile(
|
|
2127
|
+
r"(?P<repo>[\w.-]{1,100}/codeveto(?:/[\w./-]{0,200})?)@(?P<ref>[\w./+-]{1,200})", re.I
|
|
2128
|
+
)
|
|
2129
|
+
_CV_COMMAND = re.compile(
|
|
2130
|
+
r"(?:^|(?<=[\s;&|(`'\"/=]))(?:codeveto(?:\.exe)?[\"']?[ \t]+(?:review|hook|verify|publish"
|
|
2131
|
+
r"|mcp|init)(?![\w-])|-m[ \t]+codeveto(?![\w-]))",
|
|
2132
|
+
re.I,
|
|
2133
|
+
)
|
|
2134
|
+
_COMMAND_KEYS = frozenset(
|
|
2135
|
+
{"run", "script", "before_script", "after_script", "entry", "command", "commands", "cmd"}
|
|
2136
|
+
)
|
|
2137
|
+
_UNIT_SKIP_KEYS = frozenset({"name", "description", "uses"})
|
|
2138
|
+
_GUARD_KEYS = frozenset(
|
|
2139
|
+
{
|
|
2140
|
+
"on",
|
|
2141
|
+
"if",
|
|
2142
|
+
"continue-on-error",
|
|
2143
|
+
"allow_failure",
|
|
2144
|
+
"when",
|
|
2145
|
+
"rules",
|
|
2146
|
+
"only",
|
|
2147
|
+
"except",
|
|
2148
|
+
"workflow",
|
|
2149
|
+
"skip",
|
|
2150
|
+
"fail_fast",
|
|
2151
|
+
"default_stages",
|
|
2152
|
+
"stages",
|
|
2153
|
+
"exclude",
|
|
2154
|
+
"files",
|
|
2155
|
+
}
|
|
2156
|
+
)
|
|
2157
|
+
_HOOK_FILES = _globs(
|
|
2158
|
+
".husky/**",
|
|
2159
|
+
".githooks/**",
|
|
2160
|
+
"**/.git-hooks/**",
|
|
2161
|
+
"**/git-hooks/**",
|
|
2162
|
+
"**/hooks/pre-commit",
|
|
2163
|
+
"**/hooks/pre-push",
|
|
2164
|
+
"**/hooks/commit-msg",
|
|
2165
|
+
"**/hooks/pre-merge-commit",
|
|
2166
|
+
"**/hooks/prepare-commit-msg",
|
|
2167
|
+
)
|
|
2168
|
+
|
|
2169
|
+
|
|
2170
|
+
@dataclass(slots=True)
|
|
2171
|
+
class _Unit:
|
|
2172
|
+
identity: tuple[str, ...]
|
|
2173
|
+
node: YamlMap
|
|
2174
|
+
ancestors: list[tuple[tuple[str, ...], YamlMap]]
|
|
2175
|
+
repo: str | None = None
|
|
2176
|
+
ref: str | None = None
|
|
2177
|
+
ref_line: int | None = None
|
|
2178
|
+
|
|
2179
|
+
|
|
2180
|
+
def _scalar_texts(node: YamlNode | None) -> list[YamlScalar]:
|
|
2181
|
+
if isinstance(node, YamlScalar):
|
|
2182
|
+
return [node]
|
|
2183
|
+
if isinstance(node, YamlSeq):
|
|
2184
|
+
return [item for item in node.items if isinstance(item, YamlScalar)]
|
|
2185
|
+
return []
|
|
2186
|
+
|
|
2187
|
+
|
|
2188
|
+
def _invocations(node: YamlNode | None) -> list[tuple[str, int]]:
|
|
2189
|
+
"""Normalized command lines that call CodeVeto, with their file lines."""
|
|
2190
|
+
found: list[tuple[str, int]] = []
|
|
2191
|
+
for scalar in _scalar_texts(node):
|
|
2192
|
+
value = scalar.value
|
|
2193
|
+
offset = 0
|
|
2194
|
+
for part in value.split("\n"):
|
|
2195
|
+
if _CV_COMMAND.search(part):
|
|
2196
|
+
found.append((" ".join(part.split()), scalar.line_of(offset)))
|
|
2197
|
+
offset += len(part) + 1
|
|
2198
|
+
return found
|
|
2199
|
+
|
|
2200
|
+
|
|
2201
|
+
def _mentions_codeveto(node: YamlMap) -> bool:
|
|
2202
|
+
"""Does the mapping's ``id`` or ``name`` contain "codeveto"?"""
|
|
2203
|
+
for key in ("id", "name"):
|
|
2204
|
+
value = node.get(key)
|
|
2205
|
+
if isinstance(value, YamlScalar) and "codeveto" in value.value.lower():
|
|
2206
|
+
return True
|
|
2207
|
+
return False
|
|
2208
|
+
|
|
2209
|
+
|
|
2210
|
+
def _local_unit(path: str, node: YamlMap, local: bool | None, hinted: bool) -> bool:
|
|
2211
|
+
"""Is ``uses: <path>`` (a local action) CodeVeto? See :func:`_local_action`."""
|
|
2212
|
+
rest = path.lstrip(".").strip("/")
|
|
2213
|
+
if rest:
|
|
2214
|
+
return "codeveto" in rest.lower() # ./.github/actions/codeveto and the like
|
|
2215
|
+
if local is not None:
|
|
2216
|
+
return local
|
|
2217
|
+
return hinted or _mentions_codeveto(node)
|
|
2218
|
+
|
|
2219
|
+
|
|
2220
|
+
def _unit_kind(
|
|
2221
|
+
node: YamlMap, local: bool | None, hinted: bool
|
|
2222
|
+
) -> tuple[str | None, str | None, int | None, bool]:
|
|
2223
|
+
"""``(repo, ref, ref line, is a CodeVeto unit)`` of one mapping."""
|
|
2224
|
+
repo = ref = None
|
|
2225
|
+
ref_line = None
|
|
2226
|
+
unit = False
|
|
2227
|
+
for entry in node.entries:
|
|
2228
|
+
key = entry.key_text
|
|
2229
|
+
value = entry.value
|
|
2230
|
+
if key == "uses" and isinstance(value, YamlScalar):
|
|
2231
|
+
target = value.value.strip()
|
|
2232
|
+
m = _CV_USES.fullmatch(target)
|
|
2233
|
+
if m is not None:
|
|
2234
|
+
repo, ref, ref_line, unit = (
|
|
2235
|
+
m.group("repo").lower(),
|
|
2236
|
+
m.group("ref"),
|
|
2237
|
+
value.start_line,
|
|
2238
|
+
True,
|
|
2239
|
+
)
|
|
2240
|
+
elif _LOCAL_USES.fullmatch(target) and _local_unit(target, node, local, hinted):
|
|
2241
|
+
repo, unit = target, True
|
|
2242
|
+
elif (key in _COMMAND_KEYS and _invocations(value)) or (
|
|
2243
|
+
key == "id" and isinstance(value, YamlScalar) and "codeveto" in value.value.lower()
|
|
2244
|
+
):
|
|
2245
|
+
unit = True
|
|
2246
|
+
return repo, ref, ref_line, unit
|
|
2247
|
+
|
|
2248
|
+
|
|
2249
|
+
def _item_identity(node: YamlNode | None) -> str | None:
|
|
2250
|
+
if not isinstance(node, YamlMap):
|
|
2251
|
+
return None
|
|
2252
|
+
for key in ("id", "uses", "repo"):
|
|
2253
|
+
value = node.get(key)
|
|
2254
|
+
if isinstance(value, YamlScalar):
|
|
2255
|
+
text = value.value.strip()
|
|
2256
|
+
if key == "uses":
|
|
2257
|
+
text = text.split("@", 1)[0].lower()
|
|
2258
|
+
return f"{key}={text}"
|
|
2259
|
+
return None
|
|
2260
|
+
|
|
2261
|
+
|
|
2262
|
+
def _collect_units(
|
|
2263
|
+
node: YamlNode | None,
|
|
2264
|
+
identity: tuple[str, ...],
|
|
2265
|
+
ancestors: list[tuple[tuple[str, ...], YamlMap]],
|
|
2266
|
+
out: list[_Unit],
|
|
2267
|
+
local: bool | None,
|
|
2268
|
+
hinted: bool = False,
|
|
2269
|
+
depth: int = 0,
|
|
2270
|
+
) -> bool:
|
|
2271
|
+
"""Collect CodeVeto units below ``node``; return whether any was found.
|
|
2272
|
+
|
|
2273
|
+
``hinted`` says that a mapping above (a job, never the file's root) has
|
|
2274
|
+
"codeveto" in its key, ``id`` or ``name``.
|
|
2275
|
+
"""
|
|
2276
|
+
if depth > 64 or node is None:
|
|
2277
|
+
return False
|
|
2278
|
+
if isinstance(node, YamlMap):
|
|
2279
|
+
if depth > 0 and not hinted:
|
|
2280
|
+
hinted = "codeveto" in identity[-1].lower() or _mentions_codeveto(node)
|
|
2281
|
+
repo, ref, ref_line, is_unit = _unit_kind(node, local, hinted)
|
|
2282
|
+
if is_unit:
|
|
2283
|
+
out.append(_Unit(identity, node, list(ancestors), repo, ref, ref_line))
|
|
2284
|
+
return True
|
|
2285
|
+
chain = [*ancestors, (identity, node)]
|
|
2286
|
+
found = False
|
|
2287
|
+
for entry in node.entries:
|
|
2288
|
+
if entry.value is not None:
|
|
2289
|
+
found |= _collect_units(
|
|
2290
|
+
entry.value,
|
|
2291
|
+
(*identity, entry.key_text),
|
|
2292
|
+
chain,
|
|
2293
|
+
out,
|
|
2294
|
+
local,
|
|
2295
|
+
hinted,
|
|
2296
|
+
depth + 1,
|
|
2297
|
+
)
|
|
2298
|
+
return found
|
|
2299
|
+
if isinstance(node, YamlSeq):
|
|
2300
|
+
found = False
|
|
2301
|
+
ordinal = 0
|
|
2302
|
+
labels: dict[str, int] = {}
|
|
2303
|
+
for item in node.items:
|
|
2304
|
+
before = len(out)
|
|
2305
|
+
label = _item_identity(item)
|
|
2306
|
+
if label is None:
|
|
2307
|
+
label = f"#{ordinal}"
|
|
2308
|
+
elif label in labels: # two steps with the same action: tell them apart
|
|
2309
|
+
labels[label] += 1
|
|
2310
|
+
label = f"{label}#{labels[label]}"
|
|
2311
|
+
else:
|
|
2312
|
+
labels[label] = 0
|
|
2313
|
+
if _collect_units(item, (*identity, label), ancestors, out, local, hinted, depth + 1):
|
|
2314
|
+
found = True
|
|
2315
|
+
if label.startswith("#"):
|
|
2316
|
+
ordinal += 1
|
|
2317
|
+
else:
|
|
2318
|
+
del out[before:]
|
|
2319
|
+
return found
|
|
2320
|
+
return False
|
|
2321
|
+
|
|
2322
|
+
|
|
2323
|
+
def _units(result: YamlResult | None, local: bool | None) -> dict[tuple[str, ...], _Unit]:
|
|
2324
|
+
units: list[_Unit] = []
|
|
2325
|
+
if result is not None:
|
|
2326
|
+
for n, doc in enumerate(result.documents):
|
|
2327
|
+
_collect_units(doc.root, (f"doc{n}",), [], units, local)
|
|
2328
|
+
return {u.identity: u for u in units}
|
|
2329
|
+
|
|
2330
|
+
|
|
2331
|
+
_LOCAL_USES = re.compile(r"\.{1,2}(?:/[\w./-]{0,200})?")
|
|
2332
|
+
_LOCAL_REFERENCE = re.compile(r"uses:[ \t]*[\"']?\.{1,2}(?:/|[\"' \t]|$)", re.MULTILINE)
|
|
2333
|
+
_LOCAL_ACTION_FILES = frozenset({"action.yml", "action.yaml"})
|
|
2334
|
+
|
|
2335
|
+
|
|
2336
|
+
def _declares_codeveto(text: str | None) -> bool:
|
|
2337
|
+
"""Does a root action file declare CodeVeto (its ``name:``, or a CodeVeto command)?"""
|
|
2338
|
+
if not text:
|
|
2339
|
+
return False
|
|
2340
|
+
for line in text.split("\n"):
|
|
2341
|
+
if line.startswith("name:") and "codeveto" in line.lower():
|
|
2342
|
+
return True
|
|
2343
|
+
if _CV_COMMAND.search(line):
|
|
2344
|
+
return True
|
|
2345
|
+
return False
|
|
2346
|
+
|
|
2347
|
+
|
|
2348
|
+
def _local_action(ctx: FileContext) -> bool | None:
|
|
2349
|
+
"""Is ``uses: ./`` the CodeVeto action, as far as the change shows?
|
|
2350
|
+
|
|
2351
|
+
When the change touches the repository's root ``action.yml`` or
|
|
2352
|
+
``action.yaml``, that file decides: either side declaring CodeVeto makes
|
|
2353
|
+
``uses: ./`` a CodeVeto step, and neither side declaring it rules it out.
|
|
2354
|
+
Otherwise ``None``: the caller falls back to the step's ``id`` or
|
|
2355
|
+
``name``, or its job's key or ``name``, containing "codeveto".
|
|
2356
|
+
"""
|
|
2357
|
+
decided: bool | None = None
|
|
2358
|
+
for change in ctx.changeset.files:
|
|
2359
|
+
if change.path in _LOCAL_ACTION_FILES or change.old_path in _LOCAL_ACTION_FILES:
|
|
2360
|
+
if _declares_codeveto(change.old_text) or _declares_codeveto(change.new_text):
|
|
2361
|
+
return True
|
|
2362
|
+
decided = False
|
|
2363
|
+
return decided
|
|
2364
|
+
|
|
2365
|
+
|
|
2366
|
+
def _entry_span(node: YamlMap, key: str) -> tuple[int, int] | None:
|
|
2367
|
+
entry = node.entry(key)
|
|
2368
|
+
if entry is None:
|
|
2369
|
+
return None
|
|
2370
|
+
end = entry.value.end_line if entry.value is not None else entry.key_line
|
|
2371
|
+
return entry.key_line, max(end, entry.key_line)
|
|
2372
|
+
|
|
2373
|
+
|
|
2374
|
+
def _differs(old: YamlMap | None, new: YamlMap | None, key: str) -> bool:
|
|
2375
|
+
a = to_python(old.get(key)) if old is not None and old.entry(key) is not None else _MISSING
|
|
2376
|
+
b = to_python(new.get(key)) if new is not None and new.entry(key) is not None else _MISSING
|
|
2377
|
+
return a != b
|
|
2378
|
+
|
|
2379
|
+
|
|
2380
|
+
_MISSING = object()
|
|
2381
|
+
|
|
2382
|
+
|
|
2383
|
+
def _workflow_hits(ctx: FileContext, local: bool | None) -> Iterator[Hit]:
|
|
2384
|
+
old_units = _units(ctx.old_yaml, local)
|
|
2385
|
+
new_units = _units(ctx.yaml, local)
|
|
2386
|
+
for identity, old_unit in old_units.items():
|
|
2387
|
+
what = "/".join(identity[1:]) or "step"
|
|
2388
|
+
new_unit = new_units.get(identity)
|
|
2389
|
+
if new_unit is None:
|
|
2390
|
+
yield Hit(
|
|
2391
|
+
old_unit.node.start_line,
|
|
2392
|
+
end_line=max(old_unit.node.end_line, old_unit.node.start_line),
|
|
2393
|
+
side=Side.OLD,
|
|
2394
|
+
message=f"CodeVeto step removed ({_short(what, 80)})",
|
|
2395
|
+
evidence=f"removed:{what}",
|
|
2396
|
+
)
|
|
2397
|
+
continue
|
|
2398
|
+
yield from _compare_unit(old_unit, new_unit, what)
|
|
2399
|
+
# Guards above units: the trigger, job conditions, continue-on-error.
|
|
2400
|
+
for identity, new_unit in new_units.items():
|
|
2401
|
+
old_unit = old_units.get(identity)
|
|
2402
|
+
if old_unit is None:
|
|
2403
|
+
continue
|
|
2404
|
+
old_chain = {ident: node for ident, node in old_unit.ancestors}
|
|
2405
|
+
for ident, node in new_unit.ancestors:
|
|
2406
|
+
old_node = old_chain.get(ident)
|
|
2407
|
+
if old_node is None:
|
|
2408
|
+
continue
|
|
2409
|
+
for key in sorted(_GUARD_KEYS):
|
|
2410
|
+
if not _differs(old_node, node, key):
|
|
2411
|
+
continue
|
|
2412
|
+
label = (
|
|
2413
|
+
"trigger"
|
|
2414
|
+
if key in ("on", "workflow")
|
|
2415
|
+
else f"{key} of {'/'.join(ident[1:]) or 'the file'}"
|
|
2416
|
+
)
|
|
2417
|
+
yield from _guard_hit(
|
|
2418
|
+
old_node, node, key, f"CodeVeto {label} changed", what="guard"
|
|
2419
|
+
)
|
|
2420
|
+
|
|
2421
|
+
|
|
2422
|
+
def _guard_hit(old: YamlMap, new: YamlMap, key: str, message: str, *, what: str) -> Iterator[Hit]:
|
|
2423
|
+
span = _entry_span(new, key)
|
|
2424
|
+
if span is not None:
|
|
2425
|
+
yield Hit(
|
|
2426
|
+
span[0],
|
|
2427
|
+
end_line=span[1] if span[1] > span[0] else None,
|
|
2428
|
+
message=message,
|
|
2429
|
+
evidence=f"{what}:{key}",
|
|
2430
|
+
)
|
|
2431
|
+
return
|
|
2432
|
+
span = _entry_span(old, key)
|
|
2433
|
+
if span is not None:
|
|
2434
|
+
yield Hit(
|
|
2435
|
+
span[0],
|
|
2436
|
+
end_line=span[1] if span[1] > span[0] else None,
|
|
2437
|
+
side=Side.OLD,
|
|
2438
|
+
message=message,
|
|
2439
|
+
evidence=f"{what}:{key}",
|
|
2440
|
+
)
|
|
2441
|
+
|
|
2442
|
+
|
|
2443
|
+
def _compare_unit(old: _Unit, new: _Unit, what: str) -> Iterator[Hit]:
|
|
2444
|
+
name = _short(what, 80)
|
|
2445
|
+
if old.ref != new.ref and new.ref_line is not None:
|
|
2446
|
+
yield Hit(
|
|
2447
|
+
new.ref_line,
|
|
2448
|
+
message=f"CodeVeto action version changed ({name})",
|
|
2449
|
+
evidence=f"version:{what}",
|
|
2450
|
+
severity=WARNING,
|
|
2451
|
+
)
|
|
2452
|
+
keys = {e.key_text for e in old.node.entries} | {e.key_text for e in new.node.entries}
|
|
2453
|
+
for key in sorted(keys - _UNIT_SKIP_KEYS):
|
|
2454
|
+
if key in _COMMAND_KEYS:
|
|
2455
|
+
old_calls = _invocations(old.node.get(key))
|
|
2456
|
+
new_calls = _invocations(new.node.get(key))
|
|
2457
|
+
old_set = {c for c, _ in old_calls}
|
|
2458
|
+
new_set = {c for c, _ in new_calls}
|
|
2459
|
+
if old_set == new_set:
|
|
2460
|
+
continue
|
|
2461
|
+
changed = [line for command, line in new_calls if command not in old_set]
|
|
2462
|
+
for line in changed:
|
|
2463
|
+
yield Hit(
|
|
2464
|
+
line, message=f"CodeVeto command changed ({name})", evidence=f"command:{what}"
|
|
2465
|
+
)
|
|
2466
|
+
if not changed: # only removals: report them where they were
|
|
2467
|
+
for command, line in old_calls:
|
|
2468
|
+
if command not in new_set:
|
|
2469
|
+
yield Hit(
|
|
2470
|
+
line,
|
|
2471
|
+
side=Side.OLD,
|
|
2472
|
+
message=f"CodeVeto command removed ({name})",
|
|
2473
|
+
evidence=f"command:{what}",
|
|
2474
|
+
)
|
|
2475
|
+
continue
|
|
2476
|
+
if not _differs(old.node, new.node, key):
|
|
2477
|
+
continue
|
|
2478
|
+
if key == "continue-on-error":
|
|
2479
|
+
message = f"continue-on-error changed on a CodeVeto step ({name})"
|
|
2480
|
+
elif key == "if":
|
|
2481
|
+
message = f"Condition of a CodeVeto step changed ({name})"
|
|
2482
|
+
else:
|
|
2483
|
+
message = f"CodeVeto step input {key} changed ({name})"
|
|
2484
|
+
yield from _guard_hit(old.node, new.node, key, message, what="input")
|
|
2485
|
+
|
|
2486
|
+
|
|
2487
|
+
def _hook_hits(ctx: FileContext) -> Iterator[Hit]:
|
|
2488
|
+
"""Removed or edited CodeVeto command lines in a Git hook script."""
|
|
2489
|
+
new_lines = {" ".join(line.split()) for line in ctx.lines if _CV_COMMAND.search(line)}
|
|
2490
|
+
for number, line in ctx.changed_lines(Side.OLD):
|
|
2491
|
+
if not line.at_line_start or not _CV_COMMAND.search(line):
|
|
2492
|
+
continue
|
|
2493
|
+
if " ".join(ctx.old_lines[number - 1].split()) not in new_lines:
|
|
2494
|
+
yield Hit(
|
|
2495
|
+
number,
|
|
2496
|
+
side=Side.OLD,
|
|
2497
|
+
message="CodeVeto hook command removed or changed",
|
|
2498
|
+
evidence="hook:" + _short(ctx.old_lines[number - 1], 80),
|
|
2499
|
+
)
|
|
2500
|
+
|
|
2501
|
+
|
|
2502
|
+
@rule(
|
|
2503
|
+
id="agent/codeveto-workflow-changed",
|
|
2504
|
+
severity="error",
|
|
2505
|
+
title="CodeVeto gate changed",
|
|
2506
|
+
scope="file",
|
|
2507
|
+
rationale=(
|
|
2508
|
+
"Workflows, composite actions, hook configurations, hook scripts and templates that "
|
|
2509
|
+
"run CodeVeto (uses: <owner>/codeveto@<ref>, 'codeveto review', 'python -m codeveto') "
|
|
2510
|
+
"are the gate itself. Removing a CodeVeto step, changing its inputs (fail-on, ai, "
|
|
2511
|
+
"comment, package, ...), its command line, its trigger or the condition of its job, "
|
|
2512
|
+
"or adding continue-on-error, lets later changes through unreviewed. A step matches "
|
|
2513
|
+
"its counterpart by id, action repository or position among CodeVeto steps, so "
|
|
2514
|
+
"renaming a step is not a change; moving the action to another repository is a "
|
|
2515
|
+
"removal. A changed action version alone is a warning. A local action (uses: ./) is "
|
|
2516
|
+
"CodeVeto when the change touches the root action.yml or action.yaml and either side "
|
|
2517
|
+
"of it declares CodeVeto (its name or a CodeVeto command); when the change leaves "
|
|
2518
|
+
"that file alone, when the step's id or name, or its job's key or name, contains "
|
|
2519
|
+
"'codeveto' (a heuristic). uses: ./<dir> counts when <dir> contains 'codeveto'."
|
|
2520
|
+
),
|
|
2521
|
+
hint="Change the CodeVeto gate in its own pull request, approved by the owners of CI.",
|
|
2522
|
+
tags={"agent", "ci", "codeveto"},
|
|
2523
|
+
)
|
|
2524
|
+
def codeveto_workflow_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
2525
|
+
old_text, new_text = ctx.old_text or "", ctx.new_text or ""
|
|
2526
|
+
if ctx.change.status is FileStatus.ADDED:
|
|
2527
|
+
return
|
|
2528
|
+
local = _local_action(ctx) if _LOCAL_REFERENCE.search(old_text) else None
|
|
2529
|
+
|
|
2530
|
+
def relevant(text: str) -> bool:
|
|
2531
|
+
if "codeveto" in text.lower():
|
|
2532
|
+
return True
|
|
2533
|
+
return local is True and _LOCAL_REFERENCE.search(text) is not None
|
|
2534
|
+
|
|
2535
|
+
if not relevant(old_text):
|
|
2536
|
+
return
|
|
2537
|
+
if ctx.language == "yaml":
|
|
2538
|
+
for side, result in (("old", ctx.old_yaml), ("new", ctx.yaml)):
|
|
2539
|
+
text = old_text if side == "old" else new_text
|
|
2540
|
+
if result is not None and not result.ok and relevant(text):
|
|
2541
|
+
raise PartialCoverage(
|
|
2542
|
+
"YAML could not be read fully, so CodeVeto steps were not compared"
|
|
2543
|
+
)
|
|
2544
|
+
yield from _workflow_hits(ctx, local)
|
|
2545
|
+
elif _either_path(ctx, _HOOK_FILES):
|
|
2546
|
+
yield from _hook_hits(ctx)
|
|
2547
|
+
|
|
2548
|
+
|
|
2549
|
+
# --- What reviewers are shown: owners, attributes, ignore rules -----------------------------
|
|
2550
|
+
|
|
2551
|
+
_CODEOWNERS = _globs(
|
|
2552
|
+
"CODEOWNERS",
|
|
2553
|
+
".github/CODEOWNERS",
|
|
2554
|
+
"docs/CODEOWNERS",
|
|
2555
|
+
".gitlab/CODEOWNERS",
|
|
2556
|
+
".gitea/CODEOWNERS",
|
|
2557
|
+
".forgejo/CODEOWNERS",
|
|
2558
|
+
)
|
|
2559
|
+
|
|
2560
|
+
|
|
2561
|
+
def _rule_lines(lines: Iterable[str]) -> int:
|
|
2562
|
+
return sum(1 for line in lines if line.strip() and not line.lstrip().startswith("#"))
|
|
2563
|
+
|
|
2564
|
+
|
|
2565
|
+
def _counts(ctx: FileContext) -> str:
|
|
2566
|
+
added = _rule_lines(ctx.lines[n - 1] for n in ctx.added_lines if n <= len(ctx.lines))
|
|
2567
|
+
removed = _rule_lines(
|
|
2568
|
+
ctx.old_lines[n - 1] for n in ctx.removed_lines if n <= len(ctx.old_lines)
|
|
2569
|
+
)
|
|
2570
|
+
return f"{added} rule line(s) added, {removed} removed"
|
|
2571
|
+
|
|
2572
|
+
|
|
2573
|
+
@rule(
|
|
2574
|
+
id="agent/codeowners-changed",
|
|
2575
|
+
severity="warning",
|
|
2576
|
+
title="CODEOWNERS changed",
|
|
2577
|
+
scope="file",
|
|
2578
|
+
rationale=(
|
|
2579
|
+
"CODEOWNERS decides whose approval a change needs. Removing an owner, adding a broad "
|
|
2580
|
+
"pattern or moving a path out of a team's ownership changes who must look at future "
|
|
2581
|
+
"changes, including changes to the workflows and review settings."
|
|
2582
|
+
),
|
|
2583
|
+
hint="Have the current owners of the affected paths approve the ownership change.",
|
|
2584
|
+
tags={"agent", "governance"},
|
|
2585
|
+
)
|
|
2586
|
+
def codeowners_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
2587
|
+
if _either_path(ctx, _CODEOWNERS):
|
|
2588
|
+
hit = _change_hit(ctx, f"CODEOWNERS {_verb(ctx)}: {_counts(ctx)}")
|
|
2589
|
+
if hit is not None:
|
|
2590
|
+
yield hit
|
|
2591
|
+
|
|
2592
|
+
|
|
2593
|
+
_GITATTRIBUTES = _globs("**/.gitattributes")
|
|
2594
|
+
_HIDING = re.compile(
|
|
2595
|
+
r"(?:linguist-generated|linguist-vendored)(?:=(?:true|1|yes|set))?|-diff|binary"
|
|
2596
|
+
)
|
|
2597
|
+
_ASSET_EXTENSIONS = frozenset(
|
|
2598
|
+
{
|
|
2599
|
+
"png",
|
|
2600
|
+
"jpg",
|
|
2601
|
+
"jpeg",
|
|
2602
|
+
"gif",
|
|
2603
|
+
"bmp",
|
|
2604
|
+
"ico",
|
|
2605
|
+
"icns",
|
|
2606
|
+
"webp",
|
|
2607
|
+
"avif",
|
|
2608
|
+
"tif",
|
|
2609
|
+
"tiff",
|
|
2610
|
+
"psd",
|
|
2611
|
+
"ai",
|
|
2612
|
+
"eps",
|
|
2613
|
+
"pdf",
|
|
2614
|
+
"svg",
|
|
2615
|
+
"mp3",
|
|
2616
|
+
"mp4",
|
|
2617
|
+
"m4a",
|
|
2618
|
+
"wav",
|
|
2619
|
+
"ogg",
|
|
2620
|
+
"flac",
|
|
2621
|
+
"mov",
|
|
2622
|
+
"avi",
|
|
2623
|
+
"mkv",
|
|
2624
|
+
"webm",
|
|
2625
|
+
"zip",
|
|
2626
|
+
"gz",
|
|
2627
|
+
"tgz",
|
|
2628
|
+
"bz2",
|
|
2629
|
+
"xz",
|
|
2630
|
+
"7z",
|
|
2631
|
+
"rar",
|
|
2632
|
+
"tar",
|
|
2633
|
+
"jar",
|
|
2634
|
+
"war",
|
|
2635
|
+
"ear",
|
|
2636
|
+
"whl",
|
|
2637
|
+
"egg",
|
|
2638
|
+
"crate",
|
|
2639
|
+
"age",
|
|
2640
|
+
"gpg",
|
|
2641
|
+
"gem",
|
|
2642
|
+
"nupkg",
|
|
2643
|
+
"woff",
|
|
2644
|
+
"woff2",
|
|
2645
|
+
"ttf",
|
|
2646
|
+
"otf",
|
|
2647
|
+
"eot",
|
|
2648
|
+
"exe",
|
|
2649
|
+
"dll",
|
|
2650
|
+
"so",
|
|
2651
|
+
"dylib",
|
|
2652
|
+
"a",
|
|
2653
|
+
"o",
|
|
2654
|
+
"obj",
|
|
2655
|
+
"lib",
|
|
2656
|
+
"bin",
|
|
2657
|
+
"dat",
|
|
2658
|
+
"db",
|
|
2659
|
+
"sqlite",
|
|
2660
|
+
"sqlite3",
|
|
2661
|
+
"wasm",
|
|
2662
|
+
"pyc",
|
|
2663
|
+
"pyo",
|
|
2664
|
+
"class",
|
|
2665
|
+
"dex",
|
|
2666
|
+
"apk",
|
|
2667
|
+
"ipa",
|
|
2668
|
+
"dmg",
|
|
2669
|
+
"iso",
|
|
2670
|
+
"lock",
|
|
2671
|
+
"snap",
|
|
2672
|
+
"map",
|
|
2673
|
+
"pbxproj",
|
|
2674
|
+
}
|
|
2675
|
+
)
|
|
2676
|
+
_GENERATED_CLASSES = frozenset({"generated", "vendored", "minified", "lockfile"})
|
|
2677
|
+
|
|
2678
|
+
|
|
2679
|
+
def _attribute_tokens(line: str) -> tuple[str, list[str]] | None:
|
|
2680
|
+
stripped = line.strip()
|
|
2681
|
+
if not stripped or stripped.startswith("#"):
|
|
2682
|
+
return None
|
|
2683
|
+
if stripped.startswith('"'):
|
|
2684
|
+
close = stripped.find('"', 1)
|
|
2685
|
+
if close < 0:
|
|
2686
|
+
return None
|
|
2687
|
+
return stripped[1:close], stripped[close + 1 :].split()
|
|
2688
|
+
parts = stripped.split()
|
|
2689
|
+
return parts[0], parts[1:]
|
|
2690
|
+
|
|
2691
|
+
|
|
2692
|
+
def _generated_pattern(pattern: str) -> bool:
|
|
2693
|
+
"""Does a gitattributes pattern name only generated, vendored, lock or binary files?"""
|
|
2694
|
+
probe = re.sub(r"\[[^\]]{0,50}\]", "x", pattern.lstrip("/"))
|
|
2695
|
+
probe = probe.replace("**", "x").replace("*", "x").replace("?", "x")
|
|
2696
|
+
if probe.endswith("/"):
|
|
2697
|
+
probe += "x"
|
|
2698
|
+
name = probe.rsplit("/", 1)[-1].lower()
|
|
2699
|
+
ext = name.rsplit(".", 1)[-1] if "." in name else ""
|
|
2700
|
+
if ext in _ASSET_EXTENSIONS or name.endswith((".min.css", ".min.js")):
|
|
2701
|
+
return True
|
|
2702
|
+
for candidate in (probe, f"x/{probe}"):
|
|
2703
|
+
if classify(candidate).file_class in _GENERATED_CLASSES:
|
|
2704
|
+
return True
|
|
2705
|
+
return False
|
|
2706
|
+
|
|
2707
|
+
|
|
2708
|
+
@rule(
|
|
2709
|
+
id="agent/gitattributes-changed",
|
|
2710
|
+
severity="error",
|
|
2711
|
+
title=".gitattributes changed",
|
|
2712
|
+
scope="line",
|
|
2713
|
+
rationale=(
|
|
2714
|
+
".gitattributes changes how forges and tools show files. Marking paths "
|
|
2715
|
+
"linguist-generated or linguist-vendored collapses their diffs in pull requests, and "
|
|
2716
|
+
"-diff or binary hides their content from git diff, so a reviewer never sees what "
|
|
2717
|
+
"changed there: an error unless the pattern names only generated, vendored, lock, "
|
|
2718
|
+
"minified or binary asset files. Any other added or removed attribute line is a "
|
|
2719
|
+
"warning."
|
|
2720
|
+
),
|
|
2721
|
+
hint="Keep source paths visible in diffs; mark only build output and assets as generated.",
|
|
2722
|
+
tags={"agent", "governance"},
|
|
2723
|
+
)
|
|
2724
|
+
def gitattributes_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
2725
|
+
if not _matches(_GITATTRIBUTES, ctx.path):
|
|
2726
|
+
return
|
|
2727
|
+
for number, window in ctx.changed_lines():
|
|
2728
|
+
if not window.at_line_start:
|
|
2729
|
+
continue
|
|
2730
|
+
parsed = _attribute_tokens(ctx.lines[number - 1])
|
|
2731
|
+
if parsed is None:
|
|
2732
|
+
continue
|
|
2733
|
+
pattern, attrs = parsed
|
|
2734
|
+
hiding = [a for a in attrs if _HIDING.fullmatch(a)]
|
|
2735
|
+
evidence = " ".join(ctx.lines[number - 1].split())
|
|
2736
|
+
if hiding and not pattern.startswith("[attr]") and not _generated_pattern(pattern):
|
|
2737
|
+
yield Hit(
|
|
2738
|
+
number,
|
|
2739
|
+
message=f"{', '.join(hiding)} on {_short(pattern, 60)} hides changes from review",
|
|
2740
|
+
evidence=evidence,
|
|
2741
|
+
)
|
|
2742
|
+
else:
|
|
2743
|
+
yield Hit(
|
|
2744
|
+
number,
|
|
2745
|
+
message="Attribute rule added or changed",
|
|
2746
|
+
evidence=evidence,
|
|
2747
|
+
severity=WARNING,
|
|
2748
|
+
)
|
|
2749
|
+
new_lines = {" ".join(line.split()) for line in ctx.lines}
|
|
2750
|
+
pure = {n for h in ctx.change.hunks if h.new_count == 0 for n in h.old_lines}
|
|
2751
|
+
for number, window in ctx.changed_lines(Side.OLD):
|
|
2752
|
+
if not window.at_line_start or number not in pure:
|
|
2753
|
+
continue # a replaced line is reported on its new side
|
|
2754
|
+
old = ctx.old_lines[number - 1]
|
|
2755
|
+
if _attribute_tokens(old) is None or " ".join(old.split()) in new_lines:
|
|
2756
|
+
continue
|
|
2757
|
+
yield Hit(
|
|
2758
|
+
number,
|
|
2759
|
+
side=Side.OLD,
|
|
2760
|
+
message="Attribute rule removed",
|
|
2761
|
+
evidence=" ".join(old.split()),
|
|
2762
|
+
severity=WARNING,
|
|
2763
|
+
)
|
|
2764
|
+
|
|
2765
|
+
|
|
2766
|
+
_GITIGNORE = _globs("**/.gitignore")
|
|
2767
|
+
|
|
2768
|
+
|
|
2769
|
+
@rule(
|
|
2770
|
+
id="agent/ignore-rules-changed",
|
|
2771
|
+
severity="warning",
|
|
2772
|
+
title="Ignore rules changed",
|
|
2773
|
+
scope="file",
|
|
2774
|
+
rationale=(
|
|
2775
|
+
".gitignore decides which files Git, editors and agents treat as absent. A changed "
|
|
2776
|
+
"rule can hide a new file from 'git status' and from tools that honour it; worktree "
|
|
2777
|
+
"reviews use the anchor's ignore rules and still review such files, flagged "
|
|
2778
|
+
"ignored-locally, which this rule also reports."
|
|
2779
|
+
),
|
|
2780
|
+
hint="Check that no source, configuration or credential path becomes ignored or "
|
|
2781
|
+
"un-ignored by accident.",
|
|
2782
|
+
tags={"agent", "governance"},
|
|
2783
|
+
)
|
|
2784
|
+
def ignore_rules_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
2785
|
+
if _either_path(ctx, _GITIGNORE):
|
|
2786
|
+
hit = _change_hit(ctx, f".gitignore {_verb(ctx)}: {_counts(ctx)}")
|
|
2787
|
+
if hit is not None:
|
|
2788
|
+
yield hit
|
|
2789
|
+
if FLAG_IGNORED_LOCALLY in ctx.flags:
|
|
2790
|
+
hit = _change_hit(
|
|
2791
|
+
ctx, "File hidden by a local ignore rule the anchor does not have", "ignored-locally"
|
|
2792
|
+
)
|
|
2793
|
+
if hit is not None:
|
|
2794
|
+
yield hit
|
|
2795
|
+
|
|
2796
|
+
|
|
2797
|
+
# --- Suppression comments ------------------------------------------------------------------
|
|
2798
|
+
|
|
2799
|
+
_SUPPRESSION = re.compile(
|
|
2800
|
+
r"(?<![\w-])(?:codeveto-ignore|noqa|nosec|nosemgrep|nosonar|type:[ \t]?ignore"
|
|
2801
|
+
r"|pyright:[ \t]?ignore|pyre-(?:ignore|fixme)|pylint:[ \t]?disable(?:-next)?"
|
|
2802
|
+
r"|mypy:[ \t]?ignore-errors|eslint-disable(?:-next-line|-line)?|@ts-(?:ignore|expect-error"
|
|
2803
|
+
r"|nocheck)|biome-ignore(?:-all|-start)?|deno-lint-ignore(?:-file)?"
|
|
2804
|
+
r"|oxlint-disable(?:-next-line|-line)?|jshint[ \t]ignore|nolint|lint:(?:ignore|file-ignore)"
|
|
2805
|
+
r"|shellcheck[ \t]+disable|hadolint[ \t]+ignore|checkov:skip|tfsec:ignore|trivy:ignore"
|
|
2806
|
+
r"|gitleaks:allow|pragma:[ \t]?allowlist[ \t]+secret|yamllint[ \t]+disable)(?![\w-])",
|
|
2807
|
+
re.IGNORECASE,
|
|
2808
|
+
)
|
|
2809
|
+
_QUIET_SUPPRESSION_CLASSES = frozenset({"test", "docs", "generated", "vendored", "minified"})
|
|
2810
|
+
_NAMING_LINTS = frozenset({"non_snake_case", "non_camel_case_types", "non_upper_case_globals"})
|
|
2811
|
+
|
|
2812
|
+
|
|
2813
|
+
def _naming_only(lints: str) -> bool:
|
|
2814
|
+
"""Does a Rust ``allow(...)`` list (the text inside the parentheses) name only naming lints?"""
|
|
2815
|
+
names = [n.strip() for n in lints.split(",") if n.strip()]
|
|
2816
|
+
return bool(names) and all(n in _NAMING_LINTS for n in names)
|
|
2817
|
+
|
|
2818
|
+
|
|
2819
|
+
_BROAD_ANNOTATION = re.compile(
|
|
2820
|
+
r"^#[ \t]*!|^@file:|\b(?:warnings|clippy::all|clippy::pedantic|clippy::restriction)\b"
|
|
2821
|
+
r"|\"all\""
|
|
2822
|
+
)
|
|
2823
|
+
"""Classes where a suppression comment with no finding next to it is only a note."""
|
|
2824
|
+
_CODE_SUPPRESSION = {
|
|
2825
|
+
"rust": re.compile(r"#!?\[[ \t]*allow[ \t]*\("),
|
|
2826
|
+
"java": re.compile(r"@SuppressWarnings[ \t]*\("),
|
|
2827
|
+
"kotlin": re.compile(r"@(?:file:)?Suppress(?:Warnings)?[ \t]*\("),
|
|
2828
|
+
}
|
|
2829
|
+
|
|
2830
|
+
|
|
2831
|
+
@rule(
|
|
2832
|
+
id="agent/suppression-added",
|
|
2833
|
+
severity="error",
|
|
2834
|
+
title="Suppression added",
|
|
2835
|
+
scope="line",
|
|
2836
|
+
rationale=(
|
|
2837
|
+
"A suppression comment switches a check off for the code next to it. When it sits "
|
|
2838
|
+
"next to a CodeVeto finding, the engine reports this rule at that finding's severity "
|
|
2839
|
+
"(the ignore is not applied, SPEC 7.3). Every other added or edited suppression "
|
|
2840
|
+
"(codeveto-ignore, noqa, type: ignore, pyright: ignore, eslint-disable, @ts-ignore, "
|
|
2841
|
+
"@ts-expect-error, @ts-nocheck, nolint, shellcheck disable, NOSONAR, nosec, "
|
|
2842
|
+
"gitleaks:allow and similar, plus Rust #[allow(...)] and Java/Kotlin @Suppress "
|
|
2843
|
+
"annotations) is a warning: once merged, an unchanged ignore can waive later "
|
|
2844
|
+
"changes to the same line. It is a note for a comment in a test, documentation, "
|
|
2845
|
+
"generated, vendored or minified file, and for an annotation that names specific "
|
|
2846
|
+
"lints on one item, which code bases use on purpose and densely (10 per 1,000 lines "
|
|
2847
|
+
"of Cargo registry crates; rust/allow-attribute also shows each Rust one), and a Rust "
|
|
2848
|
+
"allow of naming lints only (non_snake_case, non_camel_case_types, "
|
|
2849
|
+
"non_upper_case_globals: FFI bindings keep C's names) is not reported. "
|
|
2850
|
+
"codeveto-ignore, and module- or file-wide or catch-all annotations (#![allow], "
|
|
2851
|
+
'@file:Suppress, warnings, clippy::all, "all"), stay warnings.'
|
|
2852
|
+
),
|
|
2853
|
+
hint="Fix the finding instead, or record a reviewed exception in the trusted config.",
|
|
2854
|
+
tags={"agent", "suppression"},
|
|
2855
|
+
)
|
|
2856
|
+
def suppression_added(ctx: FileContext) -> Iterator[Hit]:
|
|
2857
|
+
text = ctx.new_text
|
|
2858
|
+
if not text or not ctx.added_lines:
|
|
2859
|
+
return
|
|
2860
|
+
index = ctx.line_index
|
|
2861
|
+
added = ctx.added_lines
|
|
2862
|
+
reported: set[int] = set()
|
|
2863
|
+
quiet = ctx.file_class in _QUIET_SUPPRESSION_CLASSES
|
|
2864
|
+
for comment in ctx.comments():
|
|
2865
|
+
content = text[comment.content_start : comment.content_end]
|
|
2866
|
+
for m in _SUPPRESSION.finditer(content):
|
|
2867
|
+
offset = comment.content_start + m.start()
|
|
2868
|
+
line = index.line_of(offset)
|
|
2869
|
+
if line not in added or line in reported:
|
|
2870
|
+
continue
|
|
2871
|
+
reported.add(line)
|
|
2872
|
+
tail = content[m.start() : m.start() + 80].split("--", 1)[0]
|
|
2873
|
+
directive = " ".join(tail.split()).lower()
|
|
2874
|
+
own = directive.startswith("codeveto-ignore")
|
|
2875
|
+
yield Hit(
|
|
2876
|
+
line,
|
|
2877
|
+
column=offset - index.line_start(line) + 1,
|
|
2878
|
+
message=f"Suppression comment: {_short(m.group(), 40)}",
|
|
2879
|
+
evidence=directive,
|
|
2880
|
+
severity=NOTE if quiet and not own else WARNING,
|
|
2881
|
+
)
|
|
2882
|
+
pattern = _CODE_SUPPRESSION.get(ctx.language)
|
|
2883
|
+
if pattern is None:
|
|
2884
|
+
return
|
|
2885
|
+
masked = ctx.masked_code
|
|
2886
|
+
for number, window in ctx.changed_lines():
|
|
2887
|
+
if number in reported:
|
|
2888
|
+
continue
|
|
2889
|
+
start = index.line_start(number) + window.offset
|
|
2890
|
+
code = masked[start : start + len(window)]
|
|
2891
|
+
m = pattern.search(code)
|
|
2892
|
+
if m is not None:
|
|
2893
|
+
close = window.find(")", m.end())
|
|
2894
|
+
evidence = window[m.start() : close + 1 if close >= 0 else m.end() + 60]
|
|
2895
|
+
evidence = " ".join(evidence.split())
|
|
2896
|
+
if ctx.language == "rust" and close >= 0 and _naming_only(window[m.end() : close]):
|
|
2897
|
+
continue
|
|
2898
|
+
yield Hit(
|
|
2899
|
+
number,
|
|
2900
|
+
column=window.column(m.start()),
|
|
2901
|
+
message=f"Suppression attribute: {_short(m.group(), 40)}",
|
|
2902
|
+
evidence=evidence,
|
|
2903
|
+
severity=WARNING if _BROAD_ANNOTATION.search(evidence) else NOTE,
|
|
2904
|
+
)
|
|
2905
|
+
|
|
2906
|
+
|
|
2907
|
+
# --- Encoded payloads ---------------------------------------------------------------------
|
|
2908
|
+
|
|
2909
|
+
_BASE64_RUN = re.compile(r"(?<![A-Za-z0-9+/_-])[A-Za-z0-9+/_-]{120,4000}={0,2}")
|
|
2910
|
+
_HEX_RUN = re.compile(r"(?<![0-9A-Fa-f])(?:[0-9A-Fa-f]{2}){64,2000}(?![0-9A-Fa-f])")
|
|
2911
|
+
_ESCAPE_RUN = re.compile(r"(?:\\x[0-9A-Fa-f]{2}){24,1000}")
|
|
2912
|
+
|
|
2913
|
+
|
|
2914
|
+
def _readable(data: bytes) -> bool:
|
|
2915
|
+
"""Does ``data`` decode to natural text (words and spaces), not binary or a token?"""
|
|
2916
|
+
try:
|
|
2917
|
+
decoded = data.decode("utf-8")
|
|
2918
|
+
except UnicodeDecodeError:
|
|
2919
|
+
return False
|
|
2920
|
+
if not decoded:
|
|
2921
|
+
return False
|
|
2922
|
+
printable = sum(1 for c in decoded if c.isprintable() or c in "\n\t")
|
|
2923
|
+
spaces = decoded.count(" ") + decoded.count("\n")
|
|
2924
|
+
return printable >= 0.95 * len(decoded) and spaces >= max(3, len(decoded) // 40)
|
|
2925
|
+
|
|
2926
|
+
|
|
2927
|
+
def _decoded_payloads(window: str) -> Iterator[tuple[int, str, str]]:
|
|
2928
|
+
for m in _BASE64_RUN.finditer(window):
|
|
2929
|
+
run = m.group().rstrip("=")
|
|
2930
|
+
if not (re.search(r"[a-z]", run) and re.search(r"[A-Z]", run) and re.search(r"[0-9]", run)):
|
|
2931
|
+
continue
|
|
2932
|
+
alphabet = run.replace("-", "+").replace("_", "/")
|
|
2933
|
+
try:
|
|
2934
|
+
data = binascii.a2b_base64(alphabet + "=" * (-len(alphabet) % 4))
|
|
2935
|
+
except (binascii.Error, ValueError):
|
|
2936
|
+
continue
|
|
2937
|
+
if _readable(data):
|
|
2938
|
+
yield m.start(), "base64", m.group()
|
|
2939
|
+
for m in _HEX_RUN.finditer(window):
|
|
2940
|
+
if _readable(bytes.fromhex(m.group())):
|
|
2941
|
+
yield m.start(), "hex", m.group()
|
|
2942
|
+
for m in _ESCAPE_RUN.finditer(window):
|
|
2943
|
+
data = bytes(int(m.group()[k + 2 : k + 4], 16) for k in range(0, len(m.group()), 4))
|
|
2944
|
+
if _readable(data):
|
|
2945
|
+
yield m.start(), "\\x-escaped", m.group()
|
|
2946
|
+
|
|
2947
|
+
|
|
2948
|
+
@rule(
|
|
2949
|
+
id="agent/encoded-payload",
|
|
2950
|
+
severity="note",
|
|
2951
|
+
title="Encoded text payload",
|
|
2952
|
+
scope="line",
|
|
2953
|
+
rationale=(
|
|
2954
|
+
"A long base64, hex or \\x-escaped run that decodes to readable text hides that text "
|
|
2955
|
+
"from reviewers and from text-based checks, while a model or a program can still "
|
|
2956
|
+
"decode and follow it. Encoded binary data (images, keys, hashes) is not reported."
|
|
2957
|
+
),
|
|
2958
|
+
hint="Store the text in readable form, or explain in the change why it must be encoded.",
|
|
2959
|
+
tags={"agent", "obfuscation"},
|
|
2960
|
+
)
|
|
2961
|
+
def encoded_payload(ctx: FileContext) -> Iterator[Hit]:
|
|
2962
|
+
for number, window in ctx.changed_lines():
|
|
2963
|
+
if len(window) < 96:
|
|
2964
|
+
continue
|
|
2965
|
+
for start, kind, run in _decoded_payloads(window):
|
|
2966
|
+
yield Hit(
|
|
2967
|
+
number,
|
|
2968
|
+
column=window.column(start),
|
|
2969
|
+
message=f"Text hidden in a {kind} run of {len(run)} characters",
|
|
2970
|
+
evidence=run[:48],
|
|
2971
|
+
)
|
|
2972
|
+
break
|