datapi-selfheal 0.3.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.
selfheal_api/cli.py ADDED
@@ -0,0 +1,958 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import difflib
5
+ import importlib
6
+ import importlib.metadata
7
+ import importlib.util
8
+ import json
9
+ import os
10
+ import shlex
11
+ import shutil
12
+ import sqlite3
13
+ import stat
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import urllib.error
18
+ import urllib.request
19
+ from collections.abc import Sequence
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from pydantic import BaseModel
25
+
26
+ from selfheal_api.modelgen import (
27
+ emit_pydantic,
28
+ emit_zod,
29
+ infer_object_schema,
30
+ load_payload_samples,
31
+ )
32
+ from selfheal_api.replay import load_jsonl_samples, run_replay_corpus
33
+ from sentinel.detector import detect_drift
34
+ from sentinel.guard import compute_drift_fingerprint
35
+ from sentinel.llm_fallback import AnthropicSchemaMappingProvider, SchemaMappingProvider
36
+ from synthesizer.openapi_emitter import emit_openapi_document, emit_openapi_schema_patch
37
+ from synthesizer.patcher import PatchPlan, build_patch_plan, synthesize_patch, verify_patch
38
+ from synthesizer.zod_emitter import synthesize_zod_preprocessor
39
+
40
+
41
+ def _load_model_from_spec(model_spec: str) -> tuple[Path, type[BaseModel]]:
42
+ if ":" not in model_spec:
43
+ raise ValueError(
44
+ f"Invalid --model specification {model_spec!r}; expected <path/to/file.py:ClassName>"
45
+ )
46
+ file_part, class_name = model_spec.rsplit(":", 1)
47
+ model_path = Path(file_part).resolve()
48
+ if not model_path.is_file():
49
+ raise FileNotFoundError(f"Model file not found: {model_path}")
50
+
51
+ module_name = f"_selfheal_target_{model_path.stem}"
52
+ spec = importlib.util.spec_from_file_location(module_name, str(model_path))
53
+ if spec is None or spec.loader is None:
54
+ raise ImportError(f"Unable to load Python module spec from {model_path}")
55
+ module = importlib.util.module_from_spec(spec)
56
+ sys.modules[module_name] = module
57
+ spec.loader.exec_module(module)
58
+
59
+ model_cls = getattr(module, class_name, None)
60
+ if not isinstance(model_cls, type) or not issubclass(model_cls, BaseModel):
61
+ raise ValueError(
62
+ f"Attribute {class_name!r} in {model_path} is not a Pydantic BaseModel subclass"
63
+ )
64
+ return model_path, model_cls
65
+
66
+
67
+ def _load_json_file(path_str: str) -> dict[str, Any]:
68
+ p = Path(path_str)
69
+ if not p.is_file():
70
+ raise FileNotFoundError(f"JSON payload file not found: {p}")
71
+ data: Any = json.loads(p.read_text(encoding="utf-8"))
72
+ if not isinstance(data, dict):
73
+ raise ValueError(f"Expected JSON object in {p}, got {type(data).__name__}")
74
+ return data
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class _FileSnapshot:
79
+ """Captured raw bytes and permission bits for lossless rollback."""
80
+
81
+ path: Path
82
+ existed: bool
83
+ raw_bytes: bytes | None
84
+ mode: int | None
85
+
86
+ @classmethod
87
+ def capture(cls, path: Path) -> _FileSnapshot:
88
+ if not path.exists():
89
+ return cls(path=path, existed=False, raw_bytes=None, mode=None)
90
+ return cls(
91
+ path=path,
92
+ existed=True,
93
+ raw_bytes=path.read_bytes(),
94
+ mode=stat.S_IMODE(path.stat().st_mode),
95
+ )
96
+
97
+ def restore(self) -> None:
98
+ if not self.existed:
99
+ self.path.unlink(missing_ok=True)
100
+ return
101
+ if self.raw_bytes is not None:
102
+ _atomic_write_bytes(self.path, self.raw_bytes, mode=self.mode)
103
+
104
+
105
+ def _atomic_write_bytes(target: Path, data: bytes, mode: int | None = None) -> None:
106
+ target.parent.mkdir(parents=True, exist_ok=True)
107
+ fd, tmp_name = tempfile.mkstemp(
108
+ dir=str(target.parent), prefix=f".{target.name}.", suffix=".tmp"
109
+ )
110
+ try:
111
+ with os.fdopen(fd, "wb") as handle:
112
+ handle.write(data)
113
+ if mode is not None:
114
+ os.chmod(tmp_name, mode)
115
+ os.replace(tmp_name, target)
116
+ except Exception:
117
+ if os.path.exists(tmp_name):
118
+ os.unlink(tmp_name)
119
+ raise
120
+
121
+
122
+ def _atomic_write(target: Path, content: str, mode: int | None = None) -> None:
123
+ _atomic_write_bytes(target, content.encode("utf-8"), mode=mode)
124
+
125
+
126
+ def _run_mypy_shadow_gate(model_path: Path, patched_source: str) -> tuple[bool, str]:
127
+ with tempfile.NamedTemporaryFile(
128
+ mode="w", suffix=".py", encoding="utf-8", delete=False
129
+ ) as tmp:
130
+ tmp.write(patched_source)
131
+ tmp_path = Path(tmp.name)
132
+
133
+ try:
134
+ proc = subprocess.run(
135
+ [
136
+ sys.executable,
137
+ "-m",
138
+ "mypy",
139
+ "--strict",
140
+ "--shadow-file",
141
+ str(model_path),
142
+ str(tmp_path),
143
+ str(model_path),
144
+ ],
145
+ capture_output=True,
146
+ text=True,
147
+ check=False,
148
+ timeout=30,
149
+ )
150
+ ok = proc.returncode == 0
151
+ detail = (proc.stdout + "\n" + proc.stderr).strip()
152
+ return ok, detail
153
+ except (subprocess.TimeoutExpired, OSError) as exc:
154
+ return False, str(exc)
155
+ finally:
156
+ if tmp_path.exists():
157
+ tmp_path.unlink()
158
+
159
+
160
+ def _run_pytest_gate(pytest_args: Sequence[str]) -> tuple[bool, str]:
161
+ try:
162
+ proc = subprocess.run(
163
+ [sys.executable, "-m", "pytest", *pytest_args],
164
+ capture_output=True,
165
+ text=True,
166
+ check=False,
167
+ timeout=60,
168
+ )
169
+ ok = proc.returncode == 0
170
+ detail = (proc.stdout + "\n" + proc.stderr).strip()
171
+ return ok, detail
172
+ except (subprocess.TimeoutExpired, OSError) as exc:
173
+ return False, str(exc)
174
+
175
+
176
+ def _open_github_pr(
177
+ model_path: Path,
178
+ zod_path: Path | None,
179
+ branch_name: str,
180
+ model_name: str,
181
+ fingerprint: str,
182
+ openapi_path: Path | None = None,
183
+ ) -> None:
184
+ files_to_commit = [str(model_path)]
185
+ if zod_path is not None:
186
+ files_to_commit.append(str(zod_path))
187
+ if openapi_path is not None:
188
+ files_to_commit.append(str(openapi_path))
189
+
190
+ status_proc = subprocess.run(
191
+ ["git", "status", "--porcelain", "--", *files_to_commit],
192
+ capture_output=True,
193
+ text=True,
194
+ check=False,
195
+ timeout=15,
196
+ )
197
+ if status_proc.returncode != 0:
198
+ raise RuntimeError(f"git status failed: {status_proc.stderr.strip()}")
199
+ if not status_proc.stdout.strip():
200
+ raise RuntimeError("No modified or untracked files to commit for PR")
201
+
202
+ subprocess.run(
203
+ ["git", "checkout", "-B", branch_name],
204
+ check=True,
205
+ capture_output=True,
206
+ text=True,
207
+ timeout=15,
208
+ )
209
+ subprocess.run(
210
+ ["git", "add", "--", *files_to_commit],
211
+ check=True,
212
+ capture_output=True,
213
+ text=True,
214
+ timeout=15,
215
+ )
216
+ commit_msg = f"fix(schema): self-heal {model_name} ({fingerprint[:8]})"
217
+ subprocess.run(
218
+ ["git", "commit", "--only", *files_to_commit, "-m", commit_msg],
219
+ check=True,
220
+ capture_output=True,
221
+ text=True,
222
+ timeout=15,
223
+ )
224
+ subprocess.run(
225
+ ["git", "push", "-u", "origin", branch_name],
226
+ check=True,
227
+ capture_output=True,
228
+ text=True,
229
+ timeout=30,
230
+ )
231
+ pr_body = (
232
+ f"Automated schema-drift adapter patch for `{model_name}`.\n\n"
233
+ f"- Drift fingerprint: `{fingerprint}`\n"
234
+ "- Verification gate: `verify_patch` + `mypy --strict --shadow-file` + `pytest` passed.\n"
235
+ )
236
+ subprocess.run(
237
+ [
238
+ "gh",
239
+ "pr",
240
+ "create",
241
+ "--title",
242
+ f"fix(schema): self-heal {model_name} drift ({fingerprint[:8]})",
243
+ "--body",
244
+ pr_body,
245
+ ],
246
+ check=True,
247
+ capture_output=True,
248
+ text=True,
249
+ timeout=30,
250
+ )
251
+
252
+
253
+ def _package_version() -> str:
254
+ for dist_name in ("datapi-selfheal", "selfheal-api"):
255
+ try:
256
+ return importlib.metadata.version(dist_name)
257
+ except importlib.metadata.PackageNotFoundError:
258
+ continue
259
+ try:
260
+ mod = importlib.import_module("selfheal_api")
261
+ version = getattr(mod, "__version__", None)
262
+ if isinstance(version, str):
263
+ return version
264
+ except ImportError:
265
+ pass
266
+ return "unknown"
267
+
268
+
269
+ def build_parser() -> argparse.ArgumentParser:
270
+ parser = argparse.ArgumentParser(
271
+ prog="selfheal",
272
+ description="Datapi SelfHeal schema-drift detection, CST synthesis, and verification CLI",
273
+ )
274
+ parser.add_argument(
275
+ "-V",
276
+ "--version",
277
+ action="version",
278
+ version=f"%(prog)s {_package_version()}",
279
+ )
280
+ sub = parser.add_subparsers(dest="command", required=True)
281
+
282
+ check_p = sub.add_parser(
283
+ "check", help="Detect schema drift and emit zero-PII DriftReport JSON"
284
+ )
285
+ check_p.add_argument(
286
+ "--model", required=True, help="Target model as <path/to/file.py:ClassName>"
287
+ )
288
+ check_p.add_argument("--payload", required=True, help="Path to JSON payload file")
289
+ check_p.add_argument(
290
+ "--llm-fallback",
291
+ action="store_true",
292
+ help="Enable zero-PII AnthropicSchemaMappingProvider fallback for opaque renames",
293
+ )
294
+
295
+ heal_p = sub.add_parser(
296
+ "heal", help="Synthesize, verify, and optionally write/PR schema-drift patch"
297
+ )
298
+ heal_p.add_argument(
299
+ "--model", required=True, help="Target model as <path/to/file.py:ClassName>"
300
+ )
301
+ heal_p.add_argument(
302
+ "--payload", required=True, help="Path to drifted JSON payload file"
303
+ )
304
+ heal_p.add_argument(
305
+ "--canonical", default=None, help="Optional path to canonical legacy JSON"
306
+ )
307
+ heal_p.add_argument(
308
+ "--llm-fallback", action="store_true", help="Enable zero-PII Anthropic fallback"
309
+ )
310
+ heal_p.add_argument(
311
+ "--pytest-args", default="", help="Extra arguments passed to pytest gate"
312
+ )
313
+ heal_p.add_argument(
314
+ "--diff", action="store_true", help="Print unified diff of patched model"
315
+ )
316
+ heal_p.add_argument(
317
+ "--write", action="store_true", help="Write verified patch back to model file"
318
+ )
319
+ heal_p.add_argument(
320
+ "--zod", default=None, help="Write TypeScript Zod preprocessor to output path"
321
+ )
322
+ heal_p.add_argument(
323
+ "--openapi",
324
+ default=None,
325
+ help="Optional output path for OpenAPI 3.1 components.schemas JSON",
326
+ )
327
+ heal_p.add_argument(
328
+ "--open-pr",
329
+ action="store_true",
330
+ help="Create branch, commit verified patch, and open GitHub PR",
331
+ )
332
+ heal_p.add_argument(
333
+ "--branch", default=None, help="Target branch name for --open-pr"
334
+ )
335
+
336
+ replay_p = sub.add_parser(
337
+ "replay",
338
+ help="Replay a JSONL corpus of recorded payloads against a Pydantic model",
339
+ )
340
+ replay_p.add_argument(
341
+ "--model", required=True, help="Target model as <path/to/file.py:ClassName>"
342
+ )
343
+ replay_p.add_argument(
344
+ "--corpus",
345
+ required=True,
346
+ help="Path to JSONL corpus of ReplaySample records",
347
+ )
348
+ replay_p.add_argument(
349
+ "--payload",
350
+ default=None,
351
+ help="Optional drifted payload JSON to synthesize a PatchPlan for replay",
352
+ )
353
+
354
+ doctor_p = sub.add_parser(
355
+ "doctor",
356
+ help="Check Python, required libraries, CLI tools, and API key configuration",
357
+ )
358
+ doctor_p.add_argument(
359
+ "--json",
360
+ action="store_true",
361
+ help="Emit diagnostic report as JSON",
362
+ )
363
+ doctor_p.add_argument(
364
+ "--deploy-url",
365
+ default=None,
366
+ help="Optional hosted base URL to probe /healthz (deploy-config check)",
367
+ )
368
+
369
+ init_p = sub.add_parser(
370
+ "init",
371
+ help="Scaffold starter selfheal.config.json and GitHub Actions drift check workflow",
372
+ )
373
+ init_p.add_argument(
374
+ "--dir",
375
+ default=".",
376
+ help="Target directory to scaffold starter files (default: .)",
377
+ )
378
+ init_p.add_argument(
379
+ "--force",
380
+ action="store_true",
381
+ help="Overwrite existing files if present",
382
+ )
383
+
384
+ schema_p = sub.add_parser(
385
+ "schema",
386
+ help="Emit JSON Schema, OpenAPI 3.1, or TypeScript/Zod schema for a Pydantic model",
387
+ )
388
+ schema_p.add_argument(
389
+ "--model",
390
+ required=True,
391
+ help="Model spec <path/to/file.py:ClassName>",
392
+ )
393
+ schema_p.add_argument(
394
+ "--format",
395
+ choices=("jsonschema", "openapi", "zod"),
396
+ default="jsonschema",
397
+ help="Output schema format (default: jsonschema)",
398
+ )
399
+ schema_p.add_argument(
400
+ "--out",
401
+ default=None,
402
+ help="Optional output file path; prints to stdout if omitted",
403
+ )
404
+
405
+ connect_p = sub.add_parser(
406
+ "connect",
407
+ help="Exchange a GitHub App install token for an org API key and link this repo",
408
+ )
409
+ connect_p.add_argument(
410
+ "--token",
411
+ required=True,
412
+ help="One-time install token from the SelfHeal install flow (sit_*)",
413
+ )
414
+ connect_p.add_argument(
415
+ "--server",
416
+ default=None,
417
+ help="Control-plane base URL (default: SELFHEAL_API_BASE_URL or http://127.0.0.1:8080)",
418
+ )
419
+ connect_p.add_argument(
420
+ "--config",
421
+ default="selfheal.config.json",
422
+ help="Path to selfheal.config.json to merge org settings into",
423
+ )
424
+
425
+ models_p = sub.add_parser(
426
+ "models", help="Generate Pydantic/Zod models from JSON payload samples"
427
+ )
428
+ models_sub = models_p.add_subparsers(dest="models_command", required=True)
429
+ models_init_p = models_sub.add_parser(
430
+ "init", help="Infer a model schema from payload file(s) or a directory"
431
+ )
432
+ models_init_p.add_argument(
433
+ "--payload",
434
+ required=True,
435
+ help="Path to a JSON payload file, or a directory of *.json samples",
436
+ )
437
+ models_init_p.add_argument(
438
+ "--name",
439
+ default=None,
440
+ help="Model name (default: inferred from payload file stem)",
441
+ )
442
+ models_init_p.add_argument(
443
+ "--format",
444
+ choices=("pydantic", "zod"),
445
+ default="pydantic",
446
+ help="Output format (default: pydantic)",
447
+ )
448
+ models_init_p.add_argument(
449
+ "--out",
450
+ default=None,
451
+ help="Output file path (default: stdout)",
452
+ )
453
+ return parser
454
+
455
+
456
+ def _check_package(package_name: str) -> dict[str, Any]:
457
+ """Check whether a Python package is importable and resolve its version."""
458
+ try:
459
+ mod = importlib.import_module(package_name)
460
+ except ImportError:
461
+ return {"available": False, "version": None}
462
+
463
+ version: str | None = getattr(mod, "__version__", None)
464
+ if not isinstance(version, str):
465
+ try:
466
+ version = importlib.metadata.version(package_name)
467
+ except importlib.metadata.PackageNotFoundError:
468
+ version = None
469
+ return {"available": True, "version": version}
470
+
471
+
472
+ def _cmd_doctor(args: argparse.Namespace) -> int:
473
+ """Run local environment diagnostics without exposing secret values."""
474
+ py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
475
+ python_ok = sys.version_info >= (3, 12)
476
+
477
+ pydantic_info = _check_package("pydantic")
478
+ libcst_info = _check_package("libcst")
479
+ pydantic_ok = bool(pydantic_info["available"])
480
+ libcst_ok = bool(libcst_info["available"])
481
+
482
+ binary_names = ("ruff", "mypy", "pytest", "git", "gh")
483
+ binary_paths = {name: shutil.which(name) for name in binary_names}
484
+ anthropic_configured = bool(os.environ.get("ANTHROPIC_API_KEY"))
485
+ db_path_env = os.environ.get("SELFHEAL_DB_PATH", "").strip() or ":memory:"
486
+ db_writable = (
487
+ True
488
+ if db_path_env == ":memory:" or db_path_env.startswith("file:")
489
+ else os.access(Path(db_path_env).parent, os.W_OK)
490
+ if Path(db_path_env).parent.exists()
491
+ else True
492
+ )
493
+
494
+ healthy = python_ok and pydantic_ok and libcst_ok and db_writable
495
+
496
+ # EXP-11/T12: hosted deploy-config check — env *presence* only, never
497
+ # values. Does not affect `healthy` (OSS installs don't need hosted env).
498
+ hosted_env_names = (
499
+ "SELFHEAL_STATE_SECRET",
500
+ "SELFHEAL_JOBS_TOKEN",
501
+ "SELFHEAL_DB_PATH",
502
+ "SELFHEAL_PUBLIC_BASE_URL",
503
+ "SELFHEAL_GITHUB_APP_ID",
504
+ "SELFHEAL_GITHUB_APP_PRIVATE_KEY",
505
+ "SELFHEAL_GITHUB_APP_SLUG",
506
+ "SELFHEAL_WEBHOOK_SECRET",
507
+ "STRIPE_SECRET_KEY",
508
+ "STRIPE_WEBHOOK_SECRET",
509
+ )
510
+ deploy_env = {
511
+ name: {"configured": bool(os.environ.get(name, "").strip())}
512
+ for name in hosted_env_names
513
+ }
514
+ deploy_report: dict[str, Any] = {"env": deploy_env}
515
+ deploy_url = (args.deploy_url or "").strip().rstrip("/")
516
+ if deploy_url:
517
+ healthz_ok = False
518
+ try:
519
+ req = urllib.request.Request(f"{deploy_url}/healthz", method="GET")
520
+ with urllib.request.urlopen(req, timeout=5.0) as resp:
521
+ healthz_ok = resp.status == 200
522
+ except (urllib.error.URLError, OSError, ValueError):
523
+ healthz_ok = False
524
+ deploy_report["healthz"] = {"url": deploy_url, "ok": healthz_ok}
525
+
526
+ if args.json:
527
+ report: dict[str, Any] = {
528
+ "healthy": healthy,
529
+ "python_version": {"version": py_ver, "ok": python_ok},
530
+ "sqlite": {
531
+ "version": sqlite3.sqlite_version,
532
+ "db_path": db_path_env,
533
+ "writable": db_writable,
534
+ },
535
+ "packages": {
536
+ "pydantic": pydantic_info,
537
+ "libcst": libcst_info,
538
+ },
539
+ "binaries": {
540
+ name: {"available": path is not None, "path": path}
541
+ for name, path in binary_paths.items()
542
+ },
543
+ "anthropic_api_key_configured": anthropic_configured,
544
+ "deploy": deploy_report,
545
+ }
546
+ print(json.dumps(report, indent=2))
547
+ else:
548
+ lines = [
549
+ f"[{'ok' if python_ok else 'FAIL'}] python >= 3.12 ({py_ver})",
550
+ f"[{'ok' if db_writable else 'FAIL'}] sqlite "
551
+ f"({sqlite3.sqlite_version}, db_path={db_path_env})",
552
+ f"[{'ok' if pydantic_ok else 'FAIL'}] pydantic "
553
+ f"({pydantic_info['version'] or 'not installed'})",
554
+ f"[{'ok' if libcst_ok else 'FAIL'}] libcst "
555
+ f"({libcst_info['version'] or 'not installed'})",
556
+ ]
557
+ for name, path in binary_paths.items():
558
+ status = "ok" if path is not None else "missing"
559
+ detail = path if path is not None else "not found"
560
+ lines.append(f"[{status}] {name} ({detail})")
561
+ lines.append(
562
+ f"[{'ok' if anthropic_configured else 'unset'}] ANTHROPIC_API_KEY "
563
+ f"({'configured' if anthropic_configured else 'not configured'})"
564
+ )
565
+ missing_env = [
566
+ name for name, info in deploy_env.items() if not info["configured"]
567
+ ]
568
+ lines.append(
569
+ "[deploy] hosted env: "
570
+ + ("all configured" if not missing_env else f"missing {missing_env}")
571
+ )
572
+ if "healthz" in deploy_report:
573
+ hz = deploy_report["healthz"]
574
+ lines.append(
575
+ f"[{'ok' if hz['ok'] else 'FAIL'}] deploy /healthz "
576
+ f"({hz['url']})"
577
+ )
578
+ print("\n".join(lines))
579
+
580
+ return 0 if healthy else 1
581
+
582
+
583
+ def _cmd_replay(args: argparse.Namespace) -> int:
584
+ try:
585
+ _, model_cls = _load_model_from_spec(args.model)
586
+ samples = load_jsonl_samples(args.corpus)
587
+ plan: PatchPlan | None = None
588
+ if args.payload is not None:
589
+ drifted_payload = _load_json_file(args.payload)
590
+ drift_report = detect_drift(model_cls, drifted_payload)
591
+ plan = build_patch_plan(drift_report, root_model=model_cls)
592
+ except (FileNotFoundError, ValueError, ImportError, json.JSONDecodeError, OSError) as exc:
593
+ print(f"error: {exc}", file=sys.stderr)
594
+ return 2
595
+
596
+ report = run_replay_corpus(model_cls, samples, plan=plan)
597
+ print(report.model_dump_json(indent=2))
598
+ return 0 if report.failed == 0 else 1
599
+
600
+
601
+ _STARTER_WORKFLOW_YML = """\
602
+ name: SelfHeal Drift Check
603
+
604
+ on:
605
+ push:
606
+ branches: [main]
607
+ pull_request:
608
+
609
+ jobs:
610
+ drift-check:
611
+ runs-on: ubuntu-latest
612
+ steps:
613
+ - uses: actions/checkout@v4
614
+ - uses: actions/setup-python@v5
615
+ with:
616
+ python-version: "3.12"
617
+ - name: Install dependencies
618
+ run: |
619
+ python -m pip install --upgrade pip
620
+ pip install -e ".[dev]"
621
+ - name: Run selfheal doctor
622
+ run: selfheal doctor --json
623
+ - name: Run pytest
624
+ run: pytest -v
625
+ """
626
+
627
+
628
+ def _cmd_init(args: argparse.Namespace) -> int:
629
+ """Scaffold starter selfheal configuration and GitHub Actions workflow."""
630
+ base_dir = Path(args.dir)
631
+ starter_config: dict[str, Any] = {
632
+ "host": "0.0.0.0",
633
+ "port": 8080,
634
+ "db_path": "selfheal.db",
635
+ "model_specs": ["path/to/models.py:ModelName"],
636
+ }
637
+ templates: tuple[tuple[str, str], ...] = (
638
+ ("selfheal.config.json", json.dumps(starter_config, indent=2) + "\n"),
639
+ (".github/workflows/selfheal.yml", _STARTER_WORKFLOW_YML),
640
+ )
641
+
642
+ created: list[str] = []
643
+ skipped: list[str] = []
644
+ for rel_path, content in templates:
645
+ target = base_dir / rel_path
646
+ if target.exists() and not args.force:
647
+ skipped.append(rel_path)
648
+ continue
649
+ _atomic_write(target, content)
650
+ created.append(rel_path)
651
+
652
+ print(json.dumps({"created": created, "skipped": skipped}, indent=2))
653
+ return 0
654
+
655
+
656
+ def _http_json(
657
+ method: str, url: str, body: dict[str, Any] | None = None, token: str | None = None
658
+ ) -> tuple[int, dict[str, Any]]:
659
+ """Minimal JSON HTTP client (stdlib only, consistent with zero-dep posture)."""
660
+ data = json.dumps(body).encode("utf-8") if body is not None else None
661
+ headers = {"Content-Type": "application/json", "Accept": "application/json"}
662
+ if token:
663
+ headers["Authorization"] = f"Bearer {token}"
664
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
665
+ try:
666
+ with urllib.request.urlopen(req, timeout=15.0) as resp:
667
+ raw = resp.read().decode("utf-8")
668
+ return resp.status, json.loads(raw) if raw else {}
669
+ except urllib.error.HTTPError as exc:
670
+ raw = exc.read().decode("utf-8")
671
+ try:
672
+ payload: dict[str, Any] = json.loads(raw) if raw else {}
673
+ except json.JSONDecodeError:
674
+ payload = {"error": raw[:200]}
675
+ return exc.code, payload
676
+
677
+
678
+ def _cmd_models_init(args: argparse.Namespace) -> int:
679
+ """Generate a Pydantic or Zod model from user-supplied JSON payload samples."""
680
+ payload_path = Path(args.payload)
681
+ try:
682
+ samples = load_payload_samples(payload_path)
683
+ except (FileNotFoundError, ValueError, json.JSONDecodeError, OSError) as exc:
684
+ print(f"error: {exc}", file=sys.stderr)
685
+ return 2
686
+
687
+ model_name = args.name or payload_path.stem
688
+ if not model_name.isidentifier():
689
+ model_name = "".join(
690
+ c if c.isalnum() or c == "_" else "_" for c in model_name
691
+ ).strip("_") or "GeneratedModel"
692
+ if model_name[0].isdigit():
693
+ model_name = "M" + model_name
694
+ if model_name != args.name:
695
+ model_name = model_name[:1].upper() + model_name[1:]
696
+
697
+ root = infer_object_schema(samples)
698
+ if args.format == "zod":
699
+ output = emit_zod(model_name, root)
700
+ else:
701
+ output = emit_pydantic(model_name, root)
702
+
703
+ if args.out is not None:
704
+ _atomic_write(Path(args.out), output)
705
+ print(f"wrote {args.out}", file=sys.stderr)
706
+ else:
707
+ print(output.rstrip("\n"))
708
+ return 0
709
+
710
+
711
+ def _cmd_connect(args: argparse.Namespace) -> int:
712
+ """Exchange an install token for an org API key and persist org settings."""
713
+ server = (args.server or os.environ.get("SELFHEAL_API_BASE_URL") or "").strip()
714
+ server = server or "http://127.0.0.1:8080"
715
+ server = server.rstrip("/")
716
+
717
+ status, payload = _http_json(
718
+ "POST", f"{server}/connect/exchange", {"install_token": args.token}
719
+ )
720
+ if status != 200:
721
+ detail = payload.get("error", f"HTTP {status}")
722
+ print(f"error: connect exchange failed: {detail}", file=sys.stderr)
723
+ return 1
724
+ org_id = str(payload.get("org_id") or "")
725
+ api_key = str(payload.get("api_key") or "")
726
+ if not org_id or not api_key:
727
+ print("error: malformed exchange response", file=sys.stderr)
728
+ return 1
729
+
730
+ vstatus, _ = _http_json("GET", f"{server}/connect/verify", token=api_key)
731
+ if vstatus != 200:
732
+ print("error: post-connect verify failed; key may be invalid", file=sys.stderr)
733
+ return 1
734
+
735
+ config_path = Path(args.config)
736
+ existing: dict[str, Any] = {}
737
+ if config_path.is_file():
738
+ try:
739
+ loaded = json.loads(config_path.read_text(encoding="utf-8"))
740
+ if isinstance(loaded, dict):
741
+ existing = loaded
742
+ except (json.JSONDecodeError, OSError):
743
+ existing = {}
744
+ org_cfg = existing.get("org")
745
+ if not isinstance(org_cfg, dict):
746
+ org_cfg = {}
747
+ org_cfg["org_id"] = org_id
748
+ org_cfg["api_base_url"] = server
749
+ existing["org"] = org_cfg
750
+ _atomic_write(config_path, json.dumps(existing, indent=2) + "\n")
751
+
752
+ print(f"Connected org '{org_id}' to {server}")
753
+ print(f"Wrote org settings to {config_path}")
754
+ print()
755
+ print("Org API key (shown once — store it now):")
756
+ print(f" {api_key}")
757
+ print()
758
+ print("Export it for SelfHeal commands:")
759
+ print(f" export SELFHEAL_API_KEY='{api_key}'")
760
+ print(" export SELFHEAL_API_BASE_URL='" + server + "'")
761
+ return 0
762
+
763
+
764
+ def _cmd_schema(args: argparse.Namespace) -> int:
765
+ """Emit JSON Schema, OpenAPI 3.1, or Zod preprocessor for a Pydantic model."""
766
+ try:
767
+ _, model_cls = _load_model_from_spec(args.model)
768
+ except (FileNotFoundError, ValueError, ImportError, OSError) as exc:
769
+ print(f"error: {exc}", file=sys.stderr)
770
+ return 2
771
+
772
+ empty_plan = PatchPlan(model_name=model_cls.__name__, actions=())
773
+ if args.format == "jsonschema":
774
+ output = json.dumps(model_cls.model_json_schema(), indent=2) + "\n"
775
+ elif args.format == "openapi":
776
+ spec = emit_openapi_schema_patch(model_cls, empty_plan)
777
+ doc = emit_openapi_document([spec])
778
+ output = json.dumps(doc, indent=2) + "\n"
779
+ else:
780
+ output = synthesize_zod_preprocessor(empty_plan)
781
+
782
+ if args.out is not None:
783
+ _atomic_write(Path(args.out), output)
784
+ else:
785
+ print(output.rstrip("\n"))
786
+ return 0
787
+
788
+
789
+ def main(argv: Sequence[str] | None = None) -> int:
790
+ parser = build_parser()
791
+ args = parser.parse_args(argv)
792
+
793
+ if args.command == "doctor":
794
+ return _cmd_doctor(args)
795
+ if args.command == "replay":
796
+ return _cmd_replay(args)
797
+ if args.command == "init":
798
+ return _cmd_init(args)
799
+ if args.command == "schema":
800
+ return _cmd_schema(args)
801
+ if args.command == "connect":
802
+ return _cmd_connect(args)
803
+ if args.command == "models":
804
+ if args.models_command == "init":
805
+ return _cmd_models_init(args)
806
+
807
+ try:
808
+ model_path, model_cls = _load_model_from_spec(args.model)
809
+ drifted_payload = _load_json_file(args.payload)
810
+ except (FileNotFoundError, ValueError, ImportError, json.JSONDecodeError) as exc:
811
+ print(f"error: {exc}", file=sys.stderr)
812
+ return 2
813
+
814
+ provider: SchemaMappingProvider | None = (
815
+ AnthropicSchemaMappingProvider() if args.llm_fallback else None
816
+ )
817
+ report = detect_drift(model_cls, drifted_payload, mapping_provider=provider)
818
+
819
+ if args.command == "check":
820
+ print(report.model_dump_json(indent=2))
821
+ return 1 if report.has_drift else 0
822
+
823
+ canonical_payload: dict[str, Any] | None = None
824
+ if args.canonical is not None:
825
+ try:
826
+ canonical_payload = _load_json_file(args.canonical)
827
+ except (FileNotFoundError, ValueError, json.JSONDecodeError) as exc:
828
+ print(f"error: {exc}", file=sys.stderr)
829
+ return 2
830
+
831
+ if not report.has_drift:
832
+ return 0
833
+
834
+ model_snapshot = _FileSnapshot.capture(model_path)
835
+ source_code = (model_snapshot.raw_bytes or b"").decode("utf-8")
836
+ patch_result = synthesize_patch(source_code, report, root_model=model_cls)
837
+ if patch_result.patched_source == source_code:
838
+ return 0
839
+
840
+ verification = verify_patch(patch_result, drifted_payload, canonical_payload)
841
+ if not verification.passed:
842
+ print(f"verification gate failed: {verification.error_detail}", file=sys.stderr)
843
+ return 1
844
+
845
+ mypy_ok, mypy_detail = _run_mypy_shadow_gate(model_path, patch_result.patched_source)
846
+ if not mypy_ok:
847
+ print(f"mypy --strict gate failed:\n{mypy_detail}", file=sys.stderr)
848
+ return 1
849
+
850
+ pytest_args = shlex.split(args.pytest_args) if args.pytest_args else []
851
+ keep_written = False
852
+ _atomic_write(model_path, patch_result.patched_source, mode=model_snapshot.mode)
853
+ try:
854
+ pytest_ok, pytest_detail = _run_pytest_gate(pytest_args)
855
+ if not pytest_ok:
856
+ print(f"pytest gate failed:\n{pytest_detail}", file=sys.stderr)
857
+ return 1
858
+ keep_written = bool(args.write or args.open_pr)
859
+ finally:
860
+ if not keep_written:
861
+ model_snapshot.restore()
862
+
863
+ if args.diff:
864
+ diff_lines = difflib.unified_diff(
865
+ source_code.splitlines(keepends=True),
866
+ patch_result.patched_source.splitlines(keepends=True),
867
+ fromfile=f"a/{model_path.name}",
868
+ tofile=f"b/{model_path.name}",
869
+ )
870
+ sys.stdout.write("".join(diff_lines))
871
+
872
+ zod_path: Path | None = None
873
+ zod_snapshot: _FileSnapshot | None = None
874
+ if args.zod is not None:
875
+ zod_path = Path(args.zod)
876
+ zod_snapshot = _FileSnapshot.capture(zod_path)
877
+ zod_code = synthesize_zod_preprocessor(patch_result.plan)
878
+ _atomic_write(zod_path, zod_code, mode=zod_snapshot.mode)
879
+
880
+ openapi_path: Path | None = None
881
+ openapi_snapshot: _FileSnapshot | None = None
882
+ if args.openapi is not None:
883
+ openapi_path = Path(args.openapi)
884
+ openapi_snapshot = _FileSnapshot.capture(openapi_path)
885
+ spec = emit_openapi_schema_patch(model_cls, patch_result.plan)
886
+ doc = emit_openapi_document([spec])
887
+ _atomic_write(
888
+ openapi_path, json.dumps(doc, indent=2) + "\n", mode=openapi_snapshot.mode
889
+ )
890
+
891
+ if args.open_pr:
892
+ fp = compute_drift_fingerprint(report)
893
+ branch = args.branch or f"selfheal/{model_cls.__name__.lower()}-{fp[:8]}"
894
+ orig_branch: str | None = None
895
+ try:
896
+ rev_proc = subprocess.run(
897
+ ["git", "rev-parse", "--abbrev-ref", "HEAD"],
898
+ capture_output=True,
899
+ text=True,
900
+ check=False,
901
+ timeout=15,
902
+ )
903
+ if rev_proc.returncode == 0:
904
+ candidate = rev_proc.stdout.strip()
905
+ if candidate and candidate != "HEAD":
906
+ orig_branch = candidate
907
+ except (OSError, subprocess.TimeoutExpired):
908
+ orig_branch = None
909
+
910
+ try:
911
+ _open_github_pr(
912
+ model_path,
913
+ zod_path,
914
+ branch,
915
+ model_cls.__name__,
916
+ fp,
917
+ openapi_path=openapi_path,
918
+ )
919
+ except (
920
+ subprocess.CalledProcessError,
921
+ subprocess.TimeoutExpired,
922
+ OSError,
923
+ RuntimeError,
924
+ ) as exc:
925
+ if not args.write:
926
+ if orig_branch is not None:
927
+ try:
928
+ chk = subprocess.run(
929
+ ["git", "checkout", orig_branch],
930
+ check=False,
931
+ capture_output=True,
932
+ text=True,
933
+ timeout=15,
934
+ )
935
+ if chk.returncode != 0:
936
+ print(
937
+ f"warning: failed to restore branch {orig_branch}: "
938
+ f"{chk.stderr.strip()}",
939
+ file=sys.stderr,
940
+ )
941
+ except (OSError, subprocess.TimeoutExpired) as chk_exc:
942
+ print(
943
+ f"warning: failed to restore branch {orig_branch}: {chk_exc}",
944
+ file=sys.stderr,
945
+ )
946
+ model_snapshot.restore()
947
+ if zod_snapshot is not None:
948
+ zod_snapshot.restore()
949
+ if openapi_snapshot is not None:
950
+ openapi_snapshot.restore()
951
+ print(f"pr creation failed: {exc}", file=sys.stderr)
952
+ return 2
953
+
954
+ return 0
955
+
956
+
957
+ if __name__ == "__main__":
958
+ raise SystemExit(main())