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,265 @@
1
+ """JSON Schemas of the workflow documents: init (questions and apply), plan, next, done, status."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from python2rust.workflow.state import PHASES, TIERS
9
+
10
+ _STR = {"type": "string"}
11
+ _STR_OR_NULL = {"type": ["string", "null"]}
12
+ _INT = {"type": "integer"}
13
+ _STRS = {"type": "array", "items": _STR}
14
+
15
+ _NEXT_COMMAND = {
16
+ **_STR_OR_NULL,
17
+ "description": "The exact command to run next; null when complete.",
18
+ }
19
+
20
+
21
+ def build(
22
+ head: Callable[[str, dict[str, Any]], dict[str, Any]], obj: Callable[..., dict[str, Any]]
23
+ ) -> dict[str, dict[str, Any]]:
24
+ """The schemas, built with schemas.py's `_head` and `_obj` helpers."""
25
+ question = obj(
26
+ {
27
+ "id": _STR,
28
+ "question": _STR,
29
+ "why_it_matters": _STR,
30
+ "kind": {"enum": ["choice", "multi", "list", "int", "text"]},
31
+ "options": {
32
+ "type": "array",
33
+ "items": obj({"value": _STR, "label": _STR, "consequence": _STR}),
34
+ },
35
+ "default": {"description": "A string, integer or list of strings, by kind."},
36
+ "ask_human": {
37
+ "type": "boolean",
38
+ "description": "true: a human must decide; the agent never answers it for them.",
39
+ },
40
+ "only_if": {
41
+ "type": ["object", "null"],
42
+ "description": "{question id: [values]}: ask only when all of these hold.",
43
+ },
44
+ "pattern": _STR_OR_NULL,
45
+ }
46
+ )
47
+ coverage = obj(
48
+ {
49
+ "functions_total": _INT,
50
+ "functions_no_todo": _INT,
51
+ "models_total": _INT,
52
+ "models_no_todo": _INT,
53
+ "todo_count": _INT,
54
+ "no_todo_pct": {"type": ["number", "null"]},
55
+ "needs_review_todos": {"type": "array", "items": {"type": "object"}},
56
+ "translate_errors": _STRS,
57
+ }
58
+ )
59
+ difficulty = obj(
60
+ {"score": _INT, "level": {"enum": ["easy", "medium", "hard"]}, "reasons": _STRS}
61
+ )
62
+ risk = obj(
63
+ {
64
+ "areas": _STRS,
65
+ "dynamic": _STRS,
66
+ "io": _STRS,
67
+ "review_pattern_hits": _STRS,
68
+ "cycle": {"type": "boolean"},
69
+ }
70
+ )
71
+ unit = obj(
72
+ {
73
+ "id": _STR,
74
+ "order": _INT,
75
+ "level": _INT,
76
+ "modules": _STRS,
77
+ "files": _STRS,
78
+ "depends_on": _STRS,
79
+ "depends_on_python": _STRS,
80
+ "size": obj({"lines": _INT, "functions": _INT, "classes": _INT}),
81
+ "async_functions": _INT,
82
+ "try_blocks": _INT,
83
+ "except_handlers": _INT,
84
+ "exception_classes": _STRS,
85
+ "third_party": _STRS,
86
+ "stdlib": _STRS,
87
+ "tests": _STRS,
88
+ "coverage": coverage,
89
+ "risk": risk,
90
+ "difficulty": difficulty,
91
+ }
92
+ )
93
+ brief_unit = obj(
94
+ {
95
+ k: unit["properties"][k]
96
+ for k in (
97
+ "id",
98
+ "order",
99
+ "modules",
100
+ "files",
101
+ "depends_on",
102
+ "depends_on_python",
103
+ "tests",
104
+ "difficulty",
105
+ "risk",
106
+ "size",
107
+ "coverage",
108
+ )
109
+ }
110
+ )
111
+ todo_ref = {
112
+ "type": "object",
113
+ "description": "a needs_review item: id, file, line, reason, unit, state",
114
+ }
115
+ missing = obj(
116
+ {"rung": _STR, "file": _STR, "reason": _STR},
117
+ ["rung", "file", "reason"],
118
+ )
119
+ return {
120
+ "init-questions": head(
121
+ "init",
122
+ {
123
+ "mode": {"const": "questions"},
124
+ "ok": {"type": "boolean"},
125
+ "instructions": _STR,
126
+ "questions": {"type": "array", "items": question},
127
+ },
128
+ ),
129
+ "init": head(
130
+ "init",
131
+ {
132
+ "mode": {"const": "apply"},
133
+ "ok": {"type": "boolean"},
134
+ "project": _STR,
135
+ "files_written": _STRS,
136
+ "answers": {"type": "object"},
137
+ "answer_sources": {
138
+ "type": "object",
139
+ "additionalProperties": {"enum": ["answer", "default", "skipped"]},
140
+ },
141
+ "needs_human_confirmation": {
142
+ **_STRS,
143
+ "description": "ask_human questions that took the default.",
144
+ },
145
+ "warnings": _STRS,
146
+ "kept_done": _STRS,
147
+ "next_command": _NEXT_COMMAND,
148
+ },
149
+ ),
150
+ "plan": head(
151
+ "plan",
152
+ {
153
+ "ok": {"type": "boolean"},
154
+ "sources": _STRS,
155
+ "core": obj({"name": _STR}),
156
+ "summary": obj(
157
+ {
158
+ "modules": _INT,
159
+ "units": _INT,
160
+ "cycles": _INT,
161
+ "files_unparsable": _INT,
162
+ "tests_found": _INT,
163
+ "kept_python": _INT,
164
+ "estimated_no_todo_pct": {"type": ["number", "null"]},
165
+ }
166
+ ),
167
+ "cycles": {"type": "array", "items": _STRS},
168
+ "order": _STRS,
169
+ "units": {"type": "array", "items": unit},
170
+ "kept_python": _STRS,
171
+ "unparsable": {"type": "array", "items": obj({"file": _STR, "error": _STR})},
172
+ "third_party": _STRS,
173
+ "files_sha256": {"type": "object", "additionalProperties": _STR},
174
+ "warnings": _STRS,
175
+ },
176
+ ),
177
+ "next": head(
178
+ "next",
179
+ {
180
+ "ok": {"type": "boolean"},
181
+ "complete": {"type": "boolean"},
182
+ "unit": {"anyOf": [brief_unit, {"type": "null"}]},
183
+ "remaining": _INT,
184
+ "decisions": {"type": "array", "items": obj({"id": _STR, "decision": _STR})},
185
+ "mapping_notes": {
186
+ "anyOf": [
187
+ obj(
188
+ {
189
+ "types": _STRS,
190
+ "crates": {
191
+ "type": "array",
192
+ "items": obj({"python": _STR, "rust": _STR}),
193
+ },
194
+ "unmapped_imports": _STRS,
195
+ "exception_classes": _STRS,
196
+ }
197
+ ),
198
+ {"type": "null"},
199
+ ]
200
+ },
201
+ "open_questions": _STRS,
202
+ "commands": {
203
+ "type": "array",
204
+ "items": obj({"step": _STR, "purpose": _STR, "command": _STR}),
205
+ },
206
+ "acceptance": _STRS,
207
+ "porting_md": _STR,
208
+ "markdown": _STR,
209
+ },
210
+ ),
211
+ "done": head(
212
+ "done",
213
+ {
214
+ "ok": {"type": "boolean"},
215
+ "unit": _STR,
216
+ "recorded": {"type": "boolean"},
217
+ "tier": {
218
+ "enum": [*TIERS, None],
219
+ "description": "What actually ran and passed (null when not recorded).",
220
+ },
221
+ "requested_tier": {"enum": ["draft", "verified", "production"]},
222
+ "reviewed": {"type": "boolean"},
223
+ "next_command": _NEXT_COMMAND,
224
+ "level": _STR,
225
+ "required_rungs": _STRS,
226
+ "rungs": {"type": "object", "additionalProperties": _STR},
227
+ "missing": {"type": "array", "items": missing},
228
+ "not_verified": {
229
+ "type": "array",
230
+ "items": obj(
231
+ {"rung": _STR, "reason": _STR, "command": _STR}, ["rung", "reason"]
232
+ ),
233
+ },
234
+ "caveats": _STRS,
235
+ "review_pending": {"type": "array", "items": todo_ref},
236
+ },
237
+ ),
238
+ "status": head(
239
+ "status",
240
+ {
241
+ "ok": {"type": "boolean"},
242
+ "project": _STR,
243
+ "phase": {"enum": list(PHASES)},
244
+ "current_unit": _STR_OR_NULL,
245
+ "blockers": _STRS,
246
+ "next_command": _NEXT_COMMAND,
247
+ "open_questions": {"type": "array", "items": {"type": "object"}},
248
+ "review_queue": obj(
249
+ {"todos": {"type": "array", "items": todo_ref}, "units": _STRS}
250
+ ),
251
+ "progress": obj(
252
+ {
253
+ "units_total": _INT,
254
+ "units_done": _INT,
255
+ "units_pending": _INT,
256
+ "units_with_caveats": _INT,
257
+ "tier": _STR_OR_NULL,
258
+ "units_by_tier": {"type": "object", "additionalProperties": _INT},
259
+ "units_below_requested_tier": _INT,
260
+ }
261
+ ),
262
+ "warnings": _STRS,
263
+ },
264
+ ),
265
+ }
@@ -0,0 +1,392 @@
1
+ """The agent-first workflow: init -> plan -> (next -> work -> done)* with `status` always available.
2
+
3
+ State lives in `.python2rust/state.json` (answers, phase, completed units) and `.python2rust/plan.json`;
4
+ `python2rust.toml` holds the configuration derived from the answers. Every function returns
5
+ `(document, exit code)`, the same JSON the CLI prints and the MCP tools return.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import shutil
14
+ import sys
15
+ from datetime import UTC, datetime
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from python2rust import __version__
20
+ from python2rust.agent import finish
21
+ from python2rust.cli.ops import envelope
22
+ from python2rust.errors import EXIT_FINDINGS, EXIT_OK, UsageError
23
+ from python2rust.workflow import brief, interview, planner
24
+ from python2rust.workflow import project as scoping
25
+
26
+ STATE_DIR = ".python2rust"
27
+ TOML = "python2rust.toml"
28
+ PHASES = ("init needed", "plan needed", "porting", "verifying", "complete")
29
+ # What a recorded unit actually achieved, lowest first. `output_tier` (draft/verified/production) is
30
+ # what the human asked for; the recorded `tier` says which rungs really passed.
31
+ TIERS = ("compiled", "tested", "verified", "production")
32
+
33
+
34
+ def achieved_tier(rungs: dict[str, str]) -> str:
35
+ """compiled: cargo check; tested: plus clippy and cargo test; verified: Rust and Python gave the
36
+ same output (`equiv` ran and passed); production: all of it."""
37
+ ok = {r for r, status in rungs.items() if status == "pass"}
38
+ if "equiv" in ok:
39
+ return "production" if {"clippy", "test"} <= ok else "verified"
40
+ return "tested" if {"clippy", "test"} <= ok else "compiled"
41
+
42
+
43
+ # --- files --------------------------------------------------------------------------------------
44
+
45
+
46
+ def project_root(project: str) -> Path:
47
+ root = Path(project).resolve()
48
+ if not root.is_dir():
49
+ raise UsageError(f"project directory does not exist: {project}")
50
+ return root
51
+
52
+
53
+ def _read(path: Path, hint: str) -> dict[str, Any] | None:
54
+ if not path.is_file():
55
+ return None
56
+ try:
57
+ doc = json.loads(path.read_text(encoding="utf-8"))
58
+ except (OSError, ValueError) as exc:
59
+ raise UsageError(f"{path} is unreadable ({exc}); {hint}") from exc
60
+ if not isinstance(doc, dict):
61
+ raise UsageError(f"{path} is not a JSON object; {hint}")
62
+ return doc
63
+
64
+
65
+ def _write(path: Path, text: str) -> None:
66
+ path.parent.mkdir(parents=True, exist_ok=True)
67
+ tmp = path.with_name(path.name + ".tmp")
68
+ tmp.write_text(text, encoding="utf-8")
69
+ os.replace(tmp, path)
70
+
71
+
72
+ def _write_json(path: Path, doc: dict[str, Any]) -> None:
73
+ _write(path, json.dumps(doc, indent=2, ensure_ascii=False) + "\n")
74
+
75
+
76
+ def load_state(root: Path) -> dict[str, Any] | None:
77
+ return _read(root / STATE_DIR / "state.json", "fix it or re-run `python2rust init --force`")
78
+
79
+
80
+ def load_plan(root: Path) -> dict[str, Any] | None:
81
+ return _read(root / STATE_DIR / "plan.json", "re-run `python2rust plan`")
82
+
83
+
84
+ def _need_state(root: Path) -> dict[str, Any]:
85
+ state = load_state(root)
86
+ if state is None:
87
+ raise UsageError(
88
+ "this project is not initialised: run `python2rust init --questions --json`, ask the human, "
89
+ "then `python2rust init --answers FILE`"
90
+ )
91
+ return state
92
+
93
+
94
+ def _need_plan(root: Path) -> dict[str, Any]:
95
+ plan = load_plan(root)
96
+ if plan is None:
97
+ raise UsageError("there is no plan yet: run `python2rust plan --json`")
98
+ return plan
99
+
100
+
101
+ def _now() -> str:
102
+ return datetime.now(UTC).isoformat(timespec="seconds")
103
+
104
+
105
+ def phase_of(state: dict[str, Any] | None, plan: dict[str, Any] | None) -> str:
106
+ if state is None:
107
+ return "init needed"
108
+ if plan is None:
109
+ return "plan needed"
110
+ pending = [u for u in plan["order"] if u not in state["done"]]
111
+ if not pending:
112
+ return "complete"
113
+ return "verifying" if pending[0] in state["attempts"] else "porting"
114
+
115
+
116
+ def _save_state(root: Path, state: dict[str, Any], plan: dict[str, Any] | None) -> None:
117
+ state["phase"] = phase_of(state, plan)
118
+ _write_json(root / STATE_DIR / "state.json", state)
119
+
120
+
121
+ # --- init ---------------------------------------------------------------------------------------
122
+
123
+
124
+ def load_answers_file(path: str) -> dict[str, Any]:
125
+ try:
126
+ text = sys.stdin.read() if path == "-" else Path(path).read_text(encoding="utf-8")
127
+ doc = json.loads(text)
128
+ except (OSError, ValueError) as exc:
129
+ raise UsageError(f"cannot read answers file {path}: {exc}") from exc
130
+ if not isinstance(doc, dict):
131
+ raise UsageError(f"answers file {path} must hold one JSON object {{id: value}}")
132
+ return doc
133
+
134
+
135
+ def init_apply(
136
+ project: str,
137
+ given: dict[str, Any],
138
+ *,
139
+ defaults: bool = False,
140
+ force: bool = False,
141
+ human: bool = True,
142
+ ) -> tuple[dict[str, Any], int]:
143
+ """Write the answers, preserving user-only execution choices on the MCP path."""
144
+ root = project_root(project)
145
+ exist = [p for p in (TOML, f"{STATE_DIR}/state.json") if (root / p).exists()]
146
+ if exist and not force:
147
+ raise UsageError(
148
+ f"already initialised: {', '.join(exist)} exist(s). Nothing was changed; pass --force to "
149
+ "replace the answers and config (units already marked done are kept)"
150
+ )
151
+ old = load_state(root) if exist else None
152
+ if not human:
153
+ if "run_python" in given:
154
+ raise UsageError(
155
+ "the answer 'run_python' cannot be set through this interface: it is the user's "
156
+ "consent to execute their code. Leave it out (it stays 'no'); the user sets it with "
157
+ "`python2rust init --answer run_python=yes --force` in a terminal"
158
+ )
159
+ prior = old["answers"] if old else {}
160
+ for key in ("agent_cmd", "model"):
161
+ if key in given:
162
+ raise UsageError(
163
+ f"the answer {key!r} must be set by the user with `python2rust init`"
164
+ )
165
+ if given.get("backend", "none") != "none":
166
+ raise UsageError("the answer 'backend' must be set by the user with `python2rust init`")
167
+ if (
168
+ given.get("equivalence") == "functional-judge"
169
+ and prior.get("equivalence") != "functional-judge"
170
+ ):
171
+ raise UsageError(
172
+ "the 'functional-judge' mode must be enabled by the user with `python2rust init`"
173
+ )
174
+ given = {
175
+ **given,
176
+ "run_python": prior.get("run_python", "no"),
177
+ "backend": prior.get("backend", "none"),
178
+ }
179
+ for key in ("agent_cmd", "model"):
180
+ if key in prior and interview.applies(interview.BY_ID[key], given):
181
+ given[key] = prior[key]
182
+ values, sources = interview.resolve(given, defaults=defaults)
183
+ state = {
184
+ "schema_version": 1, "tool_version": __version__,
185
+ "created": old["created"] if old else _now(), "phase": "plan needed",
186
+ "answers": values, "answer_sources": sources,
187
+ "done": old["done"] if old else {}, "attempts": {}, "current": None,
188
+ } # fmt: skip
189
+ _write(root / TOML, interview.render_toml(values))
190
+ plan = load_plan(root) if old else None
191
+ _save_state(root, state, plan)
192
+ confirm = [i for i, s in sources.items() if s == "default" and interview.BY_ID[i]["ask_human"]]
193
+ doc = envelope(
194
+ "init", mode="apply", ok=True, project=str(root), files_written=[TOML, f"{STATE_DIR}/state.json"],
195
+ answers=values, answer_sources=sources, needs_human_confirmation=confirm,
196
+ warnings=interview.warnings_for(values), kept_done=sorted(state["done"]),
197
+ next_command="python2rust plan --json" if plan is None else "python2rust status --json",
198
+ ) # fmt: skip
199
+ return doc, EXIT_OK
200
+
201
+
202
+ # --- plan ---------------------------------------------------------------------------------------
203
+
204
+
205
+ def plan_project(project: str, paths: list[str]) -> tuple[dict[str, Any], int]:
206
+ root = project_root(project)
207
+ state = _need_state(root)
208
+ a = state["answers"]
209
+ scope = [Path(p).resolve() for p in paths] or [(root / s).resolve() for s in a["scope"]]
210
+ config = root / TOML
211
+ doc = planner.build_plan(root, scope, a, str(config) if config.is_file() else None)
212
+ orphans = sorted(set(state["done"]) - set(doc["order"]))
213
+ if orphans:
214
+ doc["warnings"].append(f"completed unit(s) no longer in the plan: {', '.join(orphans)}")
215
+ _write_json(root / STATE_DIR / "plan.json", doc)
216
+ state["current"] = state["current"] if state["current"] in doc["order"] else None
217
+ state["attempts"] = {k: v for k, v in state["attempts"].items() if k in doc["order"]}
218
+ _save_state(root, state, doc)
219
+ return doc, EXIT_OK if doc["ok"] else EXIT_FINDINGS
220
+
221
+
222
+ # --- next ---------------------------------------------------------------------------------------
223
+
224
+
225
+ def next_unit(project: str) -> tuple[dict[str, Any], int]:
226
+ root = project_root(project)
227
+ state, plan = _need_state(root), _need_plan(root)
228
+ a = state["answers"]
229
+ by_id = {u["id"]: u for u in plan["units"]}
230
+ pending = [i for i in plan["order"] if i not in state["done"]]
231
+ brief.refresh_porting(root, plan, a)
232
+ if not pending:
233
+ state["current"] = None
234
+ _save_state(root, state, plan)
235
+ text = "All units are done. Run `python2rust status --json` for the review queue.\n"
236
+ doc = envelope(
237
+ "next", ok=True, complete=True, unit=None, remaining=0, decisions=[], mapping_notes=None,
238
+ open_questions=[], commands=[], acceptance=[], porting_md=brief.PORTING, markdown=text,
239
+ ) # fmt: skip
240
+ return doc, EXIT_OK
241
+ state["current"] = pending[0]
242
+ _save_state(root, state, plan)
243
+ b = brief.build(by_id[pending[0]], a, root, len(pending))
244
+ return envelope("next", ok=True, complete=False, **b), EXIT_OK
245
+
246
+
247
+ # --- done ---------------------------------------------------------------------------------------
248
+
249
+
250
+ def unit_scope_args(project: str, unit_id: str) -> tuple[Path, dict[str, Any], dict[str, Any]]:
251
+ """(project root, plan, unit) for `--unit UNIT` on the commands that work on the whole project."""
252
+ root = project_root(project)
253
+ _need_state(root)
254
+ plan = _need_plan(root)
255
+ return root, plan, scoping.unit_of(plan, unit_id)
256
+
257
+
258
+ def done_unit(
259
+ project: str,
260
+ unit_id: str,
261
+ *,
262
+ reviewed: bool = False,
263
+ run_python: bool = False,
264
+ accept_not_clean: bool = False,
265
+ **cargo: Any,
266
+ ) -> tuple[dict[str, Any], int]:
267
+ """Judge and maybe record a unit. Python is executed only when `run_python` is true, which only
268
+ the CLI's `--run-python` sets, and only if the user's answers also allow it."""
269
+ root = project_root(project)
270
+ state, plan = _need_state(root), _need_plan(root)
271
+ unit = scoping.unit_of(plan, unit_id)
272
+ a = state["answers"]
273
+ r = finish.verify_unit(
274
+ root, plan, unit, a, run_python=run_python, accept_not_clean=accept_not_clean, **cargo
275
+ )
276
+ ok = not r["missing"]
277
+ tier = achieved_tier(r["rungs"]) if ok else None
278
+ if ok:
279
+ state["done"][unit_id] = {
280
+ "at": _now(), "tier": tier, "requested_tier": a["output_tier"],
281
+ "level": r["level"], "rungs": r["rungs"],
282
+ "not_verified": r["not_verified"], "caveats": r["caveats"],
283
+ "review_pending": [] if reviewed else r["review_pending"], "reviewed": reviewed,
284
+ } # fmt: skip
285
+ state["attempts"].pop(unit_id, None)
286
+ else:
287
+ state["attempts"][unit_id] = {"at": _now(), "missing": len(r["missing"])}
288
+ _save_state(root, state, plan)
289
+ doc = envelope(
290
+ "done", ok=ok, unit=unit_id, recorded=ok, tier=tier, requested_tier=a["output_tier"],
291
+ reviewed=reviewed,
292
+ next_command=_next_command(root, state, plan), **r,
293
+ ) # fmt: skip
294
+ return doc, EXIT_OK if ok else EXIT_FINDINGS
295
+
296
+
297
+ # --- status -------------------------------------------------------------------------------------
298
+
299
+
300
+ def _next_command(
301
+ root: Path, state: dict[str, Any] | None, plan: dict[str, Any] | None
302
+ ) -> str | None:
303
+ p = phase_of(state, plan)
304
+ if state is None or plan is None or p == "complete":
305
+ return {
306
+ "init needed": "python2rust init --questions --json",
307
+ "plan needed": "python2rust plan --json",
308
+ }.get(p)
309
+ if p == "verifying":
310
+ first = next(u for u in plan["order"] if u not in state["done"])
311
+ return brief.done_command(first, state["answers"])
312
+ return "python2rust next --json"
313
+
314
+
315
+ def _stale(root: Path, plan: dict[str, Any]) -> list[str]:
316
+ def digest(rel: str) -> str | None:
317
+ try:
318
+ return hashlib.sha256((root / rel).read_text(encoding="utf-8").encode()).hexdigest()
319
+ except OSError, UnicodeDecodeError:
320
+ return None
321
+
322
+ return [rel for rel, sha in plan["files_sha256"].items() if digest(rel) != sha]
323
+
324
+
325
+ def status_project(project: str) -> tuple[dict[str, Any], int]:
326
+ root = project_root(project)
327
+ state, plan = load_state(root), load_plan(root)
328
+ a = state["answers"] if state else {}
329
+ done = state["done"] if state else {}
330
+ blockers: list[str] = []
331
+ warnings: list[str] = []
332
+ if state and not (root / TOML).is_file():
333
+ blockers.append(f"{TOML} is missing: re-run `python2rust init --force`")
334
+ if state and shutil.which("cargo") is None:
335
+ blockers.append("cargo is not on PATH: no unit can be verified, so `done` will refuse")
336
+ units = plan["units"] if plan else []
337
+ pending = [u["id"] for u in units if u["id"] not in done]
338
+ for uid, att in (state["attempts"] if state else {}).items():
339
+ blockers.append(
340
+ f"`done {uid}` was refused: {att['missing']} item(s) missing; run it for the list"
341
+ )
342
+ queue = [
343
+ {**t, "unit": u["id"], "state": "planned"}
344
+ for u in units if u["id"] not in done
345
+ for t in u["coverage"]["needs_review_todos"]
346
+ ] + [
347
+ {**t, "unit": uid, "state": t["state"] if t["state"] == "judged" else "awaiting-human"}
348
+ for uid, rec in sorted(done.items()) for t in rec["review_pending"]
349
+ ] # fmt: skip
350
+ below = sorted(uid for uid, rec in done.items() if rec.get("not_verified"))
351
+ for uid in below:
352
+ rec = done[uid]
353
+ missing = ", ".join(n["rung"] for n in rec["not_verified"])
354
+ redo = brief.done_command(uid, a) if brief.needs_equiv(a) else None
355
+ warnings.append(
356
+ f"unit {uid} is recorded as '{rec.get('tier')}', below the requested "
357
+ f"'{rec.get('requested_tier', a.get('output_tier'))}': {missing} did not run. "
358
+ + (f"Run `{redo}`" if redo else "The user answered run_python=no, so it cannot run")
359
+ )
360
+ waiting = sorted(uid for uid, rec in done.items() if rec["review_pending"])
361
+ if waiting:
362
+ blockers.append(f"{len(waiting)} unit(s) wait for a human review: {', '.join(waiting)}")
363
+ if plan and (stale := _stale(root, plan)):
364
+ warnings.append(
365
+ f"{len(stale)} source file(s) changed since the plan: re-run `python2rust plan`"
366
+ )
367
+ open_q = [
368
+ {k: interview.BY_ID[i][k] for k in ("id", "question", "why_it_matters", "default")}
369
+ | {
370
+ "answered_with": a[i],
371
+ "how": f"confirm or change: python2rust init --answer {i}=VALUE --force",
372
+ }
373
+ for i, s in (state["answer_sources"] if state else {}).items()
374
+ if s == "default" and interview.BY_ID[i]["ask_human"]
375
+ ]
376
+ p = phase_of(state, plan)
377
+ doc = envelope(
378
+ "status", ok=True, project=str(root), phase=p,
379
+ current_unit=(pending[0] if pending and plan else None), blockers=blockers,
380
+ next_command=_next_command(root, state, plan), open_questions=open_q,
381
+ review_queue={"todos": queue, "units": waiting},
382
+ progress={
383
+ "units_total": len(units), "units_done": len(units) - len(pending),
384
+ "units_pending": len(pending),
385
+ "units_with_caveats": sum(bool(done[u]["caveats"] or done[u]["not_verified"]) for u in done),
386
+ "tier": a.get("output_tier"),
387
+ "units_by_tier": {t: sum(done[u].get("tier") == t for u in done) for t in TIERS},
388
+ "units_below_requested_tier": len(below),
389
+ },
390
+ warnings=warnings,
391
+ ) # fmt: skip
392
+ return doc, EXIT_OK