auto-code-fixer 0.3.3__py3-none-any.whl → 0.3.5__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.
@@ -1 +1 @@
1
- __version__ = "0.3.3"
1
+ __version__ = "0.3.5"
auto_code_fixer/cli.py CHANGED
@@ -19,7 +19,23 @@ from auto_code_fixer import __version__
19
19
  DEFAULT_MAX_RETRIES = 8 # can be overridden via CLI
20
20
 
21
21
 
22
- def fix_file(file_path, project_root, api_key, ask, verbose, *, dry_run: bool, model: str | None, timeout_s: int, max_retries: int, run_cmd: str | None) -> bool:
22
+ def fix_file(
23
+ file_path,
24
+ project_root,
25
+ api_key,
26
+ ask,
27
+ verbose,
28
+ *,
29
+ dry_run: bool,
30
+ model: str | None,
31
+ timeout_s: int,
32
+ max_retries: int,
33
+ run_cmd: str | None,
34
+ patch_protocol: bool,
35
+ fmt: str | None,
36
+ lint: str | None,
37
+ lint_fix: bool,
38
+ ) -> bool:
23
39
  log(f"Processing entry file: {file_path}")
24
40
 
25
41
  project_root = os.path.abspath(project_root)
@@ -29,12 +45,65 @@ def fix_file(file_path, project_root, api_key, ask, verbose, *, dry_run: bool, m
29
45
  from auto_code_fixer.sandbox import make_sandbox
30
46
  sandbox_root, sandbox_entry = make_sandbox(entry_file=file_path, project_root=project_root)
31
47
 
48
+ # Always delete temp sandbox (best-effort). Also register atexit cleanup in case of crashes.
49
+ import atexit
50
+
51
+ def cleanup_sandbox() -> None:
52
+ try:
53
+ shutil.rmtree(sandbox_root)
54
+ except FileNotFoundError:
55
+ return
56
+ except Exception as e:
57
+ log(f"WARN: failed to delete sandbox dir {sandbox_root}: {e}")
58
+
59
+ atexit.register(cleanup_sandbox)
60
+
32
61
  # Create isolated venv in sandbox
33
62
  from auto_code_fixer.venv_manager import create_venv
34
63
  from auto_code_fixer.patcher import backup_file
35
64
 
36
65
  venv_python = create_venv(sandbox_root)
37
66
 
67
+ def _run_optional_formatters_and_linters() -> None:
68
+ # Best-effort formatting/linting (only if tools are installed in the sandbox venv).
69
+ from auto_code_fixer.command_runner import run_command
70
+
71
+ if fmt == "black":
72
+ rc, out, err = run_command(
73
+ "python -m black .",
74
+ timeout_s=max(timeout_s, 60),
75
+ python_exe=venv_python,
76
+ cwd=sandbox_root,
77
+ extra_env={"PYTHONPATH": sandbox_root},
78
+ )
79
+ if rc == 0:
80
+ log("Formatted with black", "DEBUG")
81
+ else:
82
+ # If black isn't installed, ignore.
83
+ if "No module named" in (err or "") and "black" in (err or ""):
84
+ log("black not installed in sandbox venv; skipping format", "DEBUG")
85
+ else:
86
+ log(f"black failed (rc={rc}): {err}", "DEBUG")
87
+
88
+ if lint == "ruff":
89
+ cmd = "python -m ruff check ."
90
+ if lint_fix:
91
+ cmd += " --fix"
92
+ rc, out, err = run_command(
93
+ cmd,
94
+ timeout_s=max(timeout_s, 60),
95
+ python_exe=venv_python,
96
+ cwd=sandbox_root,
97
+ extra_env={"PYTHONPATH": sandbox_root},
98
+ )
99
+ if rc == 0:
100
+ log("ruff check passed", "DEBUG")
101
+ else:
102
+ if "No module named" in (err or "") and "ruff" in (err or ""):
103
+ log("ruff not installed in sandbox venv; skipping lint", "DEBUG")
104
+ else:
105
+ log(f"ruff reported issues (rc={rc}): {err}", "DEBUG")
106
+
38
107
  changed_sandbox_files: set[str] = set()
39
108
 
40
109
  for attempt in range(max_retries):
@@ -82,7 +151,7 @@ def fix_file(file_path, project_root, api_key, ask, verbose, *, dry_run: bool, m
82
151
 
83
152
  if confirm != "y":
84
153
  log("User declined overwrite", "WARN")
85
- shutil.rmtree(sandbox_root)
154
+ cleanup_sandbox()
86
155
  return False
87
156
 
88
157
  if dry_run:
@@ -126,7 +195,7 @@ def fix_file(file_path, project_root, api_key, ask, verbose, *, dry_run: bool, m
126
195
  shutil.copy(p_real, dst_real)
127
196
  log(f"File updated: {dst_real}")
128
197
 
129
- shutil.rmtree(sandbox_root)
198
+ cleanup_sandbox()
130
199
  log(f"Fix completed in {attempt + 1} attempt(s) 🎉")
131
200
  return True
132
201
 
@@ -174,27 +243,68 @@ def fix_file(file_path, project_root, api_key, ask, verbose, *, dry_run: bool, m
174
243
 
175
244
  log(f"Sending {os.path.relpath(target_file, sandbox_root)} + error to GPT 🧠", "DEBUG")
176
245
 
177
- fixed_code = fix_code_with_gpt(
178
- original_code=open(target_file, encoding="utf-8").read(),
179
- error_log=stderr,
180
- api_key=api_key,
181
- model=model,
182
- )
246
+ applied_any = False
247
+
248
+ if patch_protocol:
249
+ try:
250
+ from auto_code_fixer.fixer import fix_code_with_gpt_patch_protocol
251
+ from auto_code_fixer.patch_protocol import (
252
+ parse_patch_protocol_response,
253
+ validate_and_resolve_patch_files,
254
+ )
255
+ from auto_code_fixer.patcher import safe_read, safe_write
256
+
257
+ hint_paths = [os.path.relpath(target_file, sandbox_root)]
258
+ raw = fix_code_with_gpt_patch_protocol(
259
+ sandbox_root=sandbox_root,
260
+ error_log=stderr,
261
+ api_key=api_key,
262
+ model=model,
263
+ hint_paths=hint_paths,
264
+ )
265
+
266
+ patch_files = parse_patch_protocol_response(raw)
267
+ resolved = validate_and_resolve_patch_files(patch_files, sandbox_root=sandbox_root)
268
+
269
+ # Apply patches (only if they change content)
270
+ for abs_path, new_content in resolved:
271
+ old = ""
272
+ if os.path.exists(abs_path):
273
+ old = safe_read(abs_path)
274
+ if new_content.strip() == (old or "").strip():
275
+ continue
276
+ safe_write(abs_path, new_content)
277
+ changed_sandbox_files.add(os.path.abspath(abs_path))
278
+ applied_any = True
279
+
280
+ except Exception as e:
281
+ log(f"Patch protocol failed ({e}); falling back to full-text mode", "WARN")
282
+
283
+ if not applied_any:
284
+ fixed_code = fix_code_with_gpt(
285
+ original_code=open(target_file, encoding="utf-8").read(),
286
+ error_log=stderr,
287
+ api_key=api_key,
288
+ model=model,
289
+ )
183
290
 
184
- if fixed_code.strip() == open(target_file, encoding="utf-8").read().strip():
185
- log("GPT returned no changes. Stopping.", "WARN")
186
- break
291
+ if fixed_code.strip() == open(target_file, encoding="utf-8").read().strip():
292
+ log("GPT returned no changes. Stopping.", "WARN")
293
+ break
187
294
 
188
- with open(target_file, "w", encoding="utf-8") as f:
189
- f.write(fixed_code)
295
+ with open(target_file, "w", encoding="utf-8") as f:
296
+ f.write(fixed_code)
190
297
 
191
- changed_sandbox_files.add(os.path.abspath(target_file))
298
+ changed_sandbox_files.add(os.path.abspath(target_file))
299
+ applied_any = True
192
300
 
193
- log("Code updated by GPT ✏️")
194
- time.sleep(1)
301
+ if applied_any:
302
+ _run_optional_formatters_and_linters()
303
+ log("Code updated by GPT ✏️")
304
+ time.sleep(1)
195
305
 
196
306
  log("Failed to auto-fix file after max retries ❌", "ERROR")
197
- shutil.rmtree(sandbox_root)
307
+ cleanup_sandbox()
198
308
  return False
199
309
 
200
310
 
@@ -235,6 +345,33 @@ def main():
235
345
  help="Optional: use AI to suggest which file to edit (AUTO_CODE_FIXER_AI_PLAN=1)",
236
346
  )
237
347
 
348
+ parser.add_argument(
349
+ "--patch-protocol",
350
+ action="store_true",
351
+ help=(
352
+ "Optional: ask the model for a strict JSON patch protocol with sha256 verification "
353
+ "(falls back to full-text mode if parsing/validation fails)"
354
+ ),
355
+ )
356
+
357
+ parser.add_argument(
358
+ "--format",
359
+ default=None,
360
+ choices=["black"],
361
+ help="Optional: run formatter in sandbox (best-effort). Currently supported: black",
362
+ )
363
+ parser.add_argument(
364
+ "--lint",
365
+ default=None,
366
+ choices=["ruff"],
367
+ help="Optional: run linter in sandbox (best-effort). Currently supported: ruff",
368
+ )
369
+ parser.add_argument(
370
+ "--fix",
371
+ action="store_true",
372
+ help="If used with --lint ruff, apply fixes (ruff --fix) (best-effort)",
373
+ )
374
+
238
375
  # ✅ Proper boolean flags
239
376
  ask_group = parser.add_mutually_exclusive_group()
240
377
  ask_group.add_argument(
@@ -289,6 +426,10 @@ def main():
289
426
  timeout_s=args.timeout,
290
427
  max_retries=args.max_retries,
291
428
  run_cmd=args.run,
429
+ patch_protocol=args.patch_protocol,
430
+ fmt=args.format,
431
+ lint=args.lint,
432
+ lint_fix=args.fix,
292
433
  )
293
434
 
294
435
  raise SystemExit(0 if ok else 2)
auto_code_fixer/fixer.py CHANGED
@@ -77,3 +77,67 @@ def fix_code_with_gpt(
77
77
  text += getattr(c, "text", "") or ""
78
78
 
79
79
  return _strip_code_fences(text)
80
+
81
+
82
+ def fix_code_with_gpt_patch_protocol(
83
+ *,
84
+ sandbox_root: str,
85
+ error_log: str,
86
+ api_key: str | None = None,
87
+ model: str | None = None,
88
+ hint_paths: list[str] | None = None,
89
+ ) -> str:
90
+ """Ask the model for structured edits (patch protocol).
91
+
92
+ Returns raw model text (expected JSON). Parsing/validation happens elsewhere.
93
+
94
+ The protocol is optional and should be enabled explicitly by the caller.
95
+ """
96
+
97
+ client = get_openai_client(api_key)
98
+ model = model or os.getenv("AUTO_CODE_FIXER_MODEL") or "gpt-4.1-mini"
99
+
100
+ schema = {
101
+ "files": [
102
+ {
103
+ "path": "relative/path/from/sandbox_root.py",
104
+ "new_content": "FULL new file contents",
105
+ "sha256": "sha256 hex of new_content encoded as utf-8",
106
+ }
107
+ ]
108
+ }
109
+
110
+ hints = ""
111
+ if hint_paths:
112
+ hints = "\n\nCANDIDATE FILES (relative paths; edit one or more if needed):\n" + "\n".join(
113
+ f"- {p}" for p in hint_paths
114
+ )
115
+
116
+ prompt = (
117
+ "You are a senior Python engineer. Fix the project so it runs without errors.\n"
118
+ "Return ONLY valid JSON that matches this schema (no markdown, no commentary):\n"
119
+ + json.dumps(schema)
120
+ + hints
121
+ + "\n\nSANDBOX ROOT:\n"
122
+ + sandbox_root
123
+ + "\n\nERROR LOG:\n"
124
+ + error_log
125
+ )
126
+
127
+ resp = client.responses.create(
128
+ model=model,
129
+ input=[
130
+ {"role": "system", "content": "You output strict JSON patches for code fixes."},
131
+ {"role": "user", "content": prompt},
132
+ ],
133
+ temperature=0.2,
134
+ max_output_tokens=3000,
135
+ )
136
+
137
+ text = ""
138
+ for item in resp.output or []:
139
+ for c in item.content or []:
140
+ if getattr(c, "type", None) in ("output_text", "text"):
141
+ text += getattr(c, "text", "") or ""
142
+
143
+ return _strip_code_fences(text)
@@ -0,0 +1,102 @@
1
+ import hashlib
2
+ import json
3
+ import os
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class PatchFile:
9
+ """A single file edit from the structured patch protocol."""
10
+
11
+ path: str
12
+ new_content: str
13
+ sha256: str
14
+
15
+
16
+ def strip_code_fences(text: str) -> str:
17
+ text = (text or "").strip()
18
+ if text.startswith("```"):
19
+ text = "\n".join(text.split("\n")[1:])
20
+ if text.endswith("```"):
21
+ text = "\n".join(text.split("\n")[:-1])
22
+ return text.strip()
23
+
24
+
25
+ def compute_sha256_utf8(content: str) -> str:
26
+ return hashlib.sha256((content or "").encode("utf-8")).hexdigest()
27
+
28
+
29
+ def parse_patch_protocol_response(text: str) -> list[PatchFile]:
30
+ """Parse model output for the patch protocol.
31
+
32
+ Expected JSON schema:
33
+ {"files": [{"path": "...", "new_content": "...", "sha256": "..."}, ...]}
34
+
35
+ Raises ValueError on invalid input.
36
+ """
37
+
38
+ cleaned = strip_code_fences(text)
39
+
40
+ try:
41
+ payload = json.loads(cleaned)
42
+ except Exception as e: # pragma: no cover
43
+ raise ValueError(f"Invalid JSON: {e}")
44
+
45
+ if not isinstance(payload, dict):
46
+ raise ValueError("Patch protocol JSON must be an object")
47
+
48
+ files = payload.get("files")
49
+ if not isinstance(files, list) or not files:
50
+ raise ValueError("Patch protocol JSON must contain non-empty 'files' list")
51
+
52
+ out: list[PatchFile] = []
53
+ for i, f in enumerate(files):
54
+ if not isinstance(f, dict):
55
+ raise ValueError(f"files[{i}] must be an object")
56
+
57
+ path = f.get("path")
58
+ new_content = f.get("new_content")
59
+ sha256 = f.get("sha256")
60
+
61
+ if not isinstance(path, str) or not path.strip():
62
+ raise ValueError(f"files[{i}].path must be a non-empty string")
63
+ if not isinstance(new_content, str):
64
+ raise ValueError(f"files[{i}].new_content must be a string")
65
+ if not isinstance(sha256, str) or len(sha256.strip()) != 64:
66
+ raise ValueError(f"files[{i}].sha256 must be a 64-char hex string")
67
+
68
+ out.append(PatchFile(path=path, new_content=new_content, sha256=sha256.strip().lower()))
69
+
70
+ return out
71
+
72
+
73
+ def validate_and_resolve_patch_files(
74
+ patch_files: list[PatchFile], *, sandbox_root: str
75
+ ) -> list[tuple[str, str]]:
76
+ """Validate patch files and return a list of (abs_path, new_content).
77
+
78
+ Safety:
79
+ - paths must be relative and remain within sandbox_root
80
+ - sha256 must match new_content (utf-8)
81
+ """
82
+
83
+ sr = os.path.realpath(os.path.abspath(sandbox_root))
84
+ resolved: list[tuple[str, str]] = []
85
+
86
+ for pf in patch_files:
87
+ if os.path.isabs(pf.path):
88
+ raise ValueError(f"Absolute path not allowed in patch protocol: {pf.path}")
89
+
90
+ # Normalize and resolve against sandbox_root
91
+ abs_path = os.path.realpath(os.path.abspath(os.path.join(sr, pf.path)))
92
+
93
+ if not (abs_path.startswith(sr + os.sep) or abs_path == sr):
94
+ raise ValueError(f"Patch path escapes sandbox root: {pf.path}")
95
+
96
+ got = compute_sha256_utf8(pf.new_content)
97
+ if got != pf.sha256:
98
+ raise ValueError(f"sha256 mismatch for {pf.path}: expected {pf.sha256}, got {got}")
99
+
100
+ resolved.append((abs_path, pf.new_content))
101
+
102
+ return resolved
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: auto-code-fixer
3
- Version: 0.3.3
3
+ Version: 0.3.5
4
4
  Summary: Automatically fix Python code using ChatGPT
5
5
  Author-email: Arif Shah <ashah7775@gmail.com>
6
6
  License: MIT
@@ -121,6 +121,21 @@ auto-code-fixer main.py --ai-plan
121
121
  ```
122
122
  This enables a helper that can suggest which local file to edit. It is best-effort.
123
123
 
124
+ ### Optional structured patch protocol (JSON + sha256)
125
+ ```bash
126
+ auto-code-fixer main.py --patch-protocol
127
+ ```
128
+ When enabled, the model is asked to return strict JSON with `{files:[{path,new_content,sha256}]}`.
129
+ The tool verifies the SHA-256 hash of `new_content` before applying edits, and falls back to the
130
+ legacy full-text mode if parsing/validation fails.
131
+
132
+ ### Optional formatting / linting (best-effort)
133
+ ```bash
134
+ auto-code-fixer main.py --format black
135
+ auto-code-fixer main.py --lint ruff --fix
136
+ ```
137
+ These run inside the sandbox venv and are skipped if the tools are not installed.
138
+
124
139
  ---
125
140
 
126
141
  ## Environment variables
@@ -1,9 +1,10 @@
1
- auto_code_fixer/__init__.py,sha256=8KcCYTXH99C2-gCLuPILJvtT9YftRWJsartIx6TQ2ZY,22
2
- auto_code_fixer/cli.py,sha256=Fsty_FJC7sm7mJCnXFQpwdF7N-fFxkJkgjhHFrGr0OA,10453
1
+ auto_code_fixer/__init__.py,sha256=ThnCuF3X7rsQSd5PAea_jfYA70ZmhLvkFcLBxBPwZnY,22
2
+ auto_code_fixer/cli.py,sha256=0UszYX0cmDQIQpuLYrRa_tJCklnzUiqDAAauOfsboeg,15307
3
3
  auto_code_fixer/command_runner.py,sha256=6P8hGRavN5C39x-e03p02Vc805NnZH9U7e48ngb5jJI,1104
4
- auto_code_fixer/fixer.py,sha256=DlAOVbw9AImEKJy8llisVCtss0tXKHMnioYeFBQGXlE,2293
4
+ auto_code_fixer/fixer.py,sha256=s4owenfSKpoutzXyhVJ2fVecHp12ioQf5s8uPYdWbN0,4180
5
5
  auto_code_fixer/installer.py,sha256=LC0jasSsPI7eHMeDxa622OoMCR1951HAXUZWp-kcmVY,1522
6
6
  auto_code_fixer/models.py,sha256=JLBJutOoiOjjlT_RMPUPhWlmm1yc_nGcQqv5tY72Al0,317
7
+ auto_code_fixer/patch_protocol.py,sha256=8l1E9o-3jkO4VAI7Ulrf-1MbAshNzjQXtUkmH-0hYio,3216
7
8
  auto_code_fixer/patcher.py,sha256=WDYrkl12Dm3fpWppxWRszDGyD0-Sty3ud6mIZhjAMBU,686
8
9
  auto_code_fixer/plan.py,sha256=jrZdG-f1RDxVB0tBLlTwKbCSEiOYI_RMetdzfBcyE4s,1762
9
10
  auto_code_fixer/runner.py,sha256=BvQm3CrwkQEDOw0tpiamSTcdu3OjbOgA801xW2zWdP8,970
@@ -11,9 +12,9 @@ auto_code_fixer/sandbox.py,sha256=FWQcCxNDI4i7ckTKHuARSSIHCopBRqG16MVtx9s75R8,16
11
12
  auto_code_fixer/traceback_utils.py,sha256=sbSuLO-2UBk5QPJZYJunTK9WGOpEY8mxR6WRKbtCIoM,935
12
13
  auto_code_fixer/utils.py,sha256=YXCv3PcDo5NBM1odksBTWkHTEELRtEXfPDIORA5iYaM,3090
13
14
  auto_code_fixer/venv_manager.py,sha256=2ww8reYgLbLohh-moAD5YKM09qv_mC5yYzJRwm3XiXc,1202
14
- auto_code_fixer-0.3.3.dist-info/licenses/LICENSE,sha256=hgchJNa26tjXuLztwSUDbYQxNLnAPnLk6kDXNIkC8xc,1066
15
- auto_code_fixer-0.3.3.dist-info/METADATA,sha256=JBkdvGh27MLYWEGNX_NS46dnoVtidUhPyAn7uflcgZ8,3290
16
- auto_code_fixer-0.3.3.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
17
- auto_code_fixer-0.3.3.dist-info/entry_points.txt,sha256=a-j2rkfwkrhXZ5Qbz_6_gwk6Bj7nijYR1DALjWp5Myk,61
18
- auto_code_fixer-0.3.3.dist-info/top_level.txt,sha256=qUk1qznb6Qxqmxy2A3z_5dpOZlmNKHwUiLuJwH-CrAk,16
19
- auto_code_fixer-0.3.3.dist-info/RECORD,,
15
+ auto_code_fixer-0.3.5.dist-info/licenses/LICENSE,sha256=hgchJNa26tjXuLztwSUDbYQxNLnAPnLk6kDXNIkC8xc,1066
16
+ auto_code_fixer-0.3.5.dist-info/METADATA,sha256=e2BJl84gGASwLXcrv3B1AjeTg8dVqnQcgOAN4KRCRb8,3870
17
+ auto_code_fixer-0.3.5.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
18
+ auto_code_fixer-0.3.5.dist-info/entry_points.txt,sha256=a-j2rkfwkrhXZ5Qbz_6_gwk6Bj7nijYR1DALjWp5Myk,61
19
+ auto_code_fixer-0.3.5.dist-info/top_level.txt,sha256=qUk1qznb6Qxqmxy2A3z_5dpOZlmNKHwUiLuJwH-CrAk,16
20
+ auto_code_fixer-0.3.5.dist-info/RECORD,,