okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-020-ci' into f-020-int76e51103c

main
6.0 KiB129 linesraw
1#!/usr/bin/env python3
2"""Check source CLI dispatch without optional terminal or harness packages.
3
4This runs Python with -S against a loopback telemetry fixture. It checks lazy
5client dispatch and early serving failure, not an actual engine or installation.
6"""
7
8from __future__ import annotations
9
10import argparse
11import json
12import os
13import platform
14import subprocess
15import sys
16import tempfile
17import threading
18from pathlib import Path
19
20from portable_monitor_smoke import _server
21
22
23ROOT = Path(__file__).resolve().parents[1]
24
25
26def _run(*args: str) -> subprocess.CompletedProcess[str]:
27    env = os.environ.copy()
28    env.pop("PYTHONPATH", None)
29    env.pop("PYTHONHOME", None)
30    env["PYTHONNOUSERSITE"] = "1"
31    return subprocess.run([sys.executable, "-S", *args], cwd=ROOT, env=env,
32                          capture_output=True, text=True, timeout=20, check=False)
33
34
35def _record(result: subprocess.CompletedProcess[str], expected_exit: int) -> dict:
36    if result.returncode != expected_exit or result.stderr.strip():
37        raise RuntimeError(f"CLI exit {result.returncode}, stderr {result.stderr.strip()!r}")
38    try:
39        value = json.loads(result.stdout)
40    except json.JSONDecodeError as exc:
41        raise RuntimeError("CLI did not write exactly one JSON record") from exc
42    if not isinstance(value, dict) or value.get("schema_version") != 1:
43        raise RuntimeError("CLI JSON schema was missing")
44    return value
45
46
47def smoke() -> dict:
48    probe = _run("-c", "import importlib.util,json,sys; print(json.dumps({"
49                 "'no_site':sys.flags.no_site,'rich':importlib.util.find_spec('rich') is not None,"
50                 "'textual':importlib.util.find_spec('textual') is not None}))")
51    if probe.returncode or probe.stderr.strip():
52        raise RuntimeError("could not establish the no-site-packages test environment")
53    extras = json.loads(probe.stdout)
54    if extras != {"no_site": 1, "rich": False, "textual": False}:
55        raise RuntimeError("optional terminal packages are visible in the test environment")
56
57    help_result = _run(str(ROOT / "strata.py"), "--help")
58    if (help_result.returncode or help_result.stderr.strip() or
59            not all(word in help_result.stdout for word in ("serve", "monitor", "code"))):
60        raise RuntimeError("source CLI help failed without optional packages")
61
62    server, paths, _ = _server()
63    thread = threading.Thread(target=server.serve_forever, daemon=True)
64    thread.start()
65    try:
66        url = f"http://127.0.0.1:{server.server_address[1]}"
67        status = _record(_run(str(ROOT / "strata.py"), "status", "--url", url, "--json"), 0)
68        once = _record(_run(str(ROOT / "strata.py"), "monitor", "--url", url,
69                            "--once", "--output", "json"), 0)
70        for value in (status, once):
71            if (value.get("ok") is not True or
72                    (value.get("snapshot", {}).get("instance") or {}).get("id") != "portable-smoke" or
73                    (value.get("snapshot", {}).get("model") or {}).get("id") != "portable-smoke-model"):
74                raise RuntimeError("one-shot CLI showed the wrong telemetry fixture")
75        if paths != ["GET /v1/telemetry", "GET /v1/telemetry"]:
76            raise RuntimeError("one-shot commands sent unexpected HTTP requests")
77    finally:
78        server.shutdown()
79        server.server_close()
80        thread.join(timeout=2)
81
82    with tempfile.TemporaryDirectory(prefix="strata-minimal-cli-") as directory:
83        missing = str(Path(directory) / "missing-config.json")
84        # serve needs the API server's packages; without them strata.py stops in its
85        # preflight (exit 5, a plain message, nothing installed) before reading the config.
86        serve = _run(str(ROOT / "strata.py"), "serve", "--profile", missing,
87                     "--offline", "--output", "jsonl")
88        if (serve.returncode != 5 or serve.stdout.strip() or
89                "missing packages the API server needs" not in serve.stderr or
90                "never install anything" not in serve.stderr):
91            raise RuntimeError(f"serve without server packages did not stop in the preflight: "
92                               f"exit {serve.returncode}, stderr {serve.stderr.strip()!r}")
93        code = _record(_run(str(ROOT / "strata.py"), "code", "run", "--prompt-file",
94                            str(Path(directory) / "missing-prompt.txt"), "--policy", "review",
95                            "--output", "jsonl"), 5)
96        if (code.get("ok") is not False or
97                (code.get("error") or {}).get("code") != 5 or
98                "harness component" not in (code.get("error") or {}).get("message", "")):
99            raise RuntimeError("missing harness did not return actionable exit 5")
100
101    return {"schema_version": 1, "scope": "source_cli_without_site_packages",
102            "platform": platform.platform(), "python": platform.python_version(),
103            "optional_packages_visible": {"rich": False, "textual": False},
104            "commands": ["--help", "status --json", "monitor --once --output json",
105                         "serve --offline --output jsonl (server packages absent: preflight exit 5)",
106                         "code run --output jsonl (missing harness)"],
107            "telemetry_gets": len(paths), "non_gets": 0,
108            "actual_engine_started": False, "passed": True}
109
110
111def main() -> int:
112    parser = argparse.ArgumentParser(description=__doc__)
113    parser.add_argument("--report", type=Path, required=True, help="new absolute JSON report path")
114    args = parser.parse_args()
115    report = args.report.expanduser()
116    if not report.is_absolute() or report.exists():
117        parser.error("--report must be an absolute new file")
118    result = smoke()
119    report.parent.mkdir(parents=True, exist_ok=True)
120    descriptor = os.open(report, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
121    with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
122        json.dump(result, stream, indent=2)
123        stream.write("\n")
124    print(json.dumps({"report": str(report), "passed": result["passed"]}))
125    return 0
126
127
128if __name__ == "__main__":
129    raise SystemExit(main())