codeveto 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/schema.py ADDED
@@ -0,0 +1,384 @@
1
+ """A small standard-library validator for the JSON Schema subset our schemas use.
2
+
3
+ CodeVeto validates its own reports (tests, ``publish``) and untrusted inputs
4
+ without a runtime dependency, so it carries this validator for the subset of
5
+ JSON Schema draft 2020-12 that ``data/*.schema.json`` uses:
6
+
7
+ ``type`` (one name or a list), ``properties``, ``required``,
8
+ ``additionalProperties`` (``false`` or a schema), ``items`` (one schema),
9
+ ``enum``, ``const``, ``minimum``, ``maximum``, ``minLength``, ``maxLength``,
10
+ ``pattern``, ``$ref`` to ``#/$defs/<name>``, ``anyOf`` and ``oneOf``, plus the
11
+ annotations ``$schema``, ``$id``, ``$defs``, ``title``, ``description`` and
12
+ ``$comment``. :func:`unsupported_keywords` lists anything else a schema uses
13
+ (a test asserts it finds nothing), and :func:`validate` refuses a schema with
14
+ unsupported keywords instead of ignoring them.
15
+
16
+ Semantics follow the specification where the subset touches it: booleans are
17
+ not numbers, ``integer`` accepts integral floats, ``enum``/``const`` compare
18
+ JSON values (``1`` does not equal ``true``), string lengths count code
19
+ points, ``pattern`` is a search (unanchored unless the pattern anchors it) and
20
+ ``$`` matches only at the very end of the string, as in ECMA-262 (Python's
21
+ ``$`` would also match before a final line break, letting ``"<oid>\\n"`` pass
22
+ ``^[0-9a-f]{40}$``). Every pattern under ``data/`` is anchored at both ends, so
23
+ it must match the whole string (tested).
24
+ Patterns must be bounded: at most :data:`MAX_PATTERN_LENGTH` characters and no
25
+ unbounded repeat inside another unbounded repeat, so matching stays linear.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import math
31
+ import re
32
+ from collections.abc import Iterator, Mapping
33
+ from functools import lru_cache
34
+ from re import _constants as _sre # type: ignore[attr-defined]
35
+ from re import _parser as _sre_parse # type: ignore[attr-defined]
36
+
37
+ __all__ = [
38
+ "ANNOTATIONS",
39
+ "MAX_ERRORS",
40
+ "MAX_PATTERN_LENGTH",
41
+ "SUPPORTED_KEYWORDS",
42
+ "SchemaError",
43
+ "is_valid",
44
+ "unsupported_keywords",
45
+ "validate",
46
+ ]
47
+
48
+ ANNOTATIONS = frozenset({"$schema", "$id", "$defs", "$comment", "title", "description"})
49
+ ASSERTIONS = frozenset(
50
+ {
51
+ "type",
52
+ "properties",
53
+ "required",
54
+ "additionalProperties",
55
+ "items",
56
+ "enum",
57
+ "const",
58
+ "minimum",
59
+ "maximum",
60
+ "minLength",
61
+ "maxLength",
62
+ "pattern",
63
+ "$ref",
64
+ "anyOf",
65
+ "oneOf",
66
+ }
67
+ )
68
+ SUPPORTED_KEYWORDS = ANNOTATIONS | ASSERTIONS
69
+ MAX_PATTERN_LENGTH = 256
70
+ #: Validation stops collecting after this many errors.
71
+ MAX_ERRORS = 100
72
+ _MAX_DEPTH = 64
73
+
74
+ _TYPES = frozenset({"null", "boolean", "object", "array", "number", "integer", "string"})
75
+ _REPEATS = {_sre.MAX_REPEAT, _sre.MIN_REPEAT, getattr(_sre, "POSSESSIVE_REPEAT", _sre.MAX_REPEAT)}
76
+
77
+
78
+ class SchemaError(ValueError):
79
+ """The schema itself is malformed or uses keywords outside the subset."""
80
+
81
+
82
+ # --- schema checks -------------------------------------------------------------------
83
+
84
+
85
+ def _subschemas(schema: Mapping[str, object]) -> Iterator[tuple[str, object]]:
86
+ for key in ("items", "additionalProperties"):
87
+ if isinstance(schema.get(key), Mapping):
88
+ yield key, schema[key]
89
+ for key in ("properties", "$defs"):
90
+ table = schema.get(key)
91
+ if isinstance(table, Mapping):
92
+ for name, sub in table.items():
93
+ yield f"{key}/{name}", sub
94
+ for key in ("anyOf", "oneOf"):
95
+ options = schema.get(key)
96
+ if isinstance(options, list):
97
+ for i, sub in enumerate(options):
98
+ yield f"{key}/{i}", sub
99
+
100
+
101
+ def unsupported_keywords(schema: object, path: str = "#") -> list[str]:
102
+ """``<json-pointer>: <keyword>`` for every keyword outside the subset, recursively."""
103
+ if not isinstance(schema, Mapping):
104
+ return [f"{path}: schema is not an object"]
105
+ found = [f"{path}: {key}" for key in schema if key not in SUPPORTED_KEYWORDS]
106
+ for key, sub in _subschemas(schema):
107
+ found.extend(unsupported_keywords(sub, f"{path}/{key}"))
108
+ return found
109
+
110
+
111
+ def _nested_unbounded(pattern: str) -> bool:
112
+ def walk(parsed: object, inside: bool) -> bool:
113
+ for op, av in parsed: # type: ignore[attr-defined]
114
+ if op in _REPEATS:
115
+ _, high, sub = av
116
+ unbounded = high == _sre.MAXREPEAT
117
+ if (unbounded and inside) or walk(sub, inside or unbounded):
118
+ return True
119
+ elif op is _sre.SUBPATTERN:
120
+ if walk(av[-1], inside):
121
+ return True
122
+ elif op is _sre.BRANCH:
123
+ if any(walk(branch, inside) for branch in av[1]):
124
+ return True
125
+ elif op in (_sre.ASSERT, _sre.ASSERT_NOT) and walk(av[1], inside):
126
+ return True
127
+ return False
128
+
129
+ return walk(_sre_parse.parse(pattern), False)
130
+
131
+
132
+ def _ecma_end(pattern: str) -> str:
133
+ """``pattern`` with every ``$`` anchor written as ``\\Z`` (end of string only).
134
+
135
+ An escaped ``\\$`` and a ``$`` inside a character class stay literal.
136
+ """
137
+ out: list[str] = []
138
+ i, in_class = 0, False
139
+ while i < len(pattern):
140
+ ch = pattern[i]
141
+ if ch == "\\":
142
+ out.append(pattern[i : i + 2])
143
+ i += 2
144
+ continue
145
+ if in_class:
146
+ if ch == "]":
147
+ in_class = False
148
+ elif ch == "[":
149
+ in_class = True
150
+ # A "]" right after "[" or "[^" is a literal member, not the end.
151
+ lead = (
152
+ 3 if pattern[i + 1 : i + 3] == "^]" else 2 if pattern[i + 1 : i + 2] == "]" else 1
153
+ )
154
+ out.append(pattern[i : i + lead])
155
+ i += lead
156
+ continue
157
+ elif ch == "$":
158
+ out.append("\\Z")
159
+ i += 1
160
+ continue
161
+ out.append(ch)
162
+ i += 1
163
+ return "".join(out)
164
+
165
+
166
+ @lru_cache(maxsize=256)
167
+ def _pattern(pattern: str) -> re.Pattern[str]:
168
+ if len(pattern) > MAX_PATTERN_LENGTH:
169
+ raise SchemaError(f"pattern longer than {MAX_PATTERN_LENGTH} characters")
170
+ try:
171
+ compiled = re.compile(_ecma_end(pattern))
172
+ except re.error as exc:
173
+ raise SchemaError(f"invalid pattern {pattern!r}: {exc}") from None
174
+ if _nested_unbounded(pattern):
175
+ raise SchemaError(f"pattern {pattern!r} nests unbounded repeats")
176
+ return compiled
177
+
178
+
179
+ def _check_schema(schema: object, path: str = "#", depth: int = 0) -> None:
180
+ if depth > _MAX_DEPTH:
181
+ raise SchemaError(f"{path}: schema nests too deeply")
182
+ if not isinstance(schema, Mapping):
183
+ raise SchemaError(f"{path}: schema is not an object")
184
+ bad = [key for key in schema if key not in SUPPORTED_KEYWORDS]
185
+ if bad:
186
+ raise SchemaError(f"{path}: unsupported keyword(s) {', '.join(sorted(bad))}")
187
+ kind = schema.get("type")
188
+ names = kind if isinstance(kind, list) else [kind] if kind is not None else []
189
+ if any(n not in _TYPES for n in names) or (isinstance(kind, list) and not kind):
190
+ raise SchemaError(f"{path}: invalid type {kind!r}")
191
+ if "pattern" in schema:
192
+ if not isinstance(schema["pattern"], str):
193
+ raise SchemaError(f"{path}: pattern must be a string")
194
+ _pattern(schema["pattern"])
195
+ ref = schema.get("$ref")
196
+ if ref is not None and (not isinstance(ref, str) or not ref.startswith("#/$defs/")):
197
+ raise SchemaError(f"{path}: only #/$defs/<name> references are supported")
198
+ for key in ("anyOf", "oneOf"):
199
+ if key in schema and (not isinstance(schema[key], list) or not schema[key]):
200
+ raise SchemaError(f"{path}: {key} must be a non-empty array")
201
+ if "required" in schema and not (
202
+ isinstance(schema["required"], list) and all(isinstance(r, str) for r in schema["required"])
203
+ ):
204
+ raise SchemaError(f"{path}: required must be an array of strings")
205
+ if "enum" in schema and not isinstance(schema["enum"], list):
206
+ raise SchemaError(f"{path}: enum must be an array")
207
+ additional = schema.get("additionalProperties")
208
+ if additional is not None and not isinstance(additional, bool | Mapping):
209
+ raise SchemaError(f"{path}: additionalProperties must be a boolean or a schema")
210
+ for key, sub in _subschemas(schema):
211
+ _check_schema(sub, f"{path}/{key}", depth + 1)
212
+
213
+
214
+ # --- validation ----------------------------------------------------------------------
215
+
216
+
217
+ def _is_number(value: object) -> bool:
218
+ return isinstance(value, int | float) and not isinstance(value, bool)
219
+
220
+
221
+ def _type_ok(value: object, name: str) -> bool:
222
+ if name == "null":
223
+ return value is None
224
+ if name == "boolean":
225
+ return isinstance(value, bool)
226
+ if name == "object":
227
+ return isinstance(value, Mapping)
228
+ if name == "array":
229
+ return isinstance(value, list | tuple)
230
+ if name == "string":
231
+ return isinstance(value, str)
232
+ if name == "number":
233
+ return _is_number(value) and not (isinstance(value, float) and not math.isfinite(value))
234
+ # integer
235
+ if isinstance(value, bool):
236
+ return False
237
+ return isinstance(value, int) or (
238
+ isinstance(value, float) and math.isfinite(value) and value.is_integer()
239
+ )
240
+
241
+
242
+ def _json_equal(a: object, b: object) -> bool:
243
+ if isinstance(a, bool) or isinstance(b, bool):
244
+ return isinstance(a, bool) and isinstance(b, bool) and a == b
245
+ if _is_number(a) and _is_number(b):
246
+ return a == b
247
+ if isinstance(a, str) or isinstance(b, str) or a is None or b is None:
248
+ return type(a) is type(b) and a == b
249
+ if isinstance(a, list | tuple) and isinstance(b, list | tuple):
250
+ return len(a) == len(b) and all(_json_equal(x, y) for x, y in zip(a, b, strict=True))
251
+ if isinstance(a, Mapping) and isinstance(b, Mapping):
252
+ return a.keys() == b.keys() and all(_json_equal(a[k], b[k]) for k in a)
253
+ return False
254
+
255
+
256
+ def _pointer(path: str, key: object) -> str:
257
+ part = str(key).replace("~", "~0").replace("/", "~1")
258
+ return f"{path}/{part}"
259
+
260
+
261
+ class _Validator:
262
+ def __init__(self, root: Mapping[str, object]) -> None:
263
+ self.root = root
264
+ self.errors: list[str] = []
265
+
266
+ def error(self, path: str, problem: str) -> None:
267
+ if len(self.errors) < MAX_ERRORS:
268
+ self.errors.append(f"{path or '/'}: {problem}")
269
+
270
+ def resolve(self, ref: str) -> Mapping[str, object]:
271
+ defs = self.root.get("$defs")
272
+ name = ref.removeprefix("#/$defs/")
273
+ if not isinstance(defs, Mapping) or not isinstance(defs.get(name), Mapping):
274
+ raise SchemaError(f"unresolvable reference {ref!r}")
275
+ return defs[name] # type: ignore[return-value]
276
+
277
+ def matches(self, value: object, schema: Mapping[str, object], depth: int) -> bool:
278
+ probe = _Validator(self.root)
279
+ probe.check(value, schema, "", depth)
280
+ return not probe.errors
281
+
282
+ def check(self, value: object, schema: Mapping[str, object], path: str, depth: int) -> None:
283
+ if depth > _MAX_DEPTH:
284
+ self.error(path, "value nests too deeply")
285
+ return
286
+ if "$ref" in schema:
287
+ self.check(value, self.resolve(schema["$ref"]), path, depth + 1) # type: ignore[arg-type]
288
+ kind = schema.get("type")
289
+ if kind is not None:
290
+ names = kind if isinstance(kind, list) else [kind]
291
+ if not any(_type_ok(value, n) for n in names): # type: ignore[union-attr]
292
+ self.error(path, f"expected {' or '.join(names)}, got {_kind(value)}") # type: ignore[arg-type]
293
+ return
294
+ if "const" in schema and not _json_equal(value, schema["const"]):
295
+ self.error(path, f"must equal {schema['const']!r}")
296
+ if "enum" in schema and not any(_json_equal(value, e) for e in schema["enum"]): # type: ignore[union-attr]
297
+ self.error(path, f"must be one of {schema['enum']!r}")
298
+ if _is_number(value):
299
+ low, high = schema.get("minimum"), schema.get("maximum")
300
+ if low is not None and value < low: # type: ignore[operator]
301
+ self.error(path, f"must be >= {low}")
302
+ if high is not None and value > high: # type: ignore[operator]
303
+ self.error(path, f"must be <= {high}")
304
+ if isinstance(value, str):
305
+ self.string(value, schema, path)
306
+ if isinstance(value, Mapping):
307
+ self.object(value, schema, path, depth)
308
+ if isinstance(value, list | tuple) and isinstance(schema.get("items"), Mapping):
309
+ for i, item in enumerate(value):
310
+ self.check(item, schema["items"], _pointer(path, i), depth + 1) # type: ignore[arg-type]
311
+ if "anyOf" in schema and not any(
312
+ self.matches(value, option, depth + 1)
313
+ for option in schema["anyOf"] # type: ignore[union-attr]
314
+ ):
315
+ self.error(path, "matches none of anyOf")
316
+ if "oneOf" in schema:
317
+ count = sum(self.matches(value, o, depth + 1) for o in schema["oneOf"]) # type: ignore[union-attr]
318
+ if count != 1:
319
+ self.error(path, f"matches {count} of oneOf, expected exactly 1")
320
+
321
+ def string(self, value: str, schema: Mapping[str, object], path: str) -> None:
322
+ low, high = schema.get("minLength"), schema.get("maxLength")
323
+ if low is not None and len(value) < low: # type: ignore[operator]
324
+ self.error(path, f"shorter than {low} characters")
325
+ if high is not None and len(value) > high: # type: ignore[operator]
326
+ self.error(path, f"longer than {high} characters")
327
+ pattern = schema.get("pattern")
328
+ if isinstance(pattern, str) and not _pattern(pattern).search(value):
329
+ self.error(path, f"does not match {pattern!r}")
330
+
331
+ def object(
332
+ self, value: Mapping[object, object], schema: Mapping[str, object], path: str, depth: int
333
+ ) -> None:
334
+ for key in value:
335
+ if not isinstance(key, str):
336
+ self.error(path, f"non-string key {key!r}")
337
+ properties = schema.get("properties")
338
+ props: Mapping[str, object] = properties if isinstance(properties, Mapping) else {}
339
+ for name in schema.get("required", ()): # type: ignore[union-attr]
340
+ if name not in value:
341
+ self.error(path, f"missing required property {name!r}")
342
+ additional = schema.get("additionalProperties")
343
+ for key, item in value.items():
344
+ if not isinstance(key, str):
345
+ continue
346
+ if key in props:
347
+ self.check(item, props[key], _pointer(path, key), depth + 1) # type: ignore[arg-type]
348
+ elif additional is False:
349
+ self.error(path, f"unexpected property {key!r}")
350
+ elif isinstance(additional, Mapping):
351
+ self.check(item, additional, _pointer(path, key), depth + 1)
352
+
353
+
354
+ def _kind(value: object) -> str:
355
+ if value is None:
356
+ return "null"
357
+ if isinstance(value, bool):
358
+ return "boolean"
359
+ if _is_number(value):
360
+ return "number"
361
+ if isinstance(value, str):
362
+ return "string"
363
+ if isinstance(value, list | tuple):
364
+ return "array"
365
+ if isinstance(value, Mapping):
366
+ return "object"
367
+ return type(value).__name__
368
+
369
+
370
+ def validate(instance: object, schema: Mapping[str, object]) -> list[str]:
371
+ """Errors of ``instance`` against ``schema`` as ``<json-pointer>: <problem>`` (empty if valid).
372
+
373
+ Raises :class:`SchemaError` when the schema is malformed or uses a
374
+ keyword outside the supported subset.
375
+ """
376
+ _check_schema(schema)
377
+ validator = _Validator(schema)
378
+ validator.check(instance, schema, "", 0)
379
+ return validator.errors
380
+
381
+
382
+ def is_valid(instance: object, schema: Mapping[str, object]) -> bool:
383
+ """Does ``instance`` satisfy ``schema``?"""
384
+ return not validate(instance, schema)