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/cli_init.py ADDED
@@ -0,0 +1,254 @@
1
+ """``codeveto init github|forgejo [--repo PATH] [--force] [...]``: write a CI workflow.
2
+
3
+ - ``github`` writes ``.github/workflows/codeveto.yml``: the SPEC 10.4 template
4
+ (``pull_request_target`` and ``merge_group``, block-style concurrency,
5
+ ``actions/checkout`` pinned by commit SHA). The CodeVeto action is pinned to
6
+ ``--action-sha`` or :data:`ACTION_SHA`, the commit of this version that the
7
+ release workflow writes into the built package (a commit cannot contain its
8
+ own SHA). Without either, ``init github`` refuses, unless ``--allow-tag``
9
+ asks for the movable ``vX.Y`` minor tag, which the file then says plainly.
10
+ - ``forgejo`` writes ``.forgejo/workflows/codeveto.yml`` (SPEC 10.5): ``run:``
11
+ steps only, installing exactly this version with ``--require-hashes``. The
12
+ wheel hashes come from PyPI's JSON API for this version (HTTPS to
13
+ ``pypi.org`` only), or from ``--hash`` when given. Without network and
14
+ without ``--hash`` it fails with instructions: it never writes an unpinned
15
+ install.
16
+
17
+ An existing workflow is never overwritten without ``--force``, and a
18
+ symlinked ``.github``/``.forgejo`` or ``workflows`` directory or workflow file
19
+ is refused (the write could land outside the repository). The file is written
20
+ atomically. Exit 0 on success, 2 otherwise.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import os
27
+ import re
28
+ import tempfile
29
+ import urllib.error
30
+ import urllib.request
31
+ from collections.abc import Callable, Sequence
32
+ from importlib import resources
33
+ from pathlib import Path
34
+ from typing import Any
35
+ from urllib.parse import urlsplit
36
+
37
+ from codeveto import __version__, jsonsafe
38
+ from codeveto.cli import error_line
39
+
40
+ __all__ = [
41
+ "ACTION_REPO",
42
+ "ACTION_SHA",
43
+ "CHECKOUT",
44
+ "InitError",
45
+ "forgejo_workflow",
46
+ "github_workflow",
47
+ "pypi_wheel_hashes",
48
+ "run",
49
+ ]
50
+
51
+ ACTION_REPO = "spink-dev/codeveto"
52
+ #: Commit SHA of this version's release, filled in at release; ``None`` until then.
53
+ ACTION_SHA: str | None = "b53913a31cc4f55df23b02bb431a093804493e9b"
54
+ #: ``actions/checkout`` pinned by commit SHA (the version this repository's CI uses).
55
+ CHECKOUT = "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1"
56
+ PYPI_URL = "https://pypi.org/pypi/codeveto/{version}/json"
57
+ PYPI_TIMEOUT = 20
58
+ PYPI_MAX_BYTES = 4 * 1024 * 1024
59
+ _SHA256 = re.compile(r"sha256:[0-9a-f]{64}")
60
+ _OID = re.compile(r"[0-9a-f]{40}")
61
+ _VERSION = re.compile(r"\d+\.\d+\.\d+")
62
+ _TARGETS = {
63
+ "github": Path(".github") / "workflows" / "codeveto.yml",
64
+ "forgejo": Path(".forgejo") / "workflows" / "codeveto.yml",
65
+ }
66
+
67
+
68
+ class InitError(Exception):
69
+ """``init`` cannot write the workflow; the message says what to do."""
70
+
71
+
72
+ def _template(name: str) -> str:
73
+ return resources.files("codeveto").joinpath(f"data/templates/{name}").read_text("utf-8")
74
+
75
+
76
+ def _minor_tag(version: str) -> str:
77
+ major, minor = version.split(".")[:2]
78
+ return f"v{major}.{minor}"
79
+
80
+
81
+ def github_workflow(
82
+ version: str = __version__, action_sha: str | None = None, *, allow_tag: bool = False
83
+ ) -> str:
84
+ """The GitHub workflow text for ``version``, pinned to ``action_sha``.
85
+
86
+ Without a SHA it raises :class:`InitError`, unless ``allow_tag`` pins the
87
+ movable minor tag (with a comment saying it is one).
88
+ """
89
+ if action_sha is not None:
90
+ if not _OID.fullmatch(action_sha):
91
+ raise InitError("--action-sha must be a full 40-hex lowercase commit SHA")
92
+ action = f"{ACTION_REPO}@{action_sha} # v{version}"
93
+ elif allow_tag:
94
+ action = (
95
+ f"{ACTION_REPO}@{_minor_tag(version)} "
96
+ "# a movable tag, not a pin: replace it with a release's full commit SHA"
97
+ )
98
+ else:
99
+ raise InitError(
100
+ f"this codeveto build does not know the commit of its release (v{version}); "
101
+ "pass --action-sha <full commit SHA of the release> to pin the action, "
102
+ f"or --allow-tag to use the movable {_minor_tag(version)} tag"
103
+ )
104
+ text = _template("github-codeveto.yml")
105
+ return text.replace("@@CHECKOUT@@", CHECKOUT).replace("@@ACTION@@", action)
106
+
107
+
108
+ def forgejo_workflow(hashes: Sequence[str], version: str = __version__) -> str:
109
+ """The Forgejo workflow text installing ``codeveto==version`` with ``hashes``."""
110
+ if not hashes or not all(_SHA256.fullmatch(h) for h in hashes):
111
+ raise InitError("every --hash must be sha256: followed by 64 lowercase hex digits")
112
+ if not _VERSION.fullmatch(version):
113
+ raise InitError(f"codeveto {version} is not a release version; pass a release's hashes")
114
+ requirement = " ".join([f"codeveto=={version}", *(f"--hash={h}" for h in hashes)])
115
+ text = _template("forgejo-codeveto.yml")
116
+ return text.replace("@@VERSION@@", version).replace("@@REQUIREMENT@@", requirement)
117
+
118
+
119
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
120
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
121
+ return None # a redirect becomes an HTTPError: hashes come from pypi.org only
122
+
123
+
124
+ def _on_pypi(url: str) -> bool:
125
+ parts = urlsplit(url)
126
+ return parts.scheme == "https" and parts.hostname == "pypi.org" and parts.port in (None, 443)
127
+
128
+
129
+ def _fetch_pypi(url: str) -> bytes:
130
+ if not _on_pypi(url):
131
+ raise InitError("hashes are only ever taken from https://pypi.org")
132
+ request = urllib.request.Request( # noqa: S310 - https://pypi.org only (checked)
133
+ url, headers={"Accept": "application/json", "User-Agent": f"codeveto/{__version__}"}
134
+ )
135
+ opener = urllib.request.build_opener(_NoRedirect())
136
+ with opener.open(request, timeout=PYPI_TIMEOUT) as response:
137
+ if not _on_pypi(response.geturl()):
138
+ raise InitError("PyPI's answer came from another host")
139
+ return response.read(PYPI_MAX_BYTES + 1) # type: ignore[no-any-return]
140
+
141
+
142
+ def pypi_wheel_hashes(
143
+ version: str = __version__, fetch: Callable[[str], bytes] | None = None
144
+ ) -> list[str]:
145
+ """``sha256:<hex>`` of every wheel PyPI lists for ``codeveto==version``."""
146
+ if not _VERSION.fullmatch(version):
147
+ raise InitError(
148
+ f"codeveto {version} is not a release version, so PyPI has no hashes for it; "
149
+ "pass --hash sha256:<wheel digest> of the release to install"
150
+ )
151
+ url = PYPI_URL.format(version=version)
152
+ hint = (
153
+ f"pass --hash sha256:<digest> of the codeveto-{version} wheel "
154
+ f"(listed at https://pypi.org/project/codeveto/{version}/#files) to pin it without "
155
+ "network access; init never writes an unpinned install"
156
+ )
157
+ try:
158
+ raw = (fetch or _fetch_pypi)(url)
159
+ except urllib.error.HTTPError as exc:
160
+ raise InitError(f"PyPI has no codeveto {version} (HTTP {exc.code}); {hint}") from None
161
+ except (urllib.error.URLError, OSError, TimeoutError):
162
+ raise InitError(f"could not reach PyPI to pin codeveto {version}; {hint}") from None
163
+ if len(raw) > PYPI_MAX_BYTES:
164
+ raise InitError(f"PyPI's answer for codeveto {version} is too large; {hint}")
165
+ try:
166
+ data: Any = jsonsafe.loads(raw.decode("utf-8"))
167
+ except (UnicodeDecodeError, ValueError):
168
+ raise InitError(f"PyPI's answer for codeveto {version} is not JSON; {hint}") from None
169
+ info = data.get("info") if isinstance(data, dict) else None
170
+ files = data.get("urls") if isinstance(data, dict) else None
171
+ if not isinstance(info, dict) or info.get("version") != version or not isinstance(files, list):
172
+ raise InitError(f"PyPI's answer is not for codeveto {version}; {hint}")
173
+ if info.get("yanked") is True:
174
+ raise InitError(f"codeveto {version} was yanked from PyPI; use another release")
175
+ hashes = []
176
+ for entry in files:
177
+ if not isinstance(entry, dict) or entry.get("packagetype") != "bdist_wheel":
178
+ continue
179
+ if entry.get("yanked") is not False:
180
+ continue # yanked (or of unknown status): never pinned
181
+ digest = (entry.get("digests") or {}).get("sha256")
182
+ if isinstance(digest, str) and re.fullmatch(r"[0-9a-f]{64}", digest):
183
+ hashes.append(f"sha256:{digest}")
184
+ if not hashes:
185
+ raise InitError(f"PyPI lists no wheel for codeveto {version}; {hint}")
186
+ return sorted(set(hashes))
187
+
188
+
189
+ def _target(repo: Path, forge: str) -> Path:
190
+ if not repo.is_dir():
191
+ raise InitError(f"{repo} is not a directory")
192
+ relative = _TARGETS[forge]
193
+ current = repo
194
+ for part in relative.parts:
195
+ current = current / part
196
+ if current.is_symlink():
197
+ raise InitError(f"{current} is a symbolic link; refusing to write through it")
198
+ return repo / relative
199
+
200
+
201
+ def _write(path: Path, text: str, *, force: bool) -> None:
202
+ if (path.exists() or path.is_symlink()) and not force:
203
+ raise InitError(f"{path} already exists; pass --force to overwrite it")
204
+ path.parent.mkdir(parents=True, exist_ok=True)
205
+ fd, tmp = tempfile.mkstemp(prefix=".codeveto-", suffix=".yml", dir=path.parent)
206
+ try:
207
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream:
208
+ stream.write(text)
209
+ os.replace(tmp, path)
210
+ except BaseException:
211
+ Path(tmp).unlink(missing_ok=True)
212
+ raise
213
+
214
+
215
+ _NEXT = {
216
+ "github": (
217
+ "Next: commit it on the default branch, make 'codeveto / review' a required check, "
218
+ "and protect .github/workflows/ with CODEOWNERS or a ruleset."
219
+ ),
220
+ "forgejo": (
221
+ "Next: commit it on the default branch, make the 'codeveto / review' status required "
222
+ "in branch protection, and protect .forgejo/workflows/."
223
+ ),
224
+ }
225
+
226
+
227
+ def run(args: argparse.Namespace, *, fetch: Callable[[str], bytes] | None = None) -> int:
228
+ """Write the workflow for ``args.forge`` into ``args.repo``."""
229
+ repo = Path(args.repo or ".")
230
+ try:
231
+ target = _target(repo, args.forge)
232
+ if (target.exists() or target.is_symlink()) and not args.force:
233
+ raise InitError(f"{target} already exists; pass --force to overwrite it")
234
+ if args.forge == "github":
235
+ sha = getattr(args, "action_sha", None) or ACTION_SHA
236
+ text = github_workflow(action_sha=sha, allow_tag=getattr(args, "allow_tag", False))
237
+ else:
238
+ hashes = list(args.hash) if args.hash else pypi_wheel_hashes(fetch=fetch)
239
+ text = forgejo_workflow(hashes)
240
+ _write(target, text, force=args.force)
241
+ except InitError as exc:
242
+ error_line(f"init: {exc}")
243
+ return 2
244
+ except OSError as exc:
245
+ error_line(f"init: cannot write the workflow ({type(exc).__name__})")
246
+ return 2
247
+ print(f"wrote {target}")
248
+ if args.forge == "github" and not (getattr(args, "action_sha", None) or ACTION_SHA):
249
+ print(
250
+ f"note: the action uses the movable {_minor_tag(__version__)} tag; replace it "
251
+ "with the release's full commit SHA."
252
+ )
253
+ print(_NEXT[args.forge])
254
+ return 0
codeveto/cli_mcp.py ADDED
@@ -0,0 +1,29 @@
1
+ """``codeveto mcp``: the stdio MCP server (SPEC 10.1); see :mod:`codeveto.integrations.mcp`.
2
+
3
+ The repository, revision flags and trust anchor are resolved once, here, and
4
+ reported on stderr; stdout then carries only protocol messages until the
5
+ client closes stdin (exit 0). A usage error, or a revision or anchor that
6
+ cannot be resolved, exits 2 before anything is served.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+
13
+ from codeveto.cli import error_line
14
+ from codeveto.integrations import mcp
15
+ from codeveto.render import safe
16
+
17
+ __all__ = ["run"]
18
+
19
+
20
+ def run(args: argparse.Namespace) -> int:
21
+ try:
22
+ binding = mcp.bind(args)
23
+ except mcp.BindError as exc:
24
+ error_line(f"usage: {exc}")
25
+ return 2
26
+ error_line(f"mcp: serving {safe.text(binding.repo, 500)}: {binding.describe()}")
27
+ for note in binding.anchor_notes:
28
+ error_line(f"mcp: note: {note}")
29
+ return mcp.serve(binding)
@@ -0,0 +1,35 @@
1
+ """``codeveto packets``: write AI review packets for a harness (SPEC 9.1, 9.4 step 1).
2
+
3
+ Same revision flags, anchor and trusted config as ``review``; the output is
4
+ the packets document of :func:`codeveto.ai.packets.PacketSet.document` as
5
+ indented ASCII JSON, to stdout or atomically to ``--output``. Exit 0 when the
6
+ document was written; 2 for a usage, config or Git error. No network is used.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+
14
+ from codeveto import cli_review
15
+ from codeveto.ai import harness
16
+ from codeveto.cli import error_line, write_stdout
17
+
18
+ __all__ = ["run"]
19
+
20
+
21
+ def run(args: argparse.Namespace) -> int:
22
+ """Build the packets of the selected change and write the document."""
23
+ problem = cli_review.usage_problem(args)
24
+ if problem is not None:
25
+ error_line(f"usage: {problem}")
26
+ return 2
27
+ packets = harness.packets_for(cli_review.prepare(args))
28
+ if packets.packets and not packets.redaction:
29
+ error_line("note: the secrets pack is not installed, so these packets are not redacted")
30
+ text = json.dumps(packets.document(), indent=2, ensure_ascii=True) + "\n"
31
+ if args.output is not None:
32
+ cli_review.write_atomic(args.output, text)
33
+ else:
34
+ write_stdout(text)
35
+ return 0
@@ -0,0 +1,29 @@
1
+ """``codeveto publish github|forgejo --report FILE``: publish a report to a forge (SPEC 10.4, 10.5).
2
+
3
+ Runs inside the forge's CI job and reads its context from the runner's
4
+ environment (``GITHUB_EVENT_NAME``, ``GITHUB_EVENT_PATH``,
5
+ ``GITHUB_REPOSITORY``, ``GITHUB_SERVER_URL``, ``GITHUB_API_URL``,
6
+ ``GITHUB_STEP_SUMMARY``), the token from ``GITHUB_TOKEN``, and two switches
7
+ the action sets from its inputs: ``CODEVETO_COMMENT`` (default ``true``) and
8
+ ``CODEVETO_SARIF`` (default ``false``, GitHub only).
9
+
10
+ The report is untrusted (:mod:`codeveto.publish.untrusted`). Exit 0 when
11
+ everything was published, 2 when anything could not be (every problem is a
12
+ job-summary warning). The review's own exit code is never changed: the
13
+ action and the workflow template take it from the review step.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import os
20
+
21
+ from codeveto.publish import forgejo, github
22
+
23
+ __all__ = ["run"]
24
+
25
+
26
+ def run(args: argparse.Namespace) -> int:
27
+ """Publish ``args.report`` to ``args.forge``."""
28
+ publisher = github.publish if args.forge == "github" else forgejo.publish
29
+ return publisher(dict(os.environ), args.report)