python2rust 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 (102) hide show
  1. python2rust/__init__.py +8 -0
  2. python2rust/__main__.py +5 -0
  3. python2rust/_core.py +44 -0
  4. python2rust/agent/__init__.py +0 -0
  5. python2rust/agent/agents.py +333 -0
  6. python2rust/agent/apply.py +516 -0
  7. python2rust/agent/finish.py +295 -0
  8. python2rust/agent/fixers.py +229 -0
  9. python2rust/agent/loop.py +441 -0
  10. python2rust/agent/patches.py +1165 -0
  11. python2rust/agent/port.py +579 -0
  12. python2rust/agent/prompts/judge_v2.md +96 -0
  13. python2rust/agent/review.py +34 -0
  14. python2rust/agent/rustlex.py +232 -0
  15. python2rust/cli/__init__.py +0 -0
  16. python2rust/cli/doctor.py +62 -0
  17. python2rust/cli/inputs.py +105 -0
  18. python2rust/cli/main.py +1162 -0
  19. python2rust/cli/ops.py +642 -0
  20. python2rust/cli/workflow.py +178 -0
  21. python2rust/core/__init__.py +38 -0
  22. python2rust/core/config.py +263 -0
  23. python2rust/core/constructs.py +124 -0
  24. python2rust/core/diagnostics.py +280 -0
  25. python2rust/core/emit/__init__.py +5 -0
  26. python2rust/core/emit/crates.py +51 -0
  27. python2rust/core/emit/render.py +561 -0
  28. python2rust/core/emit/schema.py +168 -0
  29. python2rust/core/emit/translate.py +304 -0
  30. python2rust/core/frontend/__init__.py +1 -0
  31. python2rust/core/frontend/module.py +896 -0
  32. python2rust/core/frontend/names.py +129 -0
  33. python2rust/core/frontend/project.py +277 -0
  34. python2rust/core/frontend/project_imports.py +173 -0
  35. python2rust/core/frontend/symbols.py +132 -0
  36. python2rust/core/frontend/walrus.py +59 -0
  37. python2rust/core/ir/__init__.py +1 -0
  38. python2rust/core/ir/nodes.py +675 -0
  39. python2rust/core/ir/rtypes.py +122 -0
  40. python2rust/core/ir/types.py +326 -0
  41. python2rust/core/lower/__init__.py +1 -0
  42. python2rust/core/lower/calls.py +1125 -0
  43. python2rust/core/lower/context.py +223 -0
  44. python2rust/core/lower/exceptions.py +317 -0
  45. python2rust/core/lower/exprs.py +845 -0
  46. python2rust/core/lower/fstrings.py +141 -0
  47. python2rust/core/lower/funcs.py +276 -0
  48. python2rust/core/lower/lowerer.py +366 -0
  49. python2rust/core/lower/modelcalls.py +195 -0
  50. python2rust/core/lower/models.py +645 -0
  51. python2rust/core/lower/stmts.py +722 -0
  52. python2rust/core/lower/testing.py +601 -0
  53. python2rust/core/lower/validation.py +253 -0
  54. python2rust/core/passes/__init__.py +1 -0
  55. python2rust/core/passes/aliasing.py +311 -0
  56. python2rust/core/passes/analysis.py +207 -0
  57. python2rust/core/passes/devirt.py +329 -0
  58. python2rust/core/passes/ownership.py +259 -0
  59. python2rust/core/passes/raises.py +275 -0
  60. python2rust/core/rt_lib.rs +2071 -0
  61. python2rust/data/README.md +81 -0
  62. python2rust/data/py2many_builtins.toml +4744 -0
  63. python2rust/errors.py +28 -0
  64. python2rust/py.typed +0 -0
  65. python2rust/report/__init__.py +0 -0
  66. python2rust/report/constructs.py +31 -0
  67. python2rust/report/contract.py +688 -0
  68. python2rust/report/corpus.py +323 -0
  69. python2rust/report/explain.py +168 -0
  70. python2rust/report/schemas.py +914 -0
  71. python2rust/server/__init__.py +0 -0
  72. python2rust/server/mcp_server.py +289 -0
  73. python2rust/server/mcp_workflow.py +100 -0
  74. python2rust/skill/SKILL.md +214 -0
  75. python2rust/verify/__init__.py +0 -0
  76. python2rust/verify/check.py +1135 -0
  77. python2rust/verify/equiv/__init__.py +1264 -0
  78. python2rust/verify/equiv/compare.py +455 -0
  79. python2rust/verify/equiv/harness.py +505 -0
  80. python2rust/verify/equiv/judge.py +358 -0
  81. python2rust/verify/equiv/procs.py +255 -0
  82. python2rust/verify/equiv/runner.py +248 -0
  83. python2rust/verify/equiv/types.py +543 -0
  84. python2rust/verify/keystore.py +76 -0
  85. python2rust/verify/ladder.py +396 -0
  86. python2rust/verify/sandbox.py +370 -0
  87. python2rust/verify/testrun.py +280 -0
  88. python2rust/workflow/__init__.py +0 -0
  89. python2rust/workflow/brief.py +312 -0
  90. python2rust/workflow/interview.py +366 -0
  91. python2rust/workflow/layout.py +103 -0
  92. python2rust/workflow/planner.py +409 -0
  93. python2rust/workflow/project.py +134 -0
  94. python2rust/workflow/schemas.py +265 -0
  95. python2rust/workflow/state.py +392 -0
  96. python2rust/workflow/staticscan.py +209 -0
  97. python2rust-0.1.0.dist-info/METADATA +395 -0
  98. python2rust-0.1.0.dist-info/RECORD +102 -0
  99. python2rust-0.1.0.dist-info/WHEEL +4 -0
  100. python2rust-0.1.0.dist-info/entry_points.txt +4 -0
  101. python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
