File size: 12,260 Bytes
e1f5446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python3
"""Prepare one corpus repository for LocalSandbox validation and write bootstrap.json.

Replaces Repo2RLEnv's Docker-based `ensure_bootstrap` (bootstrap/runner.py line 471
requires a daemon). Produces the same BootstrapResult shape that
bootstrap/cache.py line 117 loads.

Steps
  1. sandbox checkout: `git clone --shared` of the local mirror, detached at the pinned SHA
  2. `.venv` inside the checkout (excluded by the stage script's `git clean -e .venv`)
  3. install: editable package + test extras + requirements files + pytest
  4. verify: pytest collection, then a bounded full run
  5. write bootstrap.json, requirements.lock, report.json

Usage:
  bootstrap_repo.py --repo owner/name --sha <pinned> [--python 3.12] [--extra-pkg X ...]
                    [--install-cmd "<shell>"] [--test-cmd "python -m pytest"] [--suite-timeout 1200]
Exit code 0 even when verification fails; read report.json / the printed summary.
"""

from __future__ import annotations

import argparse
import configparser
import json
import os
import re
import shutil
import subprocess
import sys
import time
import tomllib
from pathlib import Path

A = Path("/Users/beneecs/work/projects/openrsi/code/assets")
REQ_FILE_CANDIDATES = [
    "requirements-dev.txt",
    "requirements_dev.txt",
    "dev-requirements.txt",
    "requirements-test.txt",
    "requirements_test.txt",
    "test-requirements.txt",
    "test_requirements.txt",
    "requirements/dev.txt",
    "requirements/test.txt",
    "requirements/tests.txt",
    "requirements/testing.txt",
    "tests/requirements.txt",
]
EXTRA_KEYS = ("test", "tests", "testing", "dev", "develop", "development")


def sh(cmd: str, *, cwd: Path, env: dict, timeout: int) -> tuple[int, str, float]:
    t = time.monotonic()
    try:
        p = subprocess.run(
            ["bash", "-lc", cmd], cwd=str(cwd), env=env, capture_output=True, text=True,
            errors="replace", timeout=timeout, check=False,
        )
        return p.returncode, (p.stdout + "\n--- stderr ---\n" + p.stderr), time.monotonic() - t
    except subprocess.TimeoutExpired as exc:
        out = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
        return 124, out + f"\n[timeout after {timeout}s]", time.monotonic() - t


def requires_python(repo: Path) -> str | None:
    py = repo / "pyproject.toml"
    if py.exists():
        try:
            d = tomllib.loads(py.read_text())
            rp = d.get("project", {}).get("requires-python")
            if rp:
                return rp
            poetry = d.get("tool", {}).get("poetry", {}).get("dependencies", {}).get("python")
            if poetry:
                return str(poetry)
        except Exception:
            pass
    cfg = repo / "setup.cfg"
    if cfg.exists():
        cp = configparser.ConfigParser()
        try:
            cp.read(cfg)
            if cp.has_option("options", "python_requires"):
                return cp.get("options", "python_requires")
        except Exception:
            pass
    sp = repo / "setup.py"
    if sp.exists():
        m = re.search(r"python_requires\s*=\s*['\"]([^'\"]+)['\"]", sp.read_text(errors="replace"))
        if m:
            return m.group(1)
    return None


def choose_python(spec: str | None, preferred: str) -> str:
    if not spec:
        return preferred
    try:
        from packaging.specifiers import SpecifierSet
        from packaging.version import Version
    except ImportError:
        return preferred
    try:
        ss = SpecifierSet(spec.replace("^", ">="))
    except Exception:
        return preferred
    for cand in [preferred, "3.12", "3.11", "3.10", "3.9"]:
        if ss.contains(Version(cand + ".0"), prereleases=True) or ss.contains(Version(cand + ".99")):
            return cand
    return preferred


