codeveto 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,208 @@
1
+ """``--format markdown``: the pull-request summary (SPEC 8.1 Markdown rules).
2
+
3
+ The same body is the job summary and the sticky PR comment that
4
+ ``codeveto publish`` writes::
5
+
6
+ ### CodeVeto: VETOED
7
+
8
+ **2 blocking findings** · 0 warnings · 0 notes · exit 1
9
+
10
+ 3 files · 141 rules · `4f1c2a9`..`9be03d1`
11
+
12
+ | Severity | Rule | Location | Message |
13
+ | --- | --- | --- | --- |
14
+ | **✕ error** | `agent/reviewer-directive` | `src/routes/export.ts:41` | `Comment …` |
15
+
16
+ - Heading with the verdict, then the counts and what was compared.
17
+ - **Incomplete**: why the review could not finish (issues that make it
18
+ incomplete, changed files whose coverage is not benign), before the table
19
+ so the reason survives the comment cap.
20
+ - Findings table in report order (at most :data:`MAX_ROWS` rows; blocking
21
+ findings are bold). A finding on a removed line says ``(removed line)``.
22
+ - Notes: issues that do not affect the verdict, config notes, proposed
23
+ ignores that were not applied, and the AI pass when one ran.
24
+
25
+ Untrusted text (paths, rule IDs, messages, reasons, AI fields) appears only
26
+ inside code spans from :func:`codeveto.render.safe.md_code`: escaped,
27
+ capped, mentions and references broken, fence longer than any backtick run,
28
+ ``|`` escaped in table cells. No link or image is ever built from untrusted
29
+ text. :func:`codeveto.render.safe.cap_comment` keeps the whole body below
30
+ :data:`~codeveto.render.safe.MD_COMMENT_CAP` without cutting a span.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ from collections.abc import Iterable, Mapping, Sequence
36
+ from typing import Any
37
+
38
+ from codeveto.render import RenderOptions, safe
39
+ from codeveto.report import coverage_incomplete
40
+
41
+ __all__ = ["MAX_PROBLEMS", "MAX_ROWS", "render", "summary"]
42
+
43
+ #: Most findings listed in the table; the rest are counted.
44
+ MAX_ROWS = 100
45
+ #: Most incomplete-coverage entries and issues listed; the rest are counted.
46
+ MAX_PROBLEMS = 50
47
+
48
+ _SYMBOL = {"error": "✕", "warning": "▲", "note": "·"}
49
+ _FIELD = 300
50
+
51
+
52
+ def _plural(count: int, word: str) -> str:
53
+ return f"{count} {word}" if count == 1 else f"{count} {word}s"
54
+
55
+
56
+ def _short(oid: object) -> str:
57
+ return safe.md_code(oid[:7]) if isinstance(oid, str) and oid else "empty"
58
+
59
+
60
+ def _compared(target: Mapping[str, Any]) -> str:
61
+ mode = target.get("mode")
62
+ if mode == "range":
63
+ return f"{_short(target.get('merge_base') or target.get('base'))}..{_short(target['head'])}"
64
+ if mode == "commit":
65
+ return f"{_short(target.get('base'))}..{_short(target.get('head'))}"
66
+ if mode == "staged":
67
+ return f"{_short(target.get('base'))}..index"
68
+ return f"{_short(target.get('anchor'))}..worktree"
69
+
70
+
71
+ def _location(finding: Mapping[str, Any]) -> str:
72
+ where = finding["path"]
73
+ if finding["line"] is not None:
74
+ where = f"{where}:{finding['line']}"
75
+ cell = safe.md_code(where, table=True)
76
+ if finding["side"] == "old":
77
+ cell += " (removed line)"
78
+ return cell
79
+
80
+
81
+ def _row(finding: Mapping[str, Any]) -> str:
82
+ severity = finding["severity"]
83
+ label = f"{_SYMBOL[severity]} {severity}"
84
+ if finding["blocking"]:
85
+ label = f"**{label}**"
86
+ cells = (
87
+ label,
88
+ safe.md_code(finding["rule"], table=True),
89
+ _location(finding),
90
+ safe.md_code(finding["message"], _FIELD, table=True),
91
+ )
92
+ return "| " + " | ".join(cells) + " |"
93
+
94
+
95
+ def _problems(report: Mapping[str, Any]) -> list[str]:
96
+ lines: list[str] = []
97
+ explained: set[str] = set()
98
+ for issue in report.get("issues", ()):
99
+ if not issue.get("incomplete", True):
100
+ continue
101
+ if issue.get("path"):
102
+ explained.add(issue["path"])
103
+ lines.append(
104
+ f"- {safe.md_code(issue['path'])}: {safe.md_code(issue['message'], _FIELD)}"
105
+ )
106
+ else:
107
+ lines.append(f"- {safe.md_code(issue['message'], _FIELD)}")
108
+ for entry in report.get("coverage", ()):
109
+ if coverage_incomplete(entry) and entry["path"] not in explained:
110
+ reason = entry.get("reason") or "no reason given"
111
+ lines.append(
112
+ f"- {safe.md_code(entry['path'])}: {entry['status']} "
113
+ f"({safe.md_code(reason, _FIELD)})"
114
+ )
115
+ if len(lines) > MAX_PROBLEMS:
116
+ extra = len(lines) - MAX_PROBLEMS
117
+ lines = [*lines[:MAX_PROBLEMS], f"- {extra} more not shown"]
118
+ return lines
119
+
120
+
121
+ def _notes(report: Mapping[str, Any]) -> list[str]:
122
+ lines: list[str] = []
123
+ for issue in report.get("issues", ()):
124
+ if issue.get("incomplete", True):
125
+ continue
126
+ where = f"{safe.md_code(issue['path'])}: " if issue.get("path") else ""
127
+ lines.append(f"- {where}{safe.md_code(issue['message'], _FIELD)}")
128
+ for note in report.get("config_notes", ()):
129
+ lines.append(f"- {safe.md_code(note, _FIELD)}")
130
+ proposed = len(report.get("proposed_ignores", ()))
131
+ if proposed:
132
+ lines.append(f"- {_plural(proposed, 'proposed ignore')} not applied")
133
+ ai = report.get("ai") or {}
134
+ if ai.get("status", "off") != "off":
135
+ parts = [f"AI pass {safe.md_code(ai['status'])}"]
136
+ if ai.get("provider"):
137
+ parts.append(f"provider {safe.md_code(ai['provider'])}")
138
+ if ai.get("model"):
139
+ parts.append(f"model {safe.md_code(ai['model'])}")
140
+ parts.append(f"{ai.get('verified', 0)} verified, {ai.get('rejected', 0)} rejected")
141
+ lines.append("- " + " · ".join(parts))
142
+ if len(lines) > MAX_PROBLEMS:
143
+ extra = len(lines) - MAX_PROBLEMS
144
+ lines = [*lines[:MAX_PROBLEMS], f"- {extra} more not shown"]
145
+ return lines
146
+
147
+
148
+ def summary(
149
+ report: Mapping[str, Any],
150
+ *,
151
+ findings: Sequence[Mapping[str, Any]] | None = None,
152
+ prefix: Iterable[str] = (),
153
+ notes: Iterable[str] = (),
154
+ cap: int = safe.MD_COMMENT_CAP,
155
+ ) -> str:
156
+ """The Markdown summary of ``report``, at most ``cap`` characters.
157
+
158
+ ``findings`` replaces the report's findings in the table (``publish``
159
+ passes the findings left after dropping those outside the pull request).
160
+ ``prefix`` lines (trusted Markdown, such as the sticky-comment marker) come
161
+ first; ``notes`` are trusted Markdown lines added to the notes section.
162
+ """
163
+ rows = list(report["findings"] if findings is None else findings)
164
+ summary_counts = report["summary"]
165
+ verdict = report["verdict"]
166
+ parts: list[str] = [*prefix, f"### CodeVeto: {verdict.upper()}", ""]
167
+ blocking = _plural(summary_counts["blocking"], "blocking finding")
168
+ parts.append(
169
+ " · ".join(
170
+ (
171
+ f"**{blocking}**" if summary_counts["blocking"] else blocking,
172
+ _plural(summary_counts["warnings"], "warning"),
173
+ _plural(summary_counts["notes"], "note"),
174
+ f"exit {report['exit_code']}",
175
+ )
176
+ )
177
+ )
178
+ parts.append("")
179
+ parts.append(
180
+ " · ".join(
181
+ (
182
+ _plural(summary_counts["files"], "file"),
183
+ _plural(summary_counts["rules_run"], "rule"),
184
+ _compared(report["target"]),
185
+ )
186
+ )
187
+ )
188
+ problems = _problems(report)
189
+ if problems:
190
+ parts += ["", "**Incomplete**", "", *problems]
191
+ if rows:
192
+ parts += ["", "| Severity | Rule | Location | Message |", "| --- | --- | --- | --- |"]
193
+ parts += [_row(f) for f in rows[:MAX_ROWS]]
194
+ if len(rows) > MAX_ROWS:
195
+ parts += ["", f"{len(rows) - MAX_ROWS} more findings not shown."]
196
+ elif report["findings"] and findings is not None:
197
+ parts += ["", "No finding is on a line this pull request changes."]
198
+ else:
199
+ parts += ["", "No findings."]
200
+ extra = [*_notes(report), *notes]
201
+ if extra:
202
+ parts += ["", "**Notes**", "", *extra]
203
+ return safe.cap_comment(parts, cap, omitted="\n{n} more line(s) omitted (size limit).") + "\n"
204
+
205
+
206
+ def render(report: Mapping[str, Any], options: RenderOptions) -> str:
207
+ """The Markdown summary (``options`` do not apply: Markdown is never coloured)."""
208
+ return summary(report)
@@ -0,0 +1,249 @@
1
+ """The one sanitizer for untrusted text in every output format (SPEC 8.1).
2
+
3
+ Paths, snippets, messages, evidence, hints, issue and config-note strings and
4
+ AI text can all come from the change under review or from a model. Renderers
5
+ never write them raw: they pass every such field through the function for
6
+ their medium here, and only the renderer itself emits colour codes or markup.
7
+
8
+ - Terminal text and ``--format agent`` (:func:`text`): every character of
9
+ Unicode category Cc, Cf, Zl or Zp (ESC and other C0/C1 controls, bidi
10
+ embeddings, overrides and isolates, zero-width characters, tag characters,
11
+ U+2028/U+2029) becomes a visible escape (``\\x1b``, ``\\u202e``, ``\\n``).
12
+ Lone surrogates (Cs, from ``surrogateescape`` decoding) and unassigned code
13
+ points (Cn, which a later Unicode version may make Cf) are escaped too, so
14
+ the output always encodes and never reorders or hides text.
15
+ - JSON (:func:`json_text`): the same characters become ``\\uXXXX`` escapes in
16
+ the serialized document; the data is unchanged for a JSON reader.
17
+ - GitHub workflow commands (:func:`workflow_data`, :func:`workflow_property`):
18
+ ``%``, CR and LF are percent-encoded in data, plus ``:`` and ``,`` in
19
+ properties; other unsafe characters get visible escapes.
20
+ - Markdown (:func:`md_code`, :func:`md_pre`, :func:`html_code`): untrusted
21
+ text appears only inside code: a code span or a fenced block whose fence is
22
+ longer than any backtick run in the text, or an HTML-escaped ``<code>``
23
+ element for HTML blocks. ``@`` and ``#`` are followed by U+200C so they can
24
+ never form a mention or an issue reference, ``<!--`` and ``-->`` get a U+200C
25
+ inside so no HTML comment (or publisher marker) can form, every field is capped, and
26
+ :func:`cap_comment` keeps a whole comment below 65,000 characters without
27
+ ever cutting through a code span or block.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import html
33
+ import re
34
+ import unicodedata
35
+ from collections.abc import Iterable
36
+
37
+ __all__ = [
38
+ "MD_COMMENT_CAP",
39
+ "MD_FIELD_CAP",
40
+ "MD_SNIPPET_CAP",
41
+ "UNSAFE_CATEGORIES",
42
+ "break_markers",
43
+ "break_mentions",
44
+ "cap_comment",
45
+ "escape_char",
46
+ "html_code",
47
+ "is_unsafe",
48
+ "json_text",
49
+ "md_code",
50
+ "md_pre",
51
+ "text",
52
+ "truncate",
53
+ "workflow_data",
54
+ "workflow_property",
55
+ ]
56
+
57
+ #: Unicode categories that never reach output unescaped.
58
+ UNSAFE_CATEGORIES = frozenset({"Cc", "Cf", "Zl", "Zp", "Cs", "Cn"})
59
+
60
+ #: Longest untrusted field in Markdown (messages, paths, reasons).
61
+ MD_FIELD_CAP = 500
62
+ #: Longest snippet in Markdown.
63
+ MD_SNIPPET_CAP = 2_000
64
+ #: Longest Markdown comment body; GitHub refuses bodies over 65,536 characters.
65
+ MD_COMMENT_CAP = 64_000
66
+
67
+ _ZWNJ = "\u200c"
68
+ _NAMED = {"\t": "\\t", "\n": "\\n", "\r": "\\r"}
69
+ _BACKTICKS = re.compile(r"`+")
70
+ _MENTION = re.compile(r"[@#]")
71
+
72
+
73
+ def is_unsafe(ch: str) -> bool:
74
+ """Is ``ch`` a character that output must never carry raw?"""
75
+ return unicodedata.category(ch) in UNSAFE_CATEGORIES
76
+
77
+
78
+ def escape_char(ch: str) -> str:
79
+ """The visible escape of one character: ``\\t``, ``\\x1b``, ``\\u202e``, ``\\U000e0041``."""
80
+ named = _NAMED.get(ch)
81
+ if named is not None:
82
+ return named
83
+ code = ord(ch)
84
+ if code <= 0xFF:
85
+ return f"\\x{code:02x}"
86
+ if code <= 0xFFFF:
87
+ return f"\\u{code:04x}"
88
+ return f"\\U{code:08x}"
89
+
90
+
91
+ def _escape(value: str) -> str:
92
+ # str.isprintable() is False for every C* and Z* character except the
93
+ # space, so it is a cheap superset test of what needs escaping.
94
+ if value.isprintable():
95
+ return value
96
+ return "".join(escape_char(ch) if is_unsafe(ch) else ch for ch in value)
97
+
98
+
99
+ def truncate(value: str, limit: int, ellipsis: str = "…") -> str:
100
+ """``value`` cut to at most ``limit`` characters, ending in ``ellipsis`` when cut."""
101
+ if limit <= 0:
102
+ return ""
103
+ if len(value) <= limit:
104
+ return value
105
+ keep = max(0, limit - len(ellipsis))
106
+ return value[:keep] + ellipsis[: limit - keep]
107
+
108
+
109
+ def text(value: object, limit: int | None = None, ellipsis: str = "…") -> str:
110
+ """Terminal-safe single-line text: unsafe characters escaped, then capped.
111
+
112
+ ``None`` becomes the empty string; other non-strings are converted with
113
+ ``str`` first. The result never contains a line break or a control
114
+ character, so a renderer can place it on one line.
115
+ """
116
+ if value is None:
117
+ return ""
118
+ escaped = _escape(value if isinstance(value, str) else str(value))
119
+ return escaped if limit is None else truncate(escaped, limit, ellipsis)
120
+
121
+
122
+ def _json_escape_char(ch: str) -> str:
123
+ code = ord(ch)
124
+ if code <= 0xFFFF:
125
+ return f"\\u{code:04x}"
126
+ code -= 0x10000
127
+ return f"\\u{0xD800 + (code >> 10):04x}\\u{0xDC00 + (code & 0x3FF):04x}"
128
+
129
+
130
+ def json_text(serialized: str) -> str:
131
+ """Escape unsafe characters in serialized JSON as ``\\uXXXX`` (data unchanged).
132
+
133
+ ``json.dumps(..., ensure_ascii=False)`` escapes C0 controls but writes DEL,
134
+ C1 controls (including CSI), bidi and other format characters, line and
135
+ paragraph separators and lone surrogates raw. Outside strings a JSON
136
+ document holds none of those, so every occurrence is inside a string,
137
+ where the escape decodes to the same character.
138
+ """
139
+ if serialized.isprintable():
140
+ return serialized
141
+ return "".join(
142
+ _json_escape_char(ch) if ch not in "\n" and is_unsafe(ch) else ch for ch in serialized
143
+ )
144
+
145
+
146
+ # --- GitHub workflow commands ---------------------------------------------------------
147
+
148
+
149
+ def workflow_data(value: object) -> str:
150
+ """Text for the data part of a workflow command (``::error ...::<data>``)."""
151
+ raw = "" if value is None else (value if isinstance(value, str) else str(value))
152
+ encoded = raw.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
153
+ return _escape(encoded)
154
+
155
+
156
+ def workflow_property(value: object) -> str:
157
+ """Text for a workflow command property value (``file=<value>,line=...``)."""
158
+ return workflow_data(value).replace(":", "%3A").replace(",", "%2C")
159
+
160
+
161
+ # --- Markdown -----------------------------------------------------------------------
162
+
163
+
164
+ def break_mentions(value: str) -> str:
165
+ """Put U+200C after every ``@`` and ``#`` so no mention or reference forms."""
166
+ return _MENTION.sub(lambda m: m.group(0) + _ZWNJ, value)
167
+
168
+
169
+ def break_markers(value: str) -> str:
170
+ """Put U+200C inside every ``<!--`` and ``-->``: untrusted text never forms an HTML
171
+ comment, so it can never carry or imitate a marker a publisher writes."""
172
+ return value.replace("<!--", f"<{_ZWNJ}!--").replace("-->", f"--{_ZWNJ}>")
173
+
174
+
175
+ def _fence_for(value: str, minimum: int) -> str:
176
+ longest = max((len(m.group(0)) for m in _BACKTICKS.finditer(value)), default=0)
177
+ return "`" * max(minimum, longest + 1)
178
+
179
+
180
+ def md_code(value: object, limit: int = MD_FIELD_CAP, *, table: bool = False) -> str:
181
+ """An inline code span holding ``value`` literally (never Markdown, HTML or a link).
182
+
183
+ Unsafe characters (line breaks included) are escaped, the text is capped,
184
+ mentions are broken and the backtick fence is one longer than the longest
185
+ backtick run inside. ``table=True`` also escapes ``|`` for a table cell.
186
+ An empty value becomes an empty-looking span of one space.
187
+ """
188
+ body = break_markers(break_mentions(text(value, limit)))
189
+ if table:
190
+ body = body.replace("|", "\\|")
191
+ fence = _fence_for(body, 1)
192
+ if not body:
193
+ body = " "
194
+ elif body[0] in " `" or body[-1] in " `":
195
+ body = f" {body} "
196
+ return f"{fence}{body}{fence}"
197
+
198
+
199
+ def md_pre(value: object, limit: int = MD_SNIPPET_CAP, *, info: str = "") -> str:
200
+ """A fenced code block holding ``value`` literally, line breaks kept.
201
+
202
+ Each line has its unsafe characters escaped; the text is capped; the
203
+ fence is longer than any backtick run inside, so the content can never
204
+ close it. ``info`` must be trusted text (a language name).
205
+ """
206
+ raw = "" if value is None else (value if isinstance(value, str) else str(value))
207
+ lines = raw.replace("\r\n", "\n").split("\n")
208
+ body = truncate("\n".join(break_markers(break_mentions(text(line))) for line in lines), limit)
209
+ fence = _fence_for(body, 3)
210
+ return f"{fence}{info}\n{body}\n{fence}"
211
+
212
+
213
+ def html_code(value: object, limit: int = MD_FIELD_CAP) -> str:
214
+ """An HTML ``<code>`` element for use inside an HTML block (``<table>``, ``<details>``).
215
+
216
+ The text is escaped for HTML, quotes included, and Markdown punctuation
217
+ becomes character references, so the content is inert whether or not
218
+ the surrounding block is parsed as Markdown.
219
+ """
220
+ body = html.escape(break_mentions(text(value, limit)), quote=True)
221
+ for ch in "`*_[]()!~|\\:":
222
+ body = body.replace(ch, f"&#{ord(ch)};")
223
+ return f"<code>{body}</code>"
224
+
225
+
226
+ def cap_comment(
227
+ parts: Iterable[str], cap: int = MD_COMMENT_CAP, *, omitted: str = "{n} more item(s) omitted"
228
+ ) -> str:
229
+ """Join Markdown ``parts`` with newlines, dropping whole parts that would pass ``cap``.
230
+
231
+ Parts are never cut, so a code span or fenced block is never left open.
232
+ When parts are dropped, a final line from the trusted ``omitted`` template
233
+ (``{n}`` is the count) says so; room for it is kept below ``cap``.
234
+ """
235
+ items = list(parts)
236
+ reserve = len(omitted) + 24
237
+ kept: list[str] = []
238
+ size = 0
239
+ for index, part in enumerate(items):
240
+ extra = len(part) + (1 if kept else 0)
241
+ last = index == len(items) - 1
242
+ if size + extra <= (cap if last else cap - reserve):
243
+ kept.append(part)
244
+ size += extra
245
+ continue
246
+ dropped = len(items) - index
247
+ kept.append(omitted.format(n=dropped))
248
+ break
249
+ return "\n".join(kept)
@@ -0,0 +1,217 @@
1
+ """``--format sarif``: SARIF 2.1.0 for code scanning and other SARIF consumers.
2
+
3
+ One run with one tool driver. ``tool.driver.rules`` lists every rule a
4
+ finding refers to, in rule-ID order, with its title, rationale and hint as
5
+ help text (from the rule catalogue; a rule the catalogue does not know, such
6
+ as an AI category, falls back to the finding's own hint). Each finding is a
7
+ result:
8
+
9
+ - ``level`` from the severity (``error``, ``warning``, ``note``) and
10
+ ``properties`` with ``blocking``, ``severity``, ``source`` and ``side``;
11
+ - one location relative to ``%SRCROOT%``: the path as a URI reference
12
+ (percent-encoded, so no character of a hostile path survives raw), and for
13
+ a new-side line finding a region with the line, end line, column and the
14
+ snippet. A finding on a removed line or a whole file has no region (the
15
+ line does not exist in the reviewed revision); its message says which
16
+ removed line it is;
17
+ - ``partialFingerprints["codevetoFingerprint/v1"]``: the report
18
+ fingerprint, so consumers deduplicate results across runs exactly as the
19
+ report does.
20
+
21
+ Report issues become ``toolExecutionNotifications`` of the one invocation,
22
+ whose ``executionSuccessful`` is false when the review is incomplete.
23
+
24
+ Every repository- or model-derived string goes through
25
+ :mod:`codeveto.render.safe` (visible escapes for control, bidi and other
26
+ unsafe characters), and the serialized document through
27
+ :func:`~codeveto.render.safe.json_text`.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ from collections.abc import Callable, Mapping
34
+ from typing import Any
35
+ from urllib.parse import quote
36
+
37
+ from codeveto.render import RenderOptions, safe
38
+
39
+ __all__ = ["FINGERPRINT_KEY", "SARIF_SCHEMA", "SARIF_VERSION", "build", "render"]
40
+
41
+ SARIF_VERSION = "2.1.0"
42
+ SARIF_SCHEMA = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/os/schemas/sarif-schema-2.1.0.json"
43
+ FINGERPRINT_KEY = "codevetoFingerprint/v1"
44
+ INFORMATION_URI = "https://github.com/spink-dev/codeveto"
45
+ SRCROOT = "%SRCROOT%"
46
+
47
+ _LEVEL = {"error": "error", "warning": "warning", "note": "note"}
48
+ _SNIPPET_CAP = 2_000
49
+ _MESSAGE_CAP = 4_000
50
+
51
+ #: ``rule_id -> metadata or None``; metadata needs ``title``, ``rationale``,
52
+ #: ``hint``, ``severity`` and ``tags`` (a :class:`~codeveto.rules.base.RuleMeta`).
53
+ Catalog = Callable[[str], Any]
54
+
55
+
56
+ def _live_catalog() -> Catalog:
57
+ try:
58
+ from codeveto.rules import load_rules
59
+
60
+ registry = load_rules()
61
+ except Exception: # a broken pack must not stop the output; help text falls back
62
+ return lambda rule_id: None
63
+
64
+ def lookup(rule_id: str) -> Any:
65
+ entry = registry.get(rule_id)
66
+ return None if entry is None else entry.meta
67
+
68
+ return lookup
69
+
70
+
71
+ def _uri(path: str) -> str:
72
+ # Git paths are relative and use "/"; everything else is percent-encoded
73
+ # (control characters, spaces, "%", "#", "?", non-ASCII as UTF-8).
74
+ return quote(path, safe="/", errors="surrogateescape")
75
+
76
+
77
+ def _rule(rule_id: str, meta: Any, fallback_hint: str, severity: str) -> dict[str, Any]:
78
+ if meta is not None:
79
+ title = safe.text(meta.title)
80
+ rationale = safe.text(meta.rationale)
81
+ hint = safe.text(meta.hint)
82
+ level = _LEVEL[str(meta.severity)]
83
+ tags = sorted(str(t) for t in meta.tags)
84
+ else:
85
+ title = safe.text(rule_id)
86
+ rationale = ""
87
+ hint = safe.text(fallback_hint, _MESSAGE_CAP)
88
+ level = _LEVEL[severity]
89
+ tags = []
90
+ help_text = "\n\n".join(part for part in (rationale, f"Fix: {hint}" if hint else "") if part)
91
+ entry: dict[str, Any] = {
92
+ "id": safe.text(rule_id),
93
+ "name": safe.text(rule_id.split("/", 1)[-1]),
94
+ "shortDescription": {"text": title or safe.text(rule_id)},
95
+ "fullDescription": {"text": rationale or title or safe.text(rule_id)},
96
+ "help": {"text": help_text or title or safe.text(rule_id)},
97
+ "defaultConfiguration": {"level": level},
98
+ "properties": {"tags": tags} if tags else {},
99
+ }
100
+ if not entry["properties"]:
101
+ del entry["properties"]
102
+ return entry
103
+
104
+
105
+ def _snippet(value: object) -> str:
106
+ raw = value if isinstance(value, str) else ""
107
+ return safe.truncate(
108
+ "\n".join(safe.text(line) for line in raw.replace("\r\n", "\n").split("\n")),
109
+ _SNIPPET_CAP,
110
+ )
111
+
112
+
113
+ def _result(finding: Mapping[str, Any], rule_index: int) -> dict[str, Any]:
114
+ message = safe.text(finding["message"], _MESSAGE_CAP)
115
+ line = finding["line"]
116
+ location: dict[str, Any] = {
117
+ "physicalLocation": {
118
+ "artifactLocation": {"uri": _uri(finding["path"]), "uriBaseId": SRCROOT},
119
+ }
120
+ }
121
+ if line is not None and finding["side"] == "new":
122
+ region: dict[str, Any] = {"startLine": line}
123
+ end = finding["end_line"]
124
+ if end is not None and end >= line:
125
+ region["endLine"] = end
126
+ if finding["column"] is not None:
127
+ region["startColumn"] = finding["column"]
128
+ if finding.get("snippet"):
129
+ region["snippet"] = {"text": _snippet(finding["snippet"])}
130
+ location["physicalLocation"]["region"] = region
131
+ elif line is not None:
132
+ message = f"{message} (removed line {line})"
133
+ if finding["side"] == "old" and finding.get("old_path"):
134
+ location["physicalLocation"]["artifactLocation"]["uri"] = _uri(finding["old_path"])
135
+ properties: dict[str, Any] = {
136
+ "blocking": finding["blocking"],
137
+ "severity": finding["severity"],
138
+ "source": finding["source"],
139
+ "side": finding["side"],
140
+ }
141
+ if finding.get("category"):
142
+ properties["category"] = safe.text(finding["category"])
143
+ return {
144
+ "ruleId": safe.text(finding["rule"]),
145
+ "ruleIndex": rule_index,
146
+ "level": _LEVEL[finding["severity"]],
147
+ "message": {"text": message or safe.text(finding["rule"])},
148
+ "locations": [location],
149
+ "partialFingerprints": {FINGERPRINT_KEY: finding["fingerprint"]},
150
+ "properties": properties,
151
+ }
152
+
153
+
154
+ def _notification(issue: Mapping[str, Any]) -> dict[str, Any]:
155
+ text = safe.text(issue["message"], _MESSAGE_CAP) or safe.text(issue["kind"])
156
+ entry: dict[str, Any] = {
157
+ "level": "warning" if issue.get("incomplete", True) else "note",
158
+ "message": {"text": text},
159
+ "descriptor": {"id": safe.text(issue["kind"])},
160
+ }
161
+ if issue.get("path"):
162
+ entry["locations"] = [
163
+ {
164
+ "physicalLocation": {
165
+ "artifactLocation": {"uri": _uri(issue["path"]), "uriBaseId": SRCROOT}
166
+ }
167
+ }
168
+ ]
169
+ return entry
170
+
171
+
172
+ def build(report: Mapping[str, Any], catalog: Catalog | None = None) -> dict[str, Any]:
173
+ """The SARIF log of ``report`` as a dict (``catalog`` defaults to the live rule registry)."""
174
+ lookup = catalog if catalog is not None else _live_catalog()
175
+ findings = report["findings"]
176
+ first: dict[str, Mapping[str, Any]] = {}
177
+ for finding in findings:
178
+ first.setdefault(finding["rule"], finding)
179
+ rule_ids = sorted(first)
180
+ index = {rule_id: i for i, rule_id in enumerate(rule_ids)}
181
+ rules = [
182
+ _rule(rule_id, lookup(rule_id), first[rule_id]["hint"], first[rule_id]["severity"])
183
+ for rule_id in rule_ids
184
+ ]
185
+ results = [_result(f, index[f["rule"]]) for f in findings]
186
+ invocation: dict[str, Any] = {
187
+ "executionSuccessful": report["verdict"] != "incomplete",
188
+ "exitCode": report["exit_code"],
189
+ "toolExecutionNotifications": [_notification(i) for i in report.get("issues", ())],
190
+ }
191
+ run: dict[str, Any] = {
192
+ "tool": {
193
+ "driver": {
194
+ "name": "codeveto",
195
+ "version": safe.text(report["tool"]["version"]),
196
+ "semanticVersion": safe.text(report["tool"]["version"]),
197
+ "informationUri": INFORMATION_URI,
198
+ "rules": rules,
199
+ }
200
+ },
201
+ "invocations": [invocation],
202
+ "originalUriBaseIds": {SRCROOT: {"description": {"text": "The repository root."}}},
203
+ "columnKind": "unicodeCodePoints",
204
+ "results": results,
205
+ "properties": {
206
+ "verdict": report["verdict"],
207
+ "failOn": report["fail_on"],
208
+ "head": report["target"].get("head"),
209
+ "base": report["target"].get("base"),
210
+ },
211
+ }
212
+ return {"$schema": SARIF_SCHEMA, "version": SARIF_VERSION, "runs": [run]}
213
+
214
+
215
+ def render(report: Mapping[str, Any], options: RenderOptions) -> str:
216
+ """The SARIF log as indented JSON ending with a newline (``options`` do not apply)."""
217
+ return safe.json_text(json.dumps(build(report), indent=2, ensure_ascii=False)) + "\n"