@@ -0,0 +1,1162 @@
1
+ """Command-line interface.
2
+
3
+ Contract (stable, see docs/AGENT_WORKFLOW.md):
4
+ * every command accepts --json: stdout is then exactly one JSON document, nothing else;
5
+ human commentary goes to stderr (silenced by --quiet)
6
+ * exit codes: 0 ok, 1 TODOs/errors remain or unverified, 2 usage, 3 internal, 4 does not verify
7
+ * never interactive, output order is stable
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import sys
16
+ import traceback
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass, replace
19
+ from pathlib import Path
20
+ from typing import Any, NoReturn
21
+
22
+ from python2rust import __version__
23
+ from python2rust.agent.agents import BACKENDS
24
+ from python2rust.errors import (
25
+ EXIT_COMPILE,
26
+ EXIT_FINDINGS,
27
+ EXIT_INTERNAL,
28
+ EXIT_OK,
29
+ EXIT_USAGE,
30
+ InternalError,
31
+ RustSideError,
32
+ UsageError,
33
+ )
34
+
35
+ EXIT_CODES = {
36
+ "0": "ok: nothing left to do",
37
+ "1": "TODOs or error diagnostics remain, or the result could not be verified (for example no cargo)",
38
+ "2": "usage error: bad flag, missing path, invalid config, unknown id",
39
+ "3": "internal error, missing core or missing optional dependency",
40
+ "4": "the Rust does not compile or verify: compile errors, a failing rung, a rejected fix",
41
+ }
42
+
43
+ EPILOG = """\
44
+ exit codes: 0 ok | 1 TODOs/errors remain (or unverified) | 2 usage error | 3 internal error (incl. missing core) | 4 does not compile/verify
45
+ every command takes --json (one JSON document on stdout, human text on stderr). `-` reads stdin.
46
+ agent workflow: python2rust skill | schemas: python2rust schema
47
+ """
48
+
49
+
50
+ @dataclass
51
+ class Outcome:
52
+ doc: dict[str, Any] # the --json document
53
+ code: int = EXIT_OK
54
+ text: str | None = None # stdout in non-JSON mode
55
+ note: str | None = None # one human line on stderr (unless --quiet)
56
+
57
+
58
+ class _Parser(argparse.ArgumentParser):
59
+ def error(self, message: str) -> NoReturn:
60
+ raise UsageError(message)
61
+
62
+
63
+ def _common() -> _Parser:
64
+ p = _Parser(add_help=False)
65
+ p.add_argument(
66
+ "--json",
67
+ action="store_true",
68
+ default=argparse.SUPPRESS,
69
+ help="emit one JSON document on stdout",
70
+ )
71
+ p.add_argument(
72
+ "--quiet",
73
+ "-q",
74
+ action="store_true",
75
+ default=argparse.SUPPRESS,
76
+ help="no human commentary on stderr",
77
+ )
78
+ return p
79
+
80
+
81
+ def _unit_opt(p: argparse.ArgumentParser) -> None:
82
+ p.add_argument(
83
+ "--unit",
84
+ metavar="UNIT",
85
+ help="a unit of the workflow plan: translate the WHOLE planned project (every module and test, "
86
+ "imports between units resolved) and work on / report only this unit's files; takes no PATH",
87
+ )
88
+
89
+
90
+ def _translate_opts(p: argparse.ArgumentParser, *, unit: bool = False) -> None:
91
+ p.add_argument(
92
+ "paths",
93
+ nargs="*" if unit else "+",
94
+ metavar="PATH",
95
+ help="python files, directories, or - for stdin" + (" (none with --unit)" if unit else ""),
96
+ )
97
+ if unit:
98
+ _unit_opt(p)
99
+ p.add_argument(
100
+ "--config",
101
+ metavar="TOML",
102
+ help="config file: import_map, library_map, type_map, review_patterns, [patch_gate]",
103
+ )
104
+ p.add_argument(
105
+ "--no-fmt", action="store_true", help="skip rustfmt (sets Config.format = false)"
106
+ )
107
+ p.add_argument(
108
+ "--vendor-runtime",
109
+ action="store_true",
110
+ help="emit the runtime helpers into the output instead of depending on python2rust-rt "
111
+ "(sets Config.vendor_runtime = true)",
112
+ )
113
+ p.add_argument(
114
+ "--per-file",
115
+ action="store_true",
116
+ help="translate every file on its own; by default the files under one directory are "
117
+ "translated as a project, so imports between them resolve",
118
+ )
119
+ p.add_argument(
120
+ "--stdin-filename",
121
+ default="<stdin>.py",
122
+ metavar="NAME",
123
+ help="name used for - in diagnostics",
124
+ )
125
+ p.add_argument(
126
+ "--project",
127
+ default=".",
128
+ metavar="DIR",
129
+ help="project root holding .python2rust/ (default: .)",
130
+ )
131
+ p.add_argument("--no-patches", action="store_true", help="do not re-apply stored patches")
132
+
133
+
134
+ def _cargo_opts(p: argparse.ArgumentParser) -> None:
135
+ p.add_argument("--offline", action="store_true", help="pass --offline to cargo")
136
+ p.add_argument(
137
+ "--deps-from", metavar="CARGO_TOML", help="copy the dependency table from this Cargo.toml"
138
+ )
139
+ p.add_argument(
140
+ "--target-dir", metavar="DIR", help="cargo target dir (default: a per-user cache)"
141
+ )
142
+ p.add_argument(
143
+ "--timeout", type=float, default=300, metavar="SECONDS", help="cargo timeout (default 300)"
144
+ )
145
+ p.add_argument(
146
+ "--allow-unvetted-deps",
147
+ action="store_true",
148
+ help="accept a --deps-from table with crates off the vetted allow-list, git or alternate-registry "
149
+ "dependencies, build scripts, [build-dependencies], [patch]. Extend the allow-list with [deps] allow "
150
+ "in python2rust.toml instead where you can",
151
+ )
152
+ p.add_argument(
153
+ "--allow-unsandboxed-compile",
154
+ action="store_true",
155
+ help="compile even when no OS sandbox (sandbox-exec, bwrap) exists. Rust that is compiled "
156
+ "is sandboxed (no network, reads confined) by default; without a sandbox tool the run "
157
+ "refuses unless you pass this, and then cargo, build scripts and proc-macros run with your "
158
+ "full access",
159
+ )
160
+
161
+
162
+ def _equiv_opts(p: argparse.ArgumentParser, *, for_apply: bool = False) -> None:
163
+ """Flags of the `equiv` rung (verify --level equiv, apply --run-python)."""
164
+ g = p.add_argument_group("equivalence (--level equiv): compiles AND gives the same output")
165
+ g.add_argument(
166
+ "--run-python",
167
+ action="store_true",
168
+ help="allow EXECUTING the Python module in a child process with best-effort limits, not an OS sandbox (required for equiv)",
169
+ )
170
+ g.add_argument(
171
+ "--equiv-timeout", type=float, default=5.0, metavar="SECONDS",
172
+ help="per-call timeout for the Python and the Rust side (default 5)",
173
+ ) # fmt: skip
174
+ g.add_argument(
175
+ "--equiv-memory", type=int, default=1024, metavar="MIB",
176
+ help="memory limit of the Python runner (default 1024)",
177
+ ) # fmt: skip
178
+ g.add_argument(
179
+ "--equiv-inputs", type=int, default=50, metavar="N",
180
+ help="generated inputs per function (default 50; doctests and test-file cases come on top)",
181
+ ) # fmt: skip
182
+ g.add_argument("--equiv-seed", type=int, default=0, metavar="N", help="seed of the generator")
183
+ g.add_argument(
184
+ "--compare",
185
+ choices=("functional", "strict", "canonical"),
186
+ default="functional",
187
+ help="strict: byte equality; functional (default): canonical JSON + [equivalence] profile "
188
+ "rules, then the optional judge; canonical: functional without the judge",
189
+ )
190
+ g.add_argument(
191
+ "--python-path", action="append", default=[], metavar="DIR",
192
+ help="extra sys.path entry for the Python runner (repeatable)",
193
+ ) # fmt: skip
194
+ g.add_argument("--no-judge", action="store_true", help="never ask a judge, even with --agent")
195
+ g.add_argument(
196
+ "--judge-budget", type=int, default=20, metavar="N", help="max judge calls (default 20)"
197
+ )
198
+ g.add_argument(
199
+ "--spot-check", type=int, default=0, metavar="N",
200
+ help="re-judge N random judged passes with a third prompt; report the disagreement rate",
201
+ ) # fmt: skip
202
+ g.add_argument(
203
+ "--accept-judged", action="store_true",
204
+ help="count judged passes as verified for the exit code (they stay listed separately)",
205
+ ) # fmt: skip
206
+ g.add_argument(
207
+ "--agent", choices=BACKENDS, default="none",
208
+ help="judge backend for outputs the rules cannot settle; none (default) sends nothing",
209
+ ) # fmt: skip
210
+ g.add_argument("--agent-cmd", metavar="CMD", help='command for --agent cmd (e.g. "claude -p")')
211
+ g.add_argument("--model", metavar="NAME", help="model for anthropic/openai/azure")
212
+ g.add_argument(
213
+ "--base-url", metavar="URL", help="endpoint override (azure: full deployment URL)"
214
+ )
215
+ g.add_argument(
216
+ "--openai-api", choices=("chat", "responses"), default="chat",
217
+ help="OpenAI-compatible API flavour",
218
+ ) # fmt: skip
219
+ g.add_argument("--verbose", action="store_true", help="print judge prompts on stderr")
220
+ if for_apply:
221
+ g.add_argument(
222
+ "--ack-review", metavar="TODO_ID",
223
+ help="accept a judged-only equivalence pass for this needs_review TODO",
224
+ ) # fmt: skip
225
+ g.add_argument(
226
+ "--no-equiv", action="store_true",
227
+ help="accept the fix at check+tests without comparing it with the Python (recorded in the "
228
+ "document and the patch metadata). By default an applicable function needs --run-python",
229
+ ) # fmt: skip
230
+ g.add_argument(
231
+ "--require-equiv", action="store_true",
232
+ help="alias of the default: equivalence is required whenever it is applicable",
233
+ ) # fmt: skip
234
+
235
+
236
+ RUN_PYTHON_WARNING = (
237
+ "python2rust: WARNING: --run-python EXECUTES the Python module (top-level code included) in a "
238
+ "child process with best-effort time, memory, and network limits. It is not an OS sandbox. "
239
+ "Only use it on code you trust."
240
+ )
241
+
242
+
243
+ def _equiv_options(args: argparse.Namespace) -> Any:
244
+ """`EquivOptions` from the flags; builds the judge backend (None = nothing is ever sent)."""
245
+ from python2rust.agent import agents
246
+ from python2rust.verify.equiv import EquivOptions
247
+ from python2rust.verify.equiv.compare import load_profile
248
+
249
+ judge_off = args.no_judge or args.compare in ("strict", "canonical")
250
+ backend = None if judge_off else agents.make_backend(
251
+ args.agent, command=args.agent_cmd, model=args.model, base_url=args.base_url,
252
+ openai_api=args.openai_api, timeout=120, verbose=args.verbose,
253
+ ) # fmt: skip
254
+ if backend is not None: # always shown, even with --quiet: this is what leaves the machine
255
+ print(
256
+ f"python2rust: --agent {args.agent}: outputs the rules cannot settle are judged by the "
257
+ "agent; it is SENT the function's Python and Rust source and the input and output "
258
+ "values of that case (nothing else). --no-judge or --agent none sends nothing.",
259
+ file=sys.stderr,
260
+ )
261
+ return EquivOptions(
262
+ call_timeout=args.equiv_timeout, memory_mb=args.equiv_memory, inputs=args.equiv_inputs,
263
+ compare="strict" if args.compare == "strict" else "functional", seed=args.equiv_seed,
264
+ profile=load_profile(args.config), backend=backend, judge_budget=args.judge_budget,
265
+ spot_check=args.spot_check, accept_judged=args.accept_judged,
266
+ judge_cache=Path(args.project) / ".python2rust" / "cache" / "judge",
267
+ python_path=args.python_path, deps_from=args.deps_from, offline=args.offline,
268
+ timeout=args.timeout, target_dir=args.target_dir,
269
+ ) # fmt: skip
270
+
271
+
272
+ def build_parser() -> argparse.ArgumentParser:
273
+ from python2rust.verify.ladder import LEVELS
274
+
275
+ common = _common()
276
+ parser = _Parser(
277
+ prog="python2rust",
278
+ description="Typed Python to Rust, built for AI agents.",
279
+ epilog=EPILOG,
280
+ formatter_class=argparse.RawDescriptionHelpFormatter,
281
+ )
282
+ parser.add_argument("--version", action="version", version=f"python2rust {__version__}")
283
+ parser.add_argument("--json", action="store_true", help="emit one JSON document on stdout")
284
+ parser.add_argument("--quiet", "-q", action="store_true", help="no human commentary on stderr")
285
+ sub = parser.add_subparsers(dest="command", metavar="COMMAND", parser_class=_Parser)
286
+
287
+ def add(
288
+ name: str, func: Callable[[argparse.Namespace], Outcome], help: str
289
+ ) -> argparse.ArgumentParser:
290
+ p = sub.add_parser(name, parents=[common], help=help, description=help)
291
+ p.set_defaults(func=func)
292
+ return p
293
+
294
+ p = add(
295
+ "translate",
296
+ cmd_translate,
297
+ "translate python files to Rust (+ .todo.json, .rs.map, diagnostics)",
298
+ )
299
+ _translate_opts(p)
300
+ p.add_argument(
301
+ "-o",
302
+ "--out",
303
+ metavar="DIR",
304
+ help="write .rs, .rs.map, .todo.json and .diagnostics.json below DIR",
305
+ )
306
+ p.add_argument(
307
+ "--stdout", action="store_true", help="print the Rust to stdout (single input, no --json)"
308
+ )
309
+
310
+ p = add(
311
+ "check",
312
+ cmd_check,
313
+ "translate (or take .rs files), cargo check, errors by category mapped to Python lines",
314
+ )
315
+ _translate_opts(p)
316
+ _cargo_opts(p)
317
+ p.add_argument("--keep", action="store_true", help="keep the scratch crate and print its path")
318
+
319
+ p = add("verify", cmd_verify, "run the verification ladder; a verdict per function")
320
+ _translate_opts(p, unit=True)
321
+ _cargo_opts(p)
322
+ _equiv_opts(p)
323
+ p.add_argument(
324
+ "--level", choices=LEVELS, default="check", help="highest rung to run (default: check)"
325
+ )
326
+
327
+ p = add("todos", cmd_todos, "list open TODOs as the agent hand-off contract")
328
+ _translate_opts(p, unit=True)
329
+ p.add_argument(
330
+ "-o", "--out", metavar="DIR", help="also write the Rust files so each todo has a rust_file"
331
+ )
332
+ p.add_argument(
333
+ "--only-review",
334
+ action="store_true",
335
+ help="only TODOs flagged needs_review (patched ones too)",
336
+ )
337
+ p.add_argument(
338
+ "--all", action="store_true", help="include TODOs already fixed by a stored patch"
339
+ )
340
+ p.add_argument("--jsonl", action="store_true", help="one JSON object per line on stdout")
341
+
342
+ p = add(
343
+ "apply",
344
+ cmd_apply,
345
+ "store a fix for one TODO (anti-cheat gate + cargo check); re-applied by translate",
346
+ )
347
+ p.add_argument("todo_id", metavar="TODO_ID", help="the id from `todos`")
348
+ p.add_argument(
349
+ "--patch",
350
+ metavar="FILE",
351
+ help="Rust replacing the todo!() ; - for stdin. Omitted for an id `fn-...` that `port` stored: "
352
+ "the stored fix goes through the full pipeline (project tests, equivalence, gate) and, if it "
353
+ "passes, is accepted",
354
+ )
355
+ p.add_argument(
356
+ "--source",
357
+ action="append",
358
+ default=[],
359
+ metavar="PATH",
360
+ help="python file(s) holding the TODO. A fix is always judged against the project graph: a "
361
+ "planned file (or none) means the whole planned project, a file below a directory `translate` "
362
+ "was given means that directory",
363
+ )
364
+ p.add_argument(
365
+ "--unit",
366
+ metavar="UNIT",
367
+ help="a unit of the workflow plan: the TODO is looked up in the whole planned project "
368
+ "(every module and test), and the tests that import its file run against the fix",
369
+ )
370
+ p.add_argument(
371
+ "--config", metavar="TOML", help="config file; [patch_gate] allow = [...] relaxes the gate"
372
+ )
373
+ p.add_argument(
374
+ "--allow-constant-body",
375
+ action="store_true",
376
+ help="accept a function-body fix that ignores every parameter the Python uses and is only a "
377
+ "constant (same as `constant-body` in [patch_gate] allow); otherwise it is rejected",
378
+ )
379
+ p.add_argument(
380
+ "--author",
381
+ default="agent",
382
+ metavar="TAG",
383
+ help="who wrote the fix (stored in the metadata)",
384
+ )
385
+ p.add_argument(
386
+ "--project",
387
+ default=".",
388
+ metavar="DIR",
389
+ help="project root holding .python2rust/ (default: .)",
390
+ )
391
+ _cargo_opts(p)
392
+ _equiv_opts(p, for_apply=True)
393
+
394
+ p = add(
395
+ "contract",
396
+ cmd_contract,
397
+ "diff the Python app's OpenAPI with the Rust port's (the oracle for FastAPI ports)",
398
+ )
399
+ p.add_argument(
400
+ "python",
401
+ metavar="PYTHON_OPENAPI.json",
402
+ help="app.openapi() of the Python app (.json or .json.gz)",
403
+ )
404
+ p.add_argument(
405
+ "rust",
406
+ metavar="RUST_CRATE_OR_OPENAPI.json",
407
+ help="the Rust side: an OpenAPI JSON file, or a crate directory",
408
+ )
409
+ p.add_argument(
410
+ "--rust-openapi-cmd",
411
+ metavar="CMD",
412
+ help="command printing the Rust OpenAPI JSON (run in the crate directory)",
413
+ )
414
+ p.add_argument(
415
+ "--bin",
416
+ metavar="NAME",
417
+ help="binary of the crate that takes --print-openapi (default: the package name)",
418
+ )
419
+ p.add_argument(
420
+ "--strict-422",
421
+ action="store_true",
422
+ help="also report FastAPI's Python-only 422 HTTPValidationError response",
423
+ )
424
+ p.add_argument(
425
+ "--ignore-operation-id", action="store_true", help="do not report operationId differences"
426
+ )
427
+ p.add_argument(
428
+ "--timeout",
429
+ type=float,
430
+ default=600,
431
+ metavar="SECONDS",
432
+ help="timeout for the Rust OpenAPI command (default 600)",
433
+ )
434
+
435
+ p = add(
436
+ "port",
437
+ cmd_port,
438
+ "translate, compile and repair a Python tree into a Rust crate (agent loop; --agent none = dry run)",
439
+ )
440
+ p.add_argument(
441
+ "paths", nargs="*", metavar="PATH", help="python files or directories (none with --unit)"
442
+ )
443
+ _unit_opt(p)
444
+ p.add_argument(
445
+ "-o",
446
+ "--out",
447
+ required=True,
448
+ metavar="CRATE",
449
+ help="the Rust crate directory (Cargo.toml is created if missing)",
450
+ )
451
+ p.add_argument(
452
+ "--agent",
453
+ choices=BACKENDS,
454
+ default="none",
455
+ help="model backend; none (default) is a dry run that sends nothing",
456
+ )
457
+ p.add_argument(
458
+ "--agent-cmd",
459
+ metavar="CMD",
460
+ help='command for --agent cmd: task JSON on stdin, patch on stdout (e.g. "claude -p")',
461
+ )
462
+ p.add_argument(
463
+ "--strong-agent-cmd",
464
+ metavar="CMD",
465
+ help="stronger command used after --escalate-after failed rounds",
466
+ )
467
+ p.add_argument("--model", metavar="NAME", help="model for anthropic/openai/azure")
468
+ p.add_argument(
469
+ "--strong-model",
470
+ metavar="NAME",
471
+ help="stronger model used after --escalate-after failed rounds",
472
+ )
473
+ p.add_argument(
474
+ "--base-url", metavar="URL", help="endpoint override (Azure-style: the full deployment URL)"
475
+ )
476
+ p.add_argument(
477
+ "--openai-api",
478
+ choices=("chat", "responses"),
479
+ default="chat",
480
+ help="OpenAI-compatible API flavour",
481
+ )
482
+ p.add_argument(
483
+ "--budget-iters", type=int, default=8, metavar="N", help="max rounds (default 8)"
484
+ )
485
+ p.add_argument(
486
+ "--budget-tokens", type=int, default=None, metavar="N", help="stop after about N tokens"
487
+ )
488
+ p.add_argument(
489
+ "--budget-seconds", type=float, default=None, metavar="N", help="stop after N seconds"
490
+ )
491
+ p.add_argument(
492
+ "--escalate-after",
493
+ type=int,
494
+ default=2,
495
+ metavar="K",
496
+ help="failed rounds per function before the next fixer (default 2)",
497
+ )
498
+ p.add_argument(
499
+ "--patience",
500
+ type=int,
501
+ default=2,
502
+ metavar="N",
503
+ help="stop after N rounds without progress (default 2)",
504
+ )
505
+ p.add_argument(
506
+ "--workers", type=int, default=4, metavar="N", help="parallel fixers per round (default 4)"
507
+ )
508
+ p.add_argument(
509
+ "--verbose", action="store_true", help="print the prompts sent to the agent to stderr"
510
+ )
511
+ p.add_argument(
512
+ "--no-fmt", action="store_true", help="skip rustfmt (sets Config.format = false)"
513
+ )
514
+ p.add_argument(
515
+ "--vendor-runtime",
516
+ action="store_true",
517
+ help="emit the runtime helpers instead of depending on python2rust-rt",
518
+ )
519
+ p.add_argument(
520
+ "--config", metavar="TOML", help="config file (import_map, library_map, [patch_gate], ...)"
521
+ )
522
+ p.add_argument(
523
+ "--project",
524
+ default=".",
525
+ metavar="DIR",
526
+ help="project root holding .python2rust/ (default: .)",
527
+ )
528
+ p.add_argument(
529
+ "--stdin-filename",
530
+ default="<stdin>.py",
531
+ metavar="NAME",
532
+ help="name used for - in diagnostics",
533
+ )
534
+ _cargo_opts(p)
535
+
536
+ p = add("explain", cmd_explain, "explain a diagnostic code: meaning, why, fix, before/after")
537
+ p.add_argument("code", metavar="CODE", help="e.g. PY2RS001")
538
+
539
+ p = add("coverage", cmd_coverage, "corpus metrics: functions check-clean, TODOs by construct")
540
+ _translate_opts(p)
541
+ _cargo_opts(p)
542
+ p.add_argument(
543
+ "--level",
544
+ choices=("none", *LEVELS),
545
+ default="check",
546
+ help="ladder rung for check-clean (none: no cargo)",
547
+ )
548
+
549
+ p = add("eval", cmd_eval, "translate + verify a corpus directory; metrics and a README table")
550
+ p.add_argument(
551
+ "corpus", metavar="CORPUS_DIR", help="directory of .py files (+ optional expected.json)"
552
+ )
553
+ p.add_argument(
554
+ "--baseline",
555
+ metavar="FILE|py2many",
556
+ help="an earlier eval --json file, or py2many to compare",
557
+ )
558
+ p.add_argument(
559
+ "--level", choices=LEVELS, default="check", help="highest rung to run (default: check)"
560
+ )
561
+ p.add_argument(
562
+ "--run-py2many",
563
+ action="store_true",
564
+ help="REQUIRED for --baseline py2many: py2many executes code derived from the corpus "
565
+ "(it evals input-derived text), so use it only on corpora you trust",
566
+ )
567
+ p.add_argument(
568
+ "--py2many-cmd",
569
+ metavar="CMD",
570
+ help="command for py2many (default: `py2many` on PATH; never fetched implicitly)",
571
+ )
572
+ p.add_argument("--config", metavar="TOML", help="config file")
573
+ _cargo_opts(p)
574
+
575
+ add("constructs", cmd_constructs, "list Python constructs with status (from the core)")
576
+
577
+ p = add("schema", cmd_schema, "print the JSON Schema of a --json output")
578
+ p.add_argument(
579
+ "name",
580
+ nargs="?",
581
+ metavar="NAME",
582
+ help="translate, todos, coverage, check, verify, ... (omit to list)",
583
+ )
584
+
585
+ p = add("mcp", cmd_mcp, "run the MCP stdio server (needs the `mcp` extra)")
586
+ p.add_argument(
587
+ "--root", metavar="DIR", default=None, help="paths the tools may read (default: cwd)"
588
+ )
589
+ p.add_argument(
590
+ "--allow-compile",
591
+ action="store_true",
592
+ help="enable the tools that run cargo (check_rust, apply_patch, coverage check+); "
593
+ "cargo executes code, so this is off by default",
594
+ )
595
+ p.add_argument(
596
+ "--allow-build-scripts",
597
+ action="store_true",
598
+ help="with --allow-compile: let deps_from path dependencies have build scripts or be proc-macros",
599
+ )
600
+ p.add_argument(
601
+ "--allow-unsandboxed-compile",
602
+ action="store_true",
603
+ help="with --allow-compile: compile model-submitted Rust even when no OS sandbox (sandbox-exec, "
604
+ "bwrap) exists; without a sandbox such Rust can read host files through the compiler",
605
+ )
606
+ p.add_argument(
607
+ "--allow-unvetted-deps",
608
+ action="store_true",
609
+ help="with --allow-compile: accept deps_from tables with crates off the vetted allow-list, git or "
610
+ "alternate-registry dependencies, [build-dependencies] and [patch] (path dependencies stay "
611
+ "confined to --root)",
612
+ )
613
+
614
+ add("skill", cmd_skill, "print the bundled agent skill (SKILL.md)")
615
+
616
+ p = add("doctor", cmd_doctor, "check python, core, rustfmt, cargo, clippy, config")
617
+ p.add_argument("--config", metavar="TOML", help="also validate this config file")
618
+
619
+ from python2rust.cli import workflow as workflow_cli
620
+
621
+ workflow_cli.register(add, _cargo_opts) # init, plan, next, done, status
622
+ return parser
623
+
624
+
625
+ # --- command handlers ---------------------------------------------------------------------------
626
+
627
+
628
+ def _project(args: argparse.Namespace) -> str | None:
629
+ return None if args.no_patches else args.project
630
+
631
+
632
+ def _need_paths(args: argparse.Namespace) -> None:
633
+ unit = getattr(args, "unit", None)
634
+ if unit and args.paths:
635
+ raise UsageError(
636
+ "--unit translates the whole planned project: give it no PATH (use `python2rust plan` "
637
+ "to change what the project is)"
638
+ )
639
+ if not unit and not args.paths:
640
+ raise UsageError(
641
+ "no input paths given (use a file, a directory, or - for stdin), or --unit"
642
+ )
643
+
644
+
645
+ def _translate_entries(
646
+ args: argparse.Namespace,
647
+ ) -> tuple[list[Any], list[dict[str, Any]], frozenset[str] | None]:
648
+ """(sources, entries, the unit's own files). With `--unit` every module of the plan and every
649
+ test is translated together; without it, exactly the given paths."""
650
+ from python2rust.cli import inputs, ops
651
+
652
+ _need_paths(args)
653
+ if getattr(args, "unit", None):
654
+ from python2rust.workflow import project, state
655
+
656
+ if getattr(args, "out", None) is not None:
657
+ raise UsageError("--unit does not write a crate here: `python2rust port --unit` does")
658
+ root, plan, unit = state.unit_scope_args(args.project, args.unit)
659
+ with project.open_unit(root, plan, unit) as scope:
660
+ entries = ops.run_translate(
661
+ scope.sources, args.config, fmt=not args.no_fmt, vendor_runtime=args.vendor_runtime,
662
+ project=_project(args), builtin_errors=ops.WORKFLOW_BUILTIN_ERRORS,
663
+ ) # fmt: skip
664
+ return scope.sources, entries, scope.own
665
+ sources = inputs.collect(args.paths, stdin_filename=args.stdin_filename)
666
+ return (
667
+ sources,
668
+ ops.run_translate(
669
+ sources,
670
+ args.config,
671
+ fmt=not args.no_fmt,
672
+ vendor_runtime=args.vendor_runtime,
673
+ project=_project(args),
674
+ per_file=args.per_file,
675
+ ),
676
+ None,
677
+ )
678
+
679
+
680
+ def _cargo_kwargs(args: argparse.Namespace) -> dict[str, Any]:
681
+ return {
682
+ "deps_from": args.deps_from,
683
+ "offline": args.offline,
684
+ "timeout": args.timeout,
685
+ "target_dir": args.target_dir,
686
+ }
687
+
688
+
689
+ def _summary_line(doc: dict[str, Any]) -> str:
690
+ s = doc["summary"]
691
+ return (
692
+ f"{s['files']} file(s): {s['files_clean']} clean, {s['files_with_todos']} with open TODOs, "
693
+ f"{s['files_not_clean']} with unchecked behavior, {s['files_failed']} failed; {s['todo_count']} open TODO(s) ({s['todos_patched']} patched), "
694
+ f"{s['error_count']} error(s), {s['warning_count']} warning(s), "
695
+ f"{s['drift_count']} drift note(s)"
696
+ )
697
+
698
+
699
+ def _write_all(args: argparse.Namespace, sources: list[Any], entries: list[dict[str, Any]]) -> None:
700
+ from python2rust.agent import apply, patches
701
+ from python2rust.cli import inputs, ops
702
+
703
+ inputs.check_rel_collisions(sources)
704
+ for src, entry in zip(sources, entries, strict=True):
705
+ ops.write_outputs(entry, src.rel, Path(args.out))
706
+ ops.write_crate_glue(entries, Path(args.out))
707
+ if not args.no_patches:
708
+ patches.update_index(Path(args.project), entries)
709
+ apply.remember_roots(Path(args.project), sources)
710
+
711
+
712
+ def cmd_translate(args: argparse.Namespace) -> Outcome:
713
+ from python2rust.cli import ops
714
+
715
+ if args.stdout and args.json:
716
+ raise UsageError(
717
+ "--stdout and --json both claim stdout; --json already includes the Rust inline"
718
+ )
719
+ sources, entries, _ = _translate_entries(args)
720
+ if len(sources) > 1 and args.out is None and not args.json:
721
+ raise UsageError("several inputs need -o DIR (or --json, which returns the Rust inline)")
722
+ # Rust goes to stdout for one input unless it is being written to -o (then only with --stdout).
723
+ text = None
724
+ if not args.json and len(sources) == 1 and (args.out is None or args.stdout):
725
+ text = entries[0]["rust"]
726
+ if args.out is not None:
727
+ _write_all(args, sources, entries)
728
+ doc, code = ops.translate_doc(entries)
729
+ for e in entries:
730
+ if e["error"]:
731
+ print(f"error: {e['file']}: {e['error']}", file=sys.stderr)
732
+ return Outcome(doc, code, text, _summary_line(doc))
733
+
734
+
735
+ def cmd_todos(args: argparse.Namespace) -> Outcome:
736
+ from python2rust.cli import ops
737
+
738
+ sources, entries, own = _translate_entries(args)
739
+ if args.out is not None:
740
+ _write_all(args, sources, entries)
741
+ if own is not None: # the project was translated whole; the work list is the unit's
742
+ entries = [e for e in entries if e["file"] in own]
743
+ doc, code = ops.todos_doc(entries, only_review=args.only_review, include_patched=args.all)
744
+ lines = [json.dumps(t, ensure_ascii=False) for t in doc["todos"]]
745
+ human = "\n".join(lines) + ("\n" if lines else "")
746
+ if not args.jsonl:
747
+ human = "".join(
748
+ f"{t['file']}:{t['line']} {t['id']} {t['code']} {t['kind']}"
749
+ f"{' [patched]' if t['state'] == 'patched' else ''}"
750
+ f"{' [needs review]' if t['needs_review'] else ''}\n"
751
+ for t in doc["todos"]
752
+ )
753
+ note = f"{doc['count']} TODO(s)" + (
754
+ "" if args.jsonl else " (use --json or --jsonl for the full hand-off objects)"
755
+ )
756
+ return Outcome(doc, code, human, note)
757
+
758
+
759
+ def _modules(
760
+ args: argparse.Namespace,
761
+ ) -> tuple[list[dict[str, Any]], list[Any], frozenset[str] | None]:
762
+ """Entries, Rust modules and (with --unit) the unit's own files for check/verify: .py is
763
+ translated first, .rs is taken as it is. With --unit the modules are what the unit needs to
764
+ compile and test: itself, what it imports and the tests that import it."""
765
+ from python2rust.cli import inputs, ops
766
+ from python2rust.verify import check
767
+
768
+ if getattr(args, "unit", None):
769
+ from python2rust.workflow import project
770
+
771
+ sources, entries, own = _translate_entries(args)
772
+ if own is None:
773
+ raise InternalError("--unit gave no unit scope")
774
+ keep = project.compile_scope(sources, entries, own)
775
+ entries = [entries[i] for i in keep]
776
+ return entries, ops.modules_for([sources[i] for i in keep], entries), own
777
+ _need_paths(args)
778
+ sources = inputs.collect(
779
+ args.paths, suffixes=(".py", ".rs"), stdin_filename=args.stdin_filename
780
+ )
781
+ py = [s for s in sources if not s.display.endswith(".rs")]
782
+ rs = [s for s in sources if s.display.endswith(".rs")]
783
+ entries = (
784
+ ops.run_translate(
785
+ py,
786
+ args.config,
787
+ fmt=not args.no_fmt,
788
+ vendor_runtime=args.vendor_runtime,
789
+ project=_project(args),
790
+ per_file=args.per_file,
791
+ # a built-in error is a Result the equivalence rung can compare by kind
792
+ builtin_errors=ops.WORKFLOW_BUILTIN_ERRORS
793
+ if getattr(args, "level", None) == "equiv"
794
+ else None,
795
+ )
796
+ if py
797
+ else []
798
+ )
799
+ modules = ops.modules_for(py, entries)
800
+ for s in rs:
801
+ if s.text is None:
802
+ raise UsageError(s.read_error or f"cannot read {s.display}")
803
+ sidecar = Path(s.display + ".map")
804
+ smap = None
805
+ if sidecar.is_file():
806
+ try:
807
+ smap = json.loads(sidecar.read_text(encoding="utf-8"))
808
+ except ValueError:
809
+ smap = None
810
+ modules.append(check.CheckModule(s.display, s.text, source_map=smap))
811
+ modules.sort(key=lambda m: m.name)
812
+ return entries, modules, None
813
+
814
+
815
+ def cmd_check(args: argparse.Namespace) -> Outcome:
816
+ from python2rust.cli import ops
817
+ from python2rust.verify import check
818
+
819
+ entries, modules, _ = _modules(args)
820
+ cargo = check.run_check(modules, keep=args.keep, **_cargo_kwargs(args))
821
+ doc, code = ops.check_doc(entries, cargo)
822
+ cats = ", ".join(f"{k}={v}" for k, v in cargo["errors_by_category"].items()) or "none"
823
+ note = f"cargo check: {cargo['status']} ({cargo['errors']} error(s); categories: {cats})"
824
+ if cargo["reason"]:
825
+ note += f"\n{cargo['reason']}"
826
+ lines = [
827
+ f"{e['file'] or '?'}:{e['python_line'] or '?'} {e['category']} {e['code'] or ''} {e['message']}"
828
+ f"{' (approximate line)' if e['mapped_by'] == 'approximate' else ''}"
829
+ for e in cargo["diagnostics"]
830
+ ]
831
+ return Outcome(doc, code, "\n".join(lines) + ("\n" if lines else ""), note)
832
+
833
+
834
+ def cmd_verify(args: argparse.Namespace) -> Outcome:
835
+ from python2rust.cli import ops
836
+ from python2rust.verify import ladder
837
+
838
+ equiv_opts = None
839
+ if args.level == "equiv":
840
+ if not args.run_python:
841
+ raise UsageError(
842
+ "--level equiv EXECUTES your Python module to compare its output with the Rust; "
843
+ "pass --run-python to allow it (nothing is run otherwise)"
844
+ )
845
+ print(RUN_PYTHON_WARNING, file=sys.stderr) # a safety notice: shown even with --quiet
846
+ equiv_opts = _equiv_options(args)
847
+ entries, modules, own = _modules(args)
848
+ if own is not None and equiv_opts is not None:
849
+ # the equivalence rung loads the Python by path: absolute names resolve from any directory
850
+ root = Path(args.project).resolve()
851
+ modules = [replace(m, name=str(root / m.name)) for m in modules]
852
+ result = ladder.verify_units(modules, args.level, equiv=equiv_opts, **_cargo_kwargs(args))
853
+ if own is not None: # compiled together with what it needs; judged: the unit's files
854
+ for fl in result["files"]:
855
+ if equiv_opts is not None:
856
+ fl["file"] = Path(fl["file"]).relative_to(Path(args.project).resolve()).as_posix()
857
+ result["files"] = [fl for fl in result["files"] if fl["file"] in own]
858
+ entries = [e for e in entries if e["file"] in own]
859
+ doc, code = ops.verify_doc(entries, result)
860
+ s = doc["summary"]
861
+ lines = []
862
+ for fl in doc["files"]:
863
+ for fn in fl["functions"]:
864
+ lines.append(
865
+ f"{fl['file']} {fn['function']} highest={fn['highest_rung'] or 'none'} "
866
+ + " ".join(f"{k}={v}" for k, v in fn["rungs"].items())
867
+ + (
868
+ f" equiv: {fn['equiv']} ({fn['equiv_reason']})"
869
+ if fn.get("equiv_reason")
870
+ else ""
871
+ )
872
+ )
873
+ note = (
874
+ f"verify --level {args.level}: {s['functions_total']} function(s), "
875
+ f"check-clean {s['functions_check_clean']}, failing {s['failing_functions']}, "
876
+ f"{s['drift_count']} drift note(s)"
877
+ )
878
+ if args.level == "equiv" and s.get("equivalent_by_rules") is not None:
879
+ note += (
880
+ f"; equivalent by rules {s['equivalent_by_rules']}, "
881
+ f"functionally equivalent (rules + judge) {s['functionally_equivalent']}"
882
+ )
883
+ return Outcome(doc, code, "\n".join(lines) + ("\n" if lines else ""), note)
884
+
885
+
886
+ def cmd_apply(args: argparse.Namespace) -> Outcome:
887
+ from python2rust.agent import apply
888
+
889
+ if args.patch is None:
890
+ patch = None
891
+ elif args.patch == "-":
892
+ patch = sys.stdin.read()
893
+ else:
894
+ try:
895
+ patch = Path(args.patch).read_text(encoding="utf-8")
896
+ except OSError as exc:
897
+ raise UsageError(f"cannot read patch {args.patch}: {exc}") from exc
898
+ equiv_opts = None
899
+ if args.run_python:
900
+ print(RUN_PYTHON_WARNING, file=sys.stderr)
901
+ equiv_opts = _equiv_options(args)
902
+ doc, code = apply.apply_patch(
903
+ args.todo_id, patch, paths=args.source, config_path=args.config, project=args.project,
904
+ author=args.author, equiv=equiv_opts, ack_review=args.ack_review,
905
+ require_equiv=args.require_equiv, no_equiv=args.no_equiv,
906
+ allow_constant_body=args.allow_constant_body, unit=args.unit, **_cargo_kwargs(args),
907
+ ) # fmt: skip
908
+ text = (
909
+ f"{doc['status']}: {args.todo_id}" + (f" ({doc['reason']})" if doc["reason"] else "") + "\n"
910
+ )
911
+ return Outcome(doc, code, text, None)
912
+
913
+
914
+ def cmd_contract(args: argparse.Namespace) -> Outcome:
915
+ from python2rust.report import contract
916
+
917
+ doc, code = contract.contract_doc(
918
+ args.python, args.rust, command=args.rust_openapi_cmd, bin_name=args.bin,
919
+ timeout=args.timeout, strict_422=args.strict_422, ignore_operation_id=args.ignore_operation_id,
920
+ ) # fmt: skip
921
+ s = doc["summary"]
922
+ note = (
923
+ f"contract: {s['findings']} finding(s) ({s['errors']} error(s), {s['warnings']} warning(s))"
924
+ )
925
+ return Outcome(doc, code, doc["markdown"], note)
926
+
927
+
928
+ def cmd_port(args: argparse.Namespace) -> Outcome:
929
+ from python2rust.agent import agents, loop, port
930
+
931
+ backend = agents.make_backend(
932
+ args.agent, command=args.agent_cmd, model=args.model, base_url=args.base_url,
933
+ openai_api=args.openai_api, timeout=args.timeout, verbose=args.verbose,
934
+ ) # fmt: skip
935
+ strong = None
936
+ if backend is not None and (args.strong_agent_cmd or args.strong_model):
937
+ strong = agents.make_backend(
938
+ args.agent, command=args.strong_agent_cmd or args.agent_cmd, model=args.strong_model or args.model,
939
+ base_url=args.base_url, openai_api=args.openai_api, timeout=args.timeout, verbose=args.verbose,
940
+ ) # fmt: skip
941
+ if backend is not None: # always shown, even with --quiet: this is what leaves the machine
942
+ print(
943
+ f"python2rust: --agent {args.agent}: for each failing function, its Python source, the generated "
944
+ "Rust, the compiler errors and signatures of the items it uses are SENT to the agent "
945
+ "(nothing else from the project). Use --agent none for a dry run that prints the tasks instead.",
946
+ file=sys.stderr,
947
+ )
948
+
949
+ def run(**scope: Any) -> tuple[dict[str, Any], int]:
950
+ return port.port_project(
951
+ args.paths, args.out, config_path=args.config, project=args.project, backend=backend,
952
+ strong_backend=strong, budget=loop.Budget(args.budget_iters, args.budget_tokens, args.budget_seconds),
953
+ escalate_after=args.escalate_after, patience=args.patience, workers=args.workers,
954
+ offline=args.offline, timeout=args.timeout, target_dir=args.target_dir,
955
+ stdin_filename=args.stdin_filename, fmt=not args.no_fmt, vendor_runtime=args.vendor_runtime,
956
+ **scope,
957
+ ) # fmt: skip
958
+
959
+ _need_paths(args)
960
+ if args.unit:
961
+ from python2rust.workflow import project, state
962
+
963
+ root, plan, unit = state.unit_scope_args(args.project, args.unit)
964
+ with project.open_unit(root, plan, unit) as scope:
965
+ doc, code = run(sources=scope.sources, only=scope.own)
966
+ else:
967
+ doc, code = run()
968
+ t = doc["totals"]
969
+ lines = []
970
+ for r in doc["rounds"]:
971
+ lines.append(
972
+ f"round {r['round']}: errors {r['errors_before']} -> {r['errors_after']}, "
973
+ f"failing {r['failing_before']} -> {r['failing_after']}, fixed {r['fixed'] or '{}'}, {r['tokens']} tokens"
974
+ )
975
+ for task in doc["tasks"]:
976
+ lines.append(json.dumps(task, ensure_ascii=False))
977
+ note = (
978
+ f"port {doc['status']}: {t['functions_failing']} failing function(s), {t['compile_errors']} compile error(s), "
979
+ f"{t['todos_left']} todo(s) left, {t['cargo_checks']} cargo check(s), {t['tokens']} tokens"
980
+ )
981
+ if doc["dry_run"] and doc["tasks"]:
982
+ note += f"\n{len(doc['tasks'])} task(s) listed on stdout WOULD be sent with --agent; nothing was sent"
983
+ return Outcome(doc, code, "\n".join(lines) + ("\n" if lines else ""), note)
984
+
985
+
986
+ def cmd_explain(args: argparse.Namespace) -> Outcome:
987
+ from python2rust.report import explain
988
+
989
+ doc = explain.explain_doc(args.code)
990
+ return Outcome(doc, EXIT_OK, explain.explain_text(doc))
991
+
992
+
993
+ def cmd_coverage(args: argparse.Namespace) -> Outcome:
994
+ from python2rust.cli import ops
995
+ from python2rust.verify import ladder
996
+
997
+ sources, entries, _ = _translate_entries(args)
998
+ result = None
999
+ if args.level != "none":
1000
+ modules = ops.modules_for(sources, entries)
1001
+ result = ladder.verify_units(modules, args.level, **_cargo_kwargs(args))
1002
+ doc, code = ops.coverage_doc(entries, result)
1003
+ t = doc["totals"]
1004
+ clean = (
1005
+ "not verified"
1006
+ if t["functions_check_clean"] is None
1007
+ else f"{t['functions_check_clean']}/{t['functions_total']} check-clean"
1008
+ )
1009
+ return Outcome(doc, code, doc["markdown"], f"{clean}, {t['todo_count']} open TODO(s)")
1010
+
1011
+
1012
+ def cmd_eval(args: argparse.Namespace) -> Outcome:
1013
+ from python2rust.report import corpus
1014
+
1015
+ doc, code = corpus.eval_corpus(
1016
+ args.corpus,
1017
+ level=args.level,
1018
+ config_path=args.config,
1019
+ baseline=args.baseline,
1020
+ run_py2many_baseline=args.run_py2many,
1021
+ py2many_cmd=args.py2many_cmd,
1022
+ **_cargo_kwargs(args),
1023
+ )
1024
+ m = doc["metrics"]
1025
+ note = f"{m['functions_total']} function(s), check-clean {m['functions_check_clean_pct']}%, {m['todos_per_100_lines']} TODOs/100 lines"
1026
+ if doc["expectations_failed"]:
1027
+ note += "\nexpectations failed: " + "; ".join(doc["expectations_failed"])
1028
+ return Outcome(doc, code, doc["markdown"], note)
1029
+
1030
+
1031
+ def cmd_constructs(args: argparse.Namespace) -> Outcome:
1032
+ from python2rust.report import constructs
1033
+
1034
+ doc = constructs.constructs_doc()
1035
+ return Outcome(doc, EXIT_OK, constructs.constructs_text(doc))
1036
+
1037
+
1038
+ def cmd_schema(args: argparse.Namespace) -> Outcome:
1039
+ from python2rust.cli import ops
1040
+ from python2rust.report.schemas import SCHEMAS
1041
+
1042
+ if args.name is None:
1043
+ doc = ops.envelope("schema", schemas=sorted(SCHEMAS), exit_codes=EXIT_CODES)
1044
+ return Outcome(doc, EXIT_OK, "\n".join(doc["schemas"]) + "\n")
1045
+ if args.name not in SCHEMAS:
1046
+ raise UsageError(f"unknown schema {args.name!r}; known: {', '.join(sorted(SCHEMAS))}")
1047
+ return Outcome(SCHEMAS[args.name], EXIT_OK, json.dumps(SCHEMAS[args.name], indent=2) + "\n")
1048
+
1049
+
1050
+ def skill_text() -> str:
1051
+ from importlib.resources import files
1052
+
1053
+ return files("python2rust").joinpath("skill/SKILL.md").read_text(encoding="utf-8")
1054
+
1055
+
1056
+ def cmd_skill(args: argparse.Namespace) -> Outcome:
1057
+ from python2rust.cli import ops
1058
+
1059
+ text = skill_text()
1060
+ return Outcome(ops.envelope("skill", name="python2rust", text=text), EXIT_OK, text)
1061
+
1062
+
1063
+ def cmd_doctor(args: argparse.Namespace) -> Outcome:
1064
+ from python2rust.cli import doctor
1065
+
1066
+ doc, code = doctor.doctor_doc(args.config)
1067
+ text = "".join(f"{c['status']:<5}{c['name']:<9}{c['detail']}\n" for c in doc["checks"])
1068
+ return Outcome(doc, code, text)
1069
+
1070
+
1071
+ def cmd_mcp(args: argparse.Namespace) -> Outcome:
1072
+ import importlib.util
1073
+
1074
+ from python2rust._core import get_core
1075
+
1076
+ get_core() # no core: refuse to start (exit 3) instead of failing on every tool call
1077
+ if importlib.util.find_spec("mcp") is None:
1078
+ raise InternalError(
1079
+ "the MCP SDK is not installed; run: pip install 'python2rust[mcp]'",
1080
+ kind="missing_dependency",
1081
+ )
1082
+ from python2rust.server.mcp_server import serve
1083
+
1084
+ serve(
1085
+ args.root,
1086
+ allow_compile=args.allow_compile,
1087
+ allow_build_scripts=args.allow_build_scripts,
1088
+ allow_unsandboxed_compile=args.allow_unsandboxed_compile,
1089
+ allow_unvetted_deps=args.allow_unvetted_deps,
1090
+ )
1091
+ return Outcome({}, EXIT_OK)
1092
+
1093
+
1094
+ # --- entry point --------------------------------------------------------------------------------
1095
+
1096
+
1097
+ def _emit(out: Outcome, args: argparse.Namespace) -> None:
1098
+ if args.json:
1099
+ sys.stdout.write(json.dumps(out.doc, indent=2, ensure_ascii=False) + "\n")
1100
+ elif out.text:
1101
+ sys.stdout.write(out.text)
1102
+ if out.note and not args.quiet:
1103
+ print(out.note, file=sys.stderr)
1104
+
1105
+
1106
+ def _fail(kind: str, message: str, code: int, as_json: bool, quiet: bool) -> int:
1107
+ from python2rust.cli.ops import error_doc
1108
+
1109
+ if as_json:
1110
+ sys.stdout.write(json.dumps(error_doc(kind, message), indent=2) + "\n")
1111
+ if not quiet or not as_json:
1112
+ print(f"python2rust: error: {message}", file=sys.stderr)
1113
+ return code
1114
+
1115
+
1116
+ def main(argv: list[str] | None = None) -> int:
1117
+ argv = list(sys.argv[1:] if argv is None else argv)
1118
+ for stream in (sys.stdout, sys.stderr):
1119
+ if reconfigure := getattr(stream, "reconfigure", None):
1120
+ reconfigure(encoding="utf-8")
1121
+ as_json, quiet = "--json" in argv, "--quiet" in argv or "-q" in argv
1122
+ try:
1123
+ parser = build_parser()
1124
+ args = parser.parse_args(argv)
1125
+ if not getattr(args, "func", None):
1126
+ parser.print_help(sys.stderr)
1127
+ raise UsageError("no command given")
1128
+ as_json, quiet = args.json, args.quiet
1129
+ if getattr(args, "allow_unvetted_deps", False):
1130
+ from python2rust.verify import check
1131
+
1132
+ check.ALLOW_UNVETTED_DEFAULT = (
1133
+ True # every --deps-from read in this run is accepted as is
1134
+ )
1135
+ if args.command != "mcp" and hasattr(args, "allow_unsandboxed_compile"):
1136
+ from python2rust.verify import sandbox
1137
+
1138
+ sandbox.configure_cli(args.allow_unsandboxed_compile) # every cargo run is confined
1139
+ out = args.func(args)
1140
+ if args.command != "mcp":
1141
+ _emit(out, args)
1142
+ return out.code
1143
+ except UsageError as exc:
1144
+ return _fail("usage", str(exc), EXIT_USAGE, as_json, quiet)
1145
+ except RustSideError as exc:
1146
+ return _fail("rust_openapi", str(exc), EXIT_COMPILE, as_json, quiet)
1147
+ except InternalError as exc:
1148
+ return _fail(exc.kind, str(exc), EXIT_INTERNAL, as_json, quiet)
1149
+ except BrokenPipeError:
1150
+ # the reader went away before the output was complete: that is a failure, not success
1151
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
1152
+ return EXIT_FINDINGS
1153
+ except KeyboardInterrupt:
1154
+ return 130
1155
+ except Exception as exc:
1156
+ if not quiet:
1157
+ traceback.print_exc()
1158
+ return _fail("internal", f"{type(exc).__name__}: {exc}", EXIT_INTERNAL, as_json, True)
1159
+
1160
+
1161
+ if __name__ == "__main__":
1162
+ sys.exit(main())