def discover_extras(repo: Path) -> tuple[list[str], list[str], list[str]]:
    """Return (extras, requirement files, poetry dev packages)."""
    extras: list[str] = []
    poetry_dev: list[str] = []
    py = repo / "pyproject.toml"
    if py.exists():
        try:
            d = tomllib.loads(py.read_text())
            opt = d.get("project", {}).get("optional-dependencies", {})
            extras += [k for k in opt if k.lower() in EXTRA_KEYS]
            groups = d.get("tool", {}).get("poetry", {}).get("group", {})
            for g, body in groups.items():
                if g.lower() in EXTRA_KEYS:
                    poetry_dev += list(body.get("dependencies", {}).keys())
            legacy = d.get("tool", {}).get("poetry", {}).get("dev-dependencies", {})
            poetry_dev += list(legacy.keys())
            pdm = d.get("tool", {}).get("pdm", {}).get("dev-dependencies", {})
            for g, deps in pdm.items():
                if g.lower() in EXTRA_KEYS:
                    poetry_dev += [re.split(r"[<>=!~\[ ;]", x)[0] for x in deps]
            dg = d.get("dependency-groups", {})
            for g, deps in dg.items():
                if g.lower() in EXTRA_KEYS:
                    poetry_dev += [re.split(r"[<>=!~\[ ;]", x)[0] for x in deps if isinstance(x, str)]
        except Exception:
            pass
    cfg = repo / "setup.cfg"
    if cfg.exists():
        cp = configparser.ConfigParser()
        try:
            cp.read(cfg)
            if cp.has_section("options.extras_require"):
                extras += [k for k in cp.options("options.extras_require") if k.lower() in EXTRA_KEYS]
        except Exception:
            pass
    reqs = [r for r in REQ_FILE_CANDIDATES if (repo / r).exists()]
    poetry_dev = [p for p in dict.fromkeys(poetry_dev) if p.lower() != "python"]
    return list(dict.fromkeys(extras)), reqs, poetry_dev


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--repo", required=True)
    ap.add_argument("--sha", required=True)
    ap.add_argument("--python", default="3.12")
    ap.add_argument("--extra-pkg", action="append", default=[])
    ap.add_argument("--install-cmd", action="append", default=[], help="extra shell after base install")
    ap.add_argument("--test-cmd", default="python -m pytest")
    ap.add_argument("--suite-timeout", type=int, default=1200)
    ap.add_argument("--skip-suite", action="store_true")
    ap.add_argument("--force", action="store_true", help="recreate sandbox and venv")
    args = ap.parse_args()

    key = args.repo.replace("/", "__")
    mirror = A / "repos" / key
    sandbox = A / "sandboxes" / key
    home = A / "sandboxes" / f".home-{key}"
    bdir = A / "bootstrap" / key
    bdir.mkdir(parents=True, exist_ok=True)
    home.mkdir(parents=True, exist_ok=True)
    log: list[dict] = []
    t_start = time.monotonic()

    if not (mirror / ".git").exists():
        print(json.dumps({"repo": args.repo, "status": "no_mirror"}))
        return 0

    if args.force and sandbox.exists():
        shutil.rmtree(sandbox)
    if not (sandbox / ".git").exists():
        sandbox.parent.mkdir(parents=True, exist_ok=True)
        subprocess.run(["git", "clone", "-q", "--shared", "--no-checkout", f"file://{mirror}", str(sandbox)], check=True)
    subprocess.run(["git", "-C", str(sandbox), "checkout", "-q", "--detach", args.sha], check=True)
    subprocess.run(["git", "-C", str(sandbox), "clean", "-fdxq", "-e", ".venv"], check=False)

    rp = requires_python(sandbox)
    pyver = choose_python(rp, args.python)
    venv = sandbox / ".venv"
    env = {
        "PATH": f"{venv}/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
        "HOME": str(home), "VIRTUAL_ENV": str(venv), "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8",
        "PYTHONDONTWRITEBYTECODE": "1", "PIP_DISABLE_PIP_VERSION_CHECK": "1",
        "UV_CACHE_DIR": str(A / ".uv-cache"), "UV_PYTHON_INSTALL_DIR": str(A / ".uv-python"),
        "GIT_TERMINAL_PROMPT": "0",
    }

    def step(name: str, cmd: str, timeout: int = 900) -> int:
        rc, out, dt = sh(cmd, cwd=sandbox, env=env, timeout=timeout)
        log.append({"step": name, "cmd": cmd, "rc": rc, "sec": round(dt, 1), "tail": out[-3000:]})
        return rc

    if args.force or not (venv / "bin" / "python").exists():
        if venv.exists():
            shutil.rmtree(venv)
        step("venv", f"uv venv -q --python {pyver} .venv", 300)

    extras, reqs, poetry_dev = discover_extras(sandbox)
    install_cmds: list[str] = []
    pip = "uv pip install -q --python .venv/bin/python"
    base = f"{pip} -e ."
    if extras:
        base = f"{pip} -e '.[{','.join(extras)}]'"
    install_cmds.append(base)
    for r in reqs:
        install_cmds.append(f"{pip} -r {r}")
    if poetry_dev:
        install_cmds.append(f"{pip} {' '.join(repr(p) for p in poetry_dev)}")
    install_cmds.append(f"{pip} pytest")
    for extra in args.extra_pkg:
        install_cmds.append(f"{pip} {extra}")
    install_cmds += args.install_cmd

    install_ok = True
    for i, cmd in enumerate(install_cmds):
        rc = step(f"install_{i}", cmd, 900)
        if rc != 0 and cmd == base:
            # Fall back to a plain editable install if extras are broken.
            rc = step(f"install_{i}_fallback", f"{pip} -e .", 900)
        if rc != 0 and cmd in (base, f"{pip} pytest"):
            install_ok = False

    collect_ok = step("collect", "python -m pytest -q --co -p no:cacheprovider 2>&1 | tail -5", 600) == 0
    collected = None
    if log[-1]["tail"]:
        m = re.search(r"(\d+) tests? collected", log[-1]["tail"]) or re.search(r"(\d+)/(\d+) tests collected", log[-1]["tail"])
        if m:
            collected = int(m.group(1))

    suite = {"ran": False}
    if not args.skip_suite:
        rc = step("suite", f"{args.test_cmd} -q -p no:cacheprovider -x --maxfail=50 2>&1 | tail -15", args.suite_timeout)
        tail = log[-1]["tail"]
        passed = re.search(r"(\d+) passed", tail)
        failed = re.search(r"(\d+) failed", tail)
        errors = re.search(r"(\d+) errors?", tail)
        suite = {
            "ran": True, "rc": rc, "sec": log[-1]["sec"],
            "passed": int(passed.group(1)) if passed else 0,
            "failed": int(failed.group(1)) if failed else 0,
            "errors": int(errors.group(1)) if errors else 0,
        }

    step("freeze", "uv pip freeze --python .venv/bin/python > ../../bootstrap/" + key + "/requirements.lock", 120)
    step("clean", "git reset -q --hard HEAD && git clean -fdxq -e .venv", 120)

    pyv = subprocess.run([str(venv / "bin" / "python"), "-c", "import sys;print('.'.join(map(str,sys.version_info[:3])))"], capture_output=True, text=True).stdout.strip()
    smoke = install_ok and collect_ok and (not suite.get("ran") or suite.get("passed", 0) > 0)
    bootstrap = {
        "image_digest": f"local-venv:{key}",
        "image_tag": f"local/{key}",
        "language": "python",
        "repo": args.repo,
        "ref": args.sha,
        "rebuild_cmds": ["python -m pip install --no-deps --no-build-isolation -e ."],
        "test_cmds": [args.test_cmd],
        "smoke_passed": bool(smoke),
        "iterations": 0,
        "build_time_sec": round(time.monotonic() - t_start, 1),
        "llm_provider": "none",
        "llm_cost_estimate_usd": 0.0,
        "dockerfile_reconstruction": "",
        "transcript_path": None,
        "pushed_to_registry": False,
        "verify_passed": bool(smoke),
        "verify_detail": f"python {pyv}; collected={collected}; suite={suite}",
        "extra": {
            "python_version": pyv,
            "requires_python": rp,
            "install_cmds": install_cmds,
            "extras": extras,
            "requirement_files": reqs,
            "poetry_dev": poetry_dev,
            "collected": collected,
            "suite": suite,
            "sandbox_layout": "checkout with .venv inside; LocalSandbox adapter",
        },
    }
    (bdir / "bootstrap.json").write_text(json.dumps(bootstrap, indent=2))
    (bdir / "report.json").write_text(json.dumps({"log": log}, indent=2))
    print(json.dumps({
        "repo": args.repo, "python": pyv, "install_ok": install_ok, "collect_ok": collect_ok,
        "collected": collected, "suite": suite, "smoke_passed": smoke,
        "extras": extras, "reqs": reqs, "poetry_dev": poetry_dev[:8],
    }))
    return 0


if __name__ == "__main__":
    sys.exit(main())