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
File without changes
@@ -0,0 +1,289 @@
1
+ """MCP stdio server: the CLI's operations as tools for an LLM client.
2
+
3
+ Every tool returns the same JSON document as the matching CLI command (`--json`), or the shared
4
+ error document `{"schema_version": 1, "ok": false, "error": {...}}` instead of raising.
5
+ Works with both the `mcp` 1.x (`FastMCP`) and 2.x (`MCPServer`) SDKs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import anyio.to_thread
15
+
16
+ from python2rust.agent import apply
17
+ from python2rust.agent.patches import host_access_violations
18
+ from python2rust.cli import inputs, ops
19
+ from python2rust.errors import InternalError, UsageError
20
+ from python2rust.report import explain
21
+ from python2rust.verify import check, ladder, sandbox
22
+
23
+ COMPILE_OFF = (
24
+ "compiling is disabled on this server: cargo executes code (build scripts, proc-macros) and "
25
+ "this tool would compile Rust supplied through MCP. Start the server with --allow-compile "
26
+ "to enable check_rust, apply_patch and coverage levels check/clippy/test"
27
+ )
28
+
29
+ INSTRUCTIONS = (
30
+ "python2rust translates typed Python to Rust. To port a project start with init_questions: ask "
31
+ "the human ALL questions in one message (never answer an ask_human question yourself), then "
32
+ "init_apply, plan, and loop next_unit -> port -> mark_done; call status whenever unsure. "
33
+ "Per unit the loop is: translate_source -> read `todos` "
34
+ "(each has an `instruction`) -> write the Rust for each todo!() and submit it with apply_patch "
35
+ "(never edit generated files) -> check_rust -> repeat. "
36
+ "Anything with needs_review=true must be reviewed by a human or a stronger model. "
37
+ "Never claim success while todos or compile errors remain."
38
+ )
39
+
40
+
41
+ def _server_class() -> Any:
42
+ try:
43
+ from mcp.server.mcpserver import MCPServer # mcp >= 2
44
+
45
+ return MCPServer
46
+ except ImportError:
47
+ import importlib
48
+
49
+ fastmcp: Any = importlib.import_module("mcp.server.fastmcp") # mcp 1.x
50
+ return fastmcp.FastMCP
51
+
52
+
53
+ def _guard(root: Path, raw: str) -> str:
54
+ """Resolve a path the model supplied and refuse anything outside the allowed root."""
55
+ p = Path(raw)
56
+ p = (p if p.is_absolute() else root / p).resolve()
57
+ if not p.is_relative_to(root):
58
+ raise UsageError(f"path {raw!r} is outside the allowed root {root}")
59
+ return str(p)
60
+
61
+
62
+ async def _run(fn: Callable[[], dict[str, Any]]) -> dict[str, Any]:
63
+ """Run blocking work off the event loop and turn failures into the shared error document."""
64
+ try:
65
+ return await anyio.to_thread.run_sync(fn)
66
+ except UsageError as exc:
67
+ return ops.error_doc("usage", str(exc))
68
+ except InternalError as exc:
69
+ return ops.error_doc("internal", str(exc))
70
+ except Exception as exc:
71
+ return ops.error_doc("internal", f"{type(exc).__name__}: {exc}")
72
+
73
+
74
+ def build_server(
75
+ root: str | None = None,
76
+ *,
77
+ allow_compile: bool = False,
78
+ allow_build_scripts: bool = False,
79
+ allow_unsandboxed_compile: bool = False,
80
+ allow_unvetted_deps: bool = False,
81
+ ) -> Any:
82
+ """Create the server. `root` limits which local paths (config files, coverage paths) may be read.
83
+
84
+ Compiling is OFF unless `allow_compile`: cargo runs code on this machine (build scripts,
85
+ proc-macros), and `check_rust` compiles Rust that the model supplies. With it on, submitted Rust
86
+ is first scanned for host access (include!, env!, #[path], macros, ...) and every cargo run is
87
+ sandboxed (no network, reads confined; verify/sandbox.py). Without a sandbox tool on the machine
88
+ compiling is refused unless `allow_unsandboxed_compile`. `deps_from` path dependencies are
89
+ confined to `root` and may not have build scripts or be proc-macros unless `allow_build_scripts`;
90
+ registry crates must be on the vetted allow-list ([deps] allow in `root`/python2rust.toml extends
91
+ it), and git/alternate-registry dependencies, [build-dependencies] and [patch] are refused, unless
92
+ `allow_unvetted_deps`.
93
+ """
94
+ base = Path(root or ".").resolve()
95
+ server = _server_class()("python2rust", instructions=INSTRUCTIONS)
96
+
97
+ def need_compile() -> None:
98
+ if not allow_compile:
99
+ raise UsageError(COMPILE_OFF)
100
+ if sandbox.find() is None and not allow_unsandboxed_compile:
101
+ raise UsageError(sandbox.MISSING)
102
+
103
+ async def run(fn: Callable[[], dict[str, Any]]) -> dict[str, Any]:
104
+ """`_run`, with every cargo run inside it sandboxed (a missing tool refuses, see need_compile)."""
105
+
106
+ def confined() -> dict[str, Any]:
107
+ if sandbox.find() is None and allow_unsandboxed_compile:
108
+ return fn()
109
+ with sandbox.confine():
110
+ return fn()
111
+
112
+ return await _run(confined)
113
+
114
+ def one_file(source: str, path: str, config_path: str | None) -> list[dict[str, Any]]:
115
+ cfg = _guard(base, config_path) if config_path else None
116
+ src = inputs.Source(path, Path(path).name, source)
117
+ return ops.run_translate([src], cfg)
118
+
119
+ @server.tool()
120
+ async def translate_source(
121
+ source: str, path: str = "<string>.py", config_path: str | None = None
122
+ ) -> dict[str, Any]:
123
+ """Translate a string of typed Python 3.14 source to Rust.
124
+
125
+ Use this first, on one module at a time. Returns the same JSON as
126
+ `python2rust translate - --json`: `files[0].rust` is the Rust source, `files[0].todos`
127
+ lists every place the translator gave up (each is a `todo!()` in the Rust) and
128
+ `files[0].diagnostics` the machine-readable reasons (codes PY2RSnnn; use explain_diagnostic).
129
+ Act on it: for every todo, write the Rust yourself following its `instruction`, then
130
+ verify with check_rust. `status` is clean only when there are no todos and no errors.
131
+ `path` is only a label for diagnostics. `config_path` is an optional TOML config file
132
+ (import_map, library_map, type_map, review_patterns) below the server root.
133
+ """
134
+ return await run(lambda: ops.translate_doc(one_file(source, path, config_path))[0])
135
+
136
+ @server.tool()
137
+ async def list_todos(
138
+ source: str,
139
+ path: str = "<string>.py",
140
+ config_path: str | None = None,
141
+ only_review: bool = False,
142
+ ) -> dict[str, Any]:
143
+ """List the TODOs for a Python source as agent hand-off tasks, without the full Rust.
144
+
145
+ Same JSON as `python2rust todos - --json`. Each todo has `id`, `python_snippet`,
146
+ `rust_context`, `rust_line`, `needs_review` and an `instruction` that says exactly what to do.
147
+ Set only_review=true to see just the ones a human or stronger model must look at.
148
+ Use translate_source instead when you also need the Rust text.
149
+ """
150
+ return await run(
151
+ lambda: ops.todos_doc(one_file(source, path, config_path), only_review=only_review)[0]
152
+ )
153
+
154
+ @server.tool()
155
+ async def explain_diagnostic(code: str) -> dict[str, Any]:
156
+ """Explain a python2rust diagnostic code such as PY2RS001.
157
+
158
+ Returns the meaning, why it happens, the typical fix and a Python/Rust before-and-after
159
+ example (same JSON as `python2rust explain CODE --json`). Call it when a diagnostic or todo
160
+ carries a code you do not recognise, before deciding how to fix the Rust.
161
+ """
162
+ return await run(lambda: explain.explain_doc(code))
163
+
164
+ @server.tool()
165
+ async def check_rust(
166
+ rust_source: str,
167
+ python_source: str | None = None,
168
+ deps_from: str | None = None,
169
+ offline: bool = False,
170
+ ) -> dict[str, Any]:
171
+ """Compile-check Rust source with `cargo check` in a throwaway crate.
172
+
173
+ Use after you edited generated Rust. Returns the `check` JSON: `cargo.status` is ok,
174
+ errors, skipped (cargo missing) or failed (cargo itself failed, see `reason`);
175
+ `cargo.diagnostics` has each rustc error with its code, `category` (type-mismatch,
176
+ use-after-move, unresolved-import, ...) and the Rust line. Pass the original
177
+ `python_source` to also get `python_line` for errors inside a translated function.
178
+ `deps_from` is a Cargo.toml (below the server root) whose [dependencies] the crate should
179
+ use; without it only std is available, so crate imports show up as unresolved-import.
180
+ Done means cargo.status == "ok" and no `todo!()` left that you did not intend.
181
+ Only available when the server was started with --allow-compile. Rejects Rust that reads
182
+ host files or runs host code (include!, env!, #[path], macro_rules, std::fs/process/net/env,
183
+ inner attributes, ...) and compiles inside an OS sandbox (no network, reads confined).
184
+ """
185
+
186
+ def work() -> dict[str, Any]:
187
+ need_compile()
188
+ if found := host_access_violations(rust_source):
189
+ v = found[0]
190
+ raise UsageError(
191
+ f"rejected before compiling: {v['token']} at line {v['line']}: {v['message']}"
192
+ )
193
+ deps = _guard(base, deps_from) if deps_from else None
194
+ cargo = check.run_check(
195
+ [check.CheckModule("<rust>", rust_source, [], python_source)],
196
+ deps_from=deps,
197
+ offline=offline,
198
+ deps_root=base,
199
+ allow_build_scripts=allow_build_scripts,
200
+ allow_unvetted_deps=allow_unvetted_deps,
201
+ )
202
+ return ops.check_doc([], cargo)[0]
203
+
204
+ return await run(work)
205
+
206
+ @server.tool()
207
+ async def coverage(
208
+ paths: list[str], config_path: str | None = None, level: str | None = None
209
+ ) -> dict[str, Any]:
210
+ """Measure how much of a Python corpus translates cleanly.
211
+
212
+ `paths` are files or directories below the server root. Returns the `coverage` JSON:
213
+ totals, TODOs by construct and a `markdown` table. The headline is
214
+ `totals.functions_check_clean`: functions with Rust output, no todo!() left, that pass
215
+ `cargo check` (null when cargo is missing: nothing was compiled, so no claim is made).
216
+ `level` is the ladder rung to run (parse, fmt, check, clippy, test) or `none` to skip
217
+ compiling; the default is `check` when the server allows compiling (--allow-compile) and
218
+ `none` otherwise. It translates everything but writes nothing.
219
+ """
220
+
221
+ def work() -> dict[str, Any]:
222
+ cfg = _guard(base, config_path) if config_path else None
223
+ srcs = inputs.collect([_guard(base, p) for p in paths])
224
+ entries = ops.run_translate(srcs, cfg)
225
+ chosen = level or ("check" if allow_compile else "none")
226
+ if chosen != "none" and chosen not in ladder.LEVELS:
227
+ raise UsageError(f"level must be none or one of {', '.join(ladder.LEVELS)}")
228
+ if chosen not in ("none", "parse", "fmt"):
229
+ need_compile() # check, clippy and test run cargo
230
+ result = None
231
+ if chosen != "none":
232
+ result = ladder.verify_units(ops.modules_for(srcs, entries), chosen)
233
+ return ops.coverage_doc(entries, result)[0]
234
+
235
+ return await run(work)
236
+
237
+ @server.tool()
238
+ async def apply_patch(
239
+ todo_id: str,
240
+ patch: str,
241
+ source_path: str,
242
+ config_path: str | None = None,
243
+ author: str = "mcp-agent",
244
+ ) -> dict[str, Any]:
245
+ """Store your fix for one TODO. This is how a fix is submitted; never edit generated Rust.
246
+
247
+ `patch` is only the Rust that replaces the todo!() (an expression, or statements ending in
248
+ the value); `todo_id` comes from list_todos; `source_path` is the Python file holding the
249
+ TODO, below the server root. The fix is saved under `.python2rust/patches/` in the server
250
+ root and re-applied by every later translate. It is rejected (status "rejected") if it
251
+ contains todo!, unimplemented!, unwrap(, expect(, panic!, #[allow, a Default::default()
252
+ stand-in or unsafe, and accepted only if the touched function passes `cargo check`
253
+ ("failed" lists the compile errors, "unverified" means cargo is missing and the fix is NOT
254
+ accepted). Returns the `apply` JSON; act on `status` and `reason`.
255
+ """
256
+
257
+ def work() -> dict[str, Any]:
258
+ need_compile() # a fix is only accepted after cargo check
259
+ cfg = _guard(base, config_path) if config_path else None
260
+ return apply.apply_patch(
261
+ todo_id, patch, paths=[_guard(base, source_path)], config_path=cfg,
262
+ project=str(base), author=author,
263
+ )[0] # fmt: skip
264
+
265
+ return await run(work)
266
+
267
+ from python2rust.server import mcp_workflow
268
+
269
+ mcp_workflow.register(
270
+ server, base, run, allow_compile, _guard
271
+ ) # init, plan, next, done, status
272
+ return server
273
+
274
+
275
+ def serve(
276
+ root: str | None = None,
277
+ *,
278
+ allow_compile: bool = False,
279
+ allow_build_scripts: bool = False,
280
+ allow_unsandboxed_compile: bool = False,
281
+ allow_unvetted_deps: bool = False,
282
+ ) -> None:
283
+ build_server(
284
+ root,
285
+ allow_compile=allow_compile,
286
+ allow_build_scripts=allow_build_scripts,
287
+ allow_unsandboxed_compile=allow_unsandboxed_compile,
288
+ allow_unvetted_deps=allow_unvetted_deps,
289
+ ).run("stdio")
@@ -0,0 +1,100 @@
1
+ """MCP tools for the agent-first workflow. Same documents as the CLI; files stay inside the server root."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from python2rust.errors import UsageError
10
+ from python2rust.workflow import interview
11
+ from python2rust.workflow import state as workflow
12
+
13
+ Run = Callable[[Callable[[], dict[str, Any]]], Any]
14
+
15
+
16
+ def register(
17
+ server: Any, base: Path, run: Run, allow_compile: bool, guard: Callable[[Path, str], str]
18
+ ) -> None:
19
+ root = str(base)
20
+
21
+ @server.tool()
22
+ async def init_questions() -> dict[str, Any]:
23
+ """Start here: the interview a human must answer before a port begins (same JSON as `python2rust init --questions`).
24
+
25
+ Returns every question with id, why_it_matters, options with consequences, a default and
26
+ `ask_human`. Ask the human ALL questions in ONE message, showing options, consequences and
27
+ defaults. Never answer an ask_human question yourself. Then call init_apply with the answers.
28
+ """
29
+ return await run(interview.questions_doc)
30
+
31
+ @server.tool()
32
+ async def init_apply(
33
+ answers: dict[str, Any] | None = None, defaults: bool = False, force: bool = False
34
+ ) -> dict[str, Any]:
35
+ """Validate the human's answers and write python2rust.toml and .python2rust/state.json in the server root.
36
+
37
+ `answers` maps question id to value (see init_questions). Unknown ids, bad values or missing
38
+ ask_human answers are errors naming the id and the allowed values. Set defaults=true ONLY when the
39
+ human told you to take the defaults. Refuses to overwrite an existing setup unless force=true.
40
+ `run_python` (the user's consent to execute their code) cannot be answered here: leave it out, it
41
+ defaults to `no`; passing it is an error. The user configures model backends, commands,
42
+ model names, and functional-judge mode through the CLI. Next call: plan.
43
+ """
44
+ return await run(
45
+ lambda: workflow.init_apply(
46
+ root, answers or {}, defaults=defaults, force=force, human=False
47
+ )[0]
48
+ )
49
+
50
+ @server.tool()
51
+ async def plan(paths: list[str] | None = None) -> dict[str, Any]:
52
+ """Plan the port: units in dependency order with size, tests, risks and difficulty (same JSON as `python2rust plan`).
53
+
54
+ Static analysis only: the user's Python is never imported or run. `paths` are files or directories
55
+ below the server root (default: the scope answer). Import cycles are grouped into one unit. Writes
56
+ .python2rust/plan.json. The coverage numbers say so when they come from the test stub. Next: next_unit.
57
+ """
58
+ return await run(
59
+ lambda: workflow.plan_project(root, [guard(base, p) for p in paths or []])[0]
60
+ )
61
+
62
+ @server.tool()
63
+ async def next_unit() -> dict[str, Any]:
64
+ """The next unit to port as a self-contained brief: files, tests, mapping decisions, commands, acceptance.
65
+
66
+ Same JSON as `python2rust next`: `markdown` renders it, `commands` are the exact CLI calls for this
67
+ unit, `acceptance` says what must pass. It also records the unit as current and refreshes
68
+ PORTING.md in the server root. Port the unit, then call mark_done.
69
+ """
70
+ return await run(lambda: workflow.next_unit(root)[0])
71
+
72
+ @server.tool()
73
+ async def mark_done(unit: str) -> dict[str, Any]:
74
+ """Record a unit as done, only if the rungs of the chosen output tier pass (same JSON as `python2rust done`).
75
+
76
+ Re-translates the unit with the stored patches, runs cargo for check/clippy/test as the tier needs
77
+ and lists exactly what is `missing` otherwise. Never runs the user's Python: equivalence is reported
78
+ under `not_verified` with the exact CLI command (`done UNIT --run-python`, for the human to run or allow).
79
+ The recorded `tier` says which rungs really ran (`compiled`, `tested`, `verified`, `production`). Never claim a unit is done while
80
+ `missing` is not empty. Items for human review stay queued. Needs --allow-compile (cargo runs code).
81
+ """
82
+
83
+ def work() -> dict[str, Any]:
84
+ if not allow_compile:
85
+ raise UsageError(
86
+ "mark_done runs cargo, which executes code: start the server with --allow-compile"
87
+ )
88
+ return workflow.done_unit(root, unit, deps_from=None)[0] # never run_python
89
+
90
+ return await run(work)
91
+
92
+ @server.tool()
93
+ async def status() -> dict[str, Any]:
94
+ """Where the port stands: phase, current unit, blockers, the exact next command, open questions, review queue.
95
+
96
+ Same JSON as `python2rust status`. Call it whenever you are unsure what to do next. `next_command` is
97
+ the command to run (null when complete); `review_queue` lists what a human must review; a non-empty
98
+ `open_questions` means a human decision was only defaulted.
99
+ """
100
+ return await run(lambda: workflow.status_project(root)[0])
@@ -0,0 +1,214 @@
1
+ ---
2
+ name: python2rust
3
+ description: Translate typed Python to Rust with the python2rust CLI and finish the parts it could not translate. Use when asked to port, migrate or rewrite Python modules (typed, Python 3.14 syntax) to Rust, to measure how much of a Python codebase can be translated mechanically, or to fix the todo!() placeholders in Rust that python2rust generated.
4
+ ---
5
+
6
+ # python2rust
7
+
8
+ python2rust turns **typed Python** into Rust mechanically and **never silently**. Whatever it cannot
9
+ translate becomes a loud `todo!()` plus a machine-readable diagnostic. Your job is to close those
10
+ TODOs, verify with the compiler, and escalate what needs review. It is alpha software: expect TODOs.
11
+
12
+ Run it without installing: `uvx python2rust ...` (or `python2rust ...` / `py2rust ...` once installed).
13
+ Every command takes `--json`: stdout is then exactly one JSON document, human text goes to stderr.
14
+ Nothing is interactive. `-` reads stdin.
15
+
16
+ ## Start here: port a whole project
17
+
18
+ Run this flow from the project root; every command takes `--json`, nothing is interactive, and
19
+ `python2rust status --json` always names the phase and the exact next command (run it whenever unsure).
20
+
21
+ 1. `python2rust init --questions --json`: the interview. Each question has `id`, `question`,
22
+ `why_it_matters`, `kind` (`choice | multi | list | int | text`), `options` (`value`, `label`,
23
+ `consequence`), `default`, `ask_human` and `only_if`.
24
+ 2. **Ask the human ALL questions in ONE message**, showing each question, its options with their
25
+ consequences, and the default. Skip a question whose `only_if` does not hold. Questions with
26
+ `ask_human: true` need the human's decision; for the rest show the default and let them override it.
27
+ 3. `python2rust init --answers answers.json` (`{"id": value}`; lists for `multi`/`list`) or repeated
28
+ `--answer id=value`. Unknown ids and bad values are exit 2 naming the allowed values. Writes
29
+ `python2rust.toml` and `.python2rust/state.json`; re-running needs `--force`.
30
+ 4. `python2rust plan --json`: units in dependency order (import cycles are one unit, leaves first, easy
31
+ first) with size, async and exception facts, tests found, a mechanical coverage estimate, risk flags and
32
+ a difficulty score. Static analysis only: your code is never run. Writes `.python2rust/plan.json`.
33
+ 5. Loop until `status` says `complete`:
34
+ - `python2rust next --json`: one unit as a brief (`unit`, `decisions`, `mapping_notes`,
35
+ `open_questions`, `commands`, `acceptance`, `markdown`); it also refreshes `PORTING.md`.
36
+ - Port the unit with the commands in the brief (`port`, `todos`, `apply`, `verify`). They work on the
37
+ whole planned project and narrow to the unit with `--unit UNIT`: imports between units resolve and the
38
+ crate keeps every unit.
39
+ - `python2rust done UNIT --json`: records the unit only if the rungs of the chosen output tier pass
40
+ (`draft` compiles; `verified` adds equivalence, which needs `done UNIT --run-python` once the human
41
+ answered `run_python: yes`; `production` adds clippy and tests). The recorded `tier` is what ran
42
+ (`compiled`, `tested`, `verified`, `production`). Exit 1 lists what is `missing`; `not_verified` says
43
+ what could not be checked, with the command to run.
44
+ 6. Report units done, what `done` could not verify, and `review_queue` from `status`.
45
+
46
+ `status --json`: `{"phase": "init needed|plan needed|porting|verifying|complete", "current_unit": ...,
47
+ "blockers": [...], "next_command": "...", "open_questions": [...], "review_queue": {"todos": [...],
48
+ "units": [...]}, "progress": {...}}`.
49
+
50
+ Rules: never answer an `ask_human` question for the human; use `--defaults` only when they told you to;
51
+ never pass `--force` or `--reviewed` yourself; never use `--run-python` unless they answered
52
+ `run_python: yes` (it executes their code); never claim a unit is done while `done` exits 1.
53
+
54
+ ## Exit codes (all commands)
55
+
56
+ | code | meaning |
57
+ |---|---|
58
+ | 0 | ok: no TODOs, no error diagnostics, (check: it compiles) |
59
+ | 1 | ran fine, but TODOs / error diagnostics remain, or the result could not be verified (no cargo) |
60
+ | 2 | usage error: bad flag, missing path, invalid config (`--json` gives an error document) |
61
+ | 3 | internal error, missing core or missing optional dependency (a bug, or `mcp` extra missing) |
62
+ | 4 | the Rust does not compile or verify: compile errors, a failing clippy/test/equiv rung, a fix rejected by `apply` |
63
+
64
+ Error document (exit 2 and 3, with `--json`): `{"schema_version": 1, "ok": false, "error": {"kind": "usage|internal|missing_dependency|missing_core|rust_openapi", "message": "..."}}`.
65
+
66
+ ## The loop
67
+
68
+ 1. **Translate**: `python2rust translate src/ -o rust_out/ --json [--config project.toml]`
69
+ Writes `<name>.rs`, `<name>.todo.json` and `<name>.diagnostics.json` per Python file.
70
+ 2. **Read the TODOs**: `python2rust todos src/ -o rust_out/ --json` (the hand-off contract below).
71
+ 3. **Fix one TODO at a time**: write the replacement for the `todo!()` using `python_snippet` and
72
+ `rust_context` (keep signatures) and submit it: `python2rust apply TODO_ID --patch fix.rs --json`
73
+ (`-` for stdin). The fix is stored in `.python2rust/patches/` and re-applied by every translate; never edit the
74
+ generated file. `apply` rejects `todo!`, `unimplemented!`, `unreachable!`, `unwrap`/`expect`, `panic!`,
75
+ `loop {}`, `#[allow]`, `Default::default()` stand-ins, `process::exit`, `unsafe`, `transmute`, `include*!`,
76
+ `env!` and build-script tricks (exit 1, JSON reason), and accepts a fix only if the function compiles
77
+ every translated `#[test]` that uses the module passes (tests that reach another open TODO are listed as
78
+ `skipped-todo`; a TODO inside a test is refused; `unverified`, not accepted, when cargo is missing or the tests
79
+ cannot run; exit 4 on compile errors or a failing test) and, for a pure function with a JSON-able signature,
80
+ the output equals the Python's: that needs `--run-python` (it executes the Python in a child process with best-effort limits, not an OS sandbox; only with the
81
+ human's yes), otherwise the fix is `unverified`. `--no-equiv` accepts at check+tests and records it
82
+ (`verified_level`: "check+tests, not equivalence"). `cfg!`/`#[cfg]` are rejected. Never edit or delete a test
83
+ to make the Rust pass.
84
+ 4. **Check**: `python2rust check rust_out/ --json [--deps-from Cargo.toml] [--offline]`
85
+ Compiles the Rust in a throwaway crate and groups errors by category with the Python line.
86
+ 5. **Iterate** until `check` exits 0 and `todos` lists nothing you have not handled. If an edit
87
+ makes the error count rise, revert it and try another approach.
88
+ 6. **Escalate** every TODO with `needs_review: true` (and any translated function a diagnostic flags
89
+ with a review code) to a human or a stronger model. Do not call those finished.
90
+
91
+ Never edit generated Rust, never delete a `todo!()` without replacing it by real code through `apply`, never
92
+ mark work done while `check` fails or TODOs remain.
93
+
94
+ `python2rust port SRC -o CRATE` runs the whole loop (translate, one `cargo check` per round, repair per function:
95
+ stored fix, compiler suggestions, then a model) and prints a JSON round log. `--agent none` (default) is a dry run
96
+ that lists the tasks it would send; nothing leaves the machine without `--agent cmd|anthropic|openai|azure`
97
+ (`cmd` gets task JSON on stdin, see `python2rust schema port-task`, and prints patch JSON, see `port-patch`).
98
+ The report's `unverified_patches` lists each model fix with its `id`, `file`, `function` and `patch_path`.
99
+ Submit each fix with `apply` to run the acceptance checks before calling `done`.
100
+ `python2rust contract PYTHON_OPENAPI.json RUST_CRATE_OR_OPENAPI.json` (experimental) diffs a FastAPI port's
101
+ OpenAPI document against the Python one (stable `PY2RS-C###` codes, exit 0 identical / 1 differences).
102
+
103
+ ## JSON contracts (full JSON Schemas: `python2rust schema [NAME]`)
104
+
105
+ `translate --json` (schema `translate`):
106
+ ```json
107
+ {"schema_version": 1, "command": "translate", "version": "0.1.0", "ok": false,
108
+ "summary": {"files": 1, "files_clean": 0, "files_with_todos": 1, "files_not_clean": 0, "files_failed": 0,
109
+ "functions_total": 2, "functions_clean": 1, "models_total": 1, "models_clean": 1,
110
+ "todo_count": 1, "needs_review_count": 0, "error_count": 0, "warning_count": 1,
111
+ "drift_count": 1, "drift_by_code": {"PY2RS041": 1}},
112
+ "files": [{"file": "shop.py", "status": "todo", "rust_path": "out/shop.rs", "rust": null,
113
+ "stats": {"functions_total": 2, "functions_clean": 1, "models_total": 1, "models_clean": 1, "todo_count": 1},
114
+ "diagnostics": [{"code": "PY2RS019", "severity": "warning", "message": "...", "file": "shop.py",
115
+ "line": 15, "col": 11, "construct": "call to unknown function getattr()", "hint": null}],
116
+ "todos": [], "patches": [], "notes": [], "error": null,
117
+ "drift": [{"code": "PY2RS041", "file": "shop.py", "line": 9,
118
+ "message": "Drift: int is i64 while Python ints are unbounded; ...",
119
+ "construct": "i64 arithmetic"}]}]}
120
+ ```
121
+ `drift` is the drift ledger: places where the Rust compiles but may behave differently from the
122
+ Python (PY2RS041..PY2RS049: overflow, float formatting, strict deserialisation, panics instead of
123
+ exceptions, ...). A clean, compiling file can still have drift notes: read them before trusting it.
124
+ `status` is `clean | not_clean | todo | error | internal_error`. A file with unresolved behavior
125
+ findings and no open TODOs reports `not_clean` and exits 1. Without `-o`, `rust` holds the source inline and
126
+ `rust_path` is null. Diagnostic codes are `PY2RS<NNN>`; `python2rust explain PY2RS019` says what a code
127
+ means, why, the typical fix and a before/after example.
128
+
129
+ `todos --json` (schema `todos`): `{"count": N, "todos": [...], "failed_files": [...]}`; each todo, the unit of work for one agent:
130
+ ```json
131
+ {"id": "teb7ba511", "code": "PY2RS019", "file": "shop.py", "line": 15, "kind": "stmt",
132
+ "python_snippet": "getattr(o, name)",
133
+ "rust_context": "pub fn get(o: Item, name: String) -> String {\n todo!(\"python2rust teb7ba511 PY2RS019: call to unknown function getattr() at shop.py:15\");\n}", "rust_line": 18,
134
+ "needs_review": false, "review_reason": null,
135
+ "rust_file": "out/shop.rs", "hint": "translate by hand from the python snippet",
136
+ "instruction": "Fix teb7ba511 (stmt, PY2RS019): write Rust that does what the Python at shop.py:15 does, to replace the todo!() at out/shop.rs:18. Do not edit the generated file. Submit only the replacement for that todo!() with `python2rust apply teb7ba511 --patch FILE` ... keep signatures; take types and helper names from rust_context."}
137
+ ```
138
+ `instruction` is the exact task text: follow it literally. `--jsonl` prints one such object per line.
139
+
140
+ `check --json` (schema `check`): `cargo.status` is `ok | errors | skipped | failed`:
141
+ ```json
142
+ {"ok": false, "translation": {"summary": {}, "files": []},
143
+ "cargo": {"available": true, "status": "errors", "reason": null, "errors": 1, "warnings": 0,
144
+ "errors_by_category": {"type-mismatch": 1},
145
+ "diagnostics": [{"file": "shop.py", "rust_file": "src/m000.rs", "rust_line": 8, "rust_col": 5,
146
+ "code": "E0308", "category": "type-mismatch", "message": "mismatched types",
147
+ "python_line": 15, "mapped_by": "source_map", "todo_id": "teb7ba511"}]}}
148
+ ```
149
+ `skipped` means cargo is not installed: the code was NOT compiled; say so, do not report success.
150
+ `failed` means cargo itself failed (offline cache, bad `--deps-from`); read `reason`. Categories:
151
+ type-mismatch, trait-bound, no-such-method, unresolved-name/-type/-import, use-after-move, borrow,
152
+ mutability, type-annotations-needed, lifetime, wrong-arg-count, no-such-field, async, syntax, other.
153
+ Crate imports show as `unresolved-import` unless you pass `--deps-from Cargo.toml`.
154
+
155
+ Other commands: `coverage PATH... --json` (corpus metrics, plus a markdown table), `constructs`
156
+ (the core's own list: supported / partial / todo constructs with their PY2RS codes), `doctor --json` (python, core, rustfmt, cargo,
157
+ config), `schema`, `skill`, `mcp` (stdio MCP server, needs `python2rust[mcp]`).
158
+
159
+ ## Configuration
160
+
161
+ `--config project.toml` carries project knowledge the translator cannot guess: `import_map` (Python
162
+ module to Rust path), `library_map` (third-party call to crate API), `type_map`, `review_patterns`
163
+ (what must be flagged for review). An unmapped import is a diagnostic (`PY2RS004`): fix it in the
164
+ config and re-translate rather than patching every file.
165
+
166
+ ## Worked example
167
+
168
+ ```text
169
+ $ cat shop.py
170
+ from dataclasses import dataclass
171
+
172
+
173
+ @dataclass
174
+ class Item:
175
+ id: int
176
+ title: str
177
+
178
+
179
+ def add(a: int, b: int) -> int:
180
+ return a + b
181
+
182
+
183
+ def get(o: Item, name: str) -> str:
184
+ return getattr(o, name)
185
+
186
+ $ python2rust todos shop.py -o out --json --quiet # exit 1: one todo, teb7ba511 = function `get`
187
+ $ cat -n out/shop.rs # line 18 is the todo!() named by rust_line
188
+ 17 pub fn get(o: Item, name: String) -> String {
189
+ 18 todo!("python2rust teb7ba511 PY2RS019: call to unknown function getattr() at shop.py:15");
190
+ 19 }
191
+ ```
192
+ Read `python_snippet` (`getattr` with a computed name): no static Rust form, so decide with the
193
+ caller which attributes are valid and write a `match`:
194
+ ```rust
195
+ pub fn get(o: &Item, name: &str) -> Result<String, Error> {
196
+ match name {
197
+ "id" => Ok(o.id.to_string()),
198
+ "title" => Ok(o.title.clone()),
199
+ _ => Err(Error::UnknownField(name.to_string())),
200
+ }
201
+ }
202
+ ```
203
+ Then `python2rust check out/ --deps-from Cargo.toml --json`: exit 0 and `cargo.status == "ok"` means it
204
+ compiles; a remaining `needs_review` flag still needs a reviewer. Behavioural equivalence is **not**
205
+ proven by any of this: add tests on both sides for anything that matters.
206
+
207
+ ## MCP
208
+
209
+ `python2rust mcp` serves the same operations over stdio: `translate_source`, `list_todos`,
210
+ `explain_diagnostic`, `check_rust`, `coverage`, `apply_patch`, and the workflow tools `init_questions`, `init_apply`,
211
+ `plan`, `next_unit`, `mark_done` (needs `--allow-compile`; never runs your Python) and `status`. Each returns the JSON documents above. Paths the tools
212
+ read (config, coverage) are limited to `--root` (default: the working directory). The tools that run cargo
213
+ (`check_rust`, `apply_patch`, coverage levels check and above) need `--allow-compile`: cargo executes code and
214
+ they compile model-supplied Rust, so enable it only with the human's agreement.
File without changes