Repository navigation
Expand file tree
/
Copy pathqualify_runtime_artifact.py
More file actions
189 lines (179 loc) · 10.4 KB
/
Copy pathqualify_runtime_artifact.py
File metadata and controls
189 lines (179 loc) · 10.4 KB
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
#!/usr/bin/env python3
"""Install and upgrade a runtime archive in a disposable, isolated environment."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import subprocess
import shutil
import sys
import tempfile
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from loopx.cli_commands.update_artifact import (
extract_artifact,
file_hash,
validate_default_contract,
validate_published_manifest,
)
def observe_default_contract(source: Path) -> dict:
"""Observe the candidate's real default writer in an isolated release fixture.
No model runs, active Goal or saved operator configuration participates.
Probe the ordinary invocation, with inline transport for direct schema inspection.
"""
source = source.resolve()
with tempfile.TemporaryDirectory(prefix="loopx-default-contract-") as raw:
scratch = Path(raw).resolve()
env = {key: value for key, value in os.environ.items()
if not key.startswith("LOOPX_") and key not in {
"CODEX_HOME", "CODEX_THREAD_ID", "CODEX_SESSION_ID", "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR"}}
env.update(PYTHONPATH=str(source), TMPDIR=str(scratch), TEMP=str(scratch), TMP=str(scratch),
CODEX_HOME=str(scratch / "home/codex"))
result = subprocess.run([sys.executable, "-c", r'''
import json, subprocess, sys
from pathlib import Path
import loopx
if Path(loopx.__file__).resolve().parents[1] != Path(sys.argv[2]):
raise ValueError("Default contract probe imported another source")
from loopx.control_plane.effect_runtime import restart_effect_runtime
from loopx.control_plane.testing.terminal_settlement_tool_behavior import (
_build_fixture, TERMINAL_SETTLEMENT_FIXTURE_GOAL_ID, TERMINAL_SETTLEMENT_FIXTURE_AGENT_ID)
try:
fixture = _build_fixture(Path(sys.argv[1]))
result = subprocess.run([sys.executable, "-m", "loopx.entrypoint", "--format", "json",
"--registry", str(fixture.global_registry_path), "--runtime-root", str(fixture.runtime_root),
"quota", "should-run", "--goal-id", TERMINAL_SETTLEMENT_FIXTURE_GOAL_ID,
"--agent-id", TERMINAL_SETTLEMENT_FIXTURE_AGENT_ID, "--context-delivery", "off"],
cwd=fixture.project_root, capture_output=True, text=True, encoding="utf-8", timeout=60, check=True)
payload = json.loads(result.stdout)
if payload.get("ok") is not True or payload.get("goal_id") != TERMINAL_SETTLEMENT_FIXTURE_GOAL_ID:
raise ValueError("Default writer probe did not return its original Goal")
schema = payload.get("schema_version")
print(json.dumps({"surface": "complete_turn" if schema == "loopx_turn_envelope_v1" else "quota_packet",
"schema_version": schema,
"interaction_schema_version": payload.get("interaction_contract", {}).get("schema_version")}))
finally:
restart_effect_runtime(wait_for_exit=True)
''', str(scratch / "fixture"), str(source)], cwd=source, env=env, capture_output=True,
text=True, encoding="utf-8", timeout=120)
if result.returncode:
raise ValueError("Runtime default contract could not be qualified through its isolated CLI")
return json.loads(result.stdout)
def qualify(directory: Path) -> dict:
manifest = validate_published_manifest(json.loads((directory / "loopx-runtime.json").read_text()))
archive = directory / f"loopx-runtime-{manifest['source_revision']}.tar.gz"
assert archive.stat().st_size == manifest["size"] and file_hash(archive) == manifest["sha256"]
with tempfile.TemporaryDirectory(prefix="loopx-runtime-qualification-") as raw:
scratch = Path(raw)
source = scratch / "source"
source.mkdir()
extract_artifact(archive, source)
env = dict(os.environ)
# No developer's runtime, home, skills or host config may participate.
for key in tuple(env):
if key.startswith("LOOPX_") or key in {"CODEX_HOME", "PYTHONPATH", "GIT_DIR", "GIT_WORK_TREE"}:
env.pop(key)
env.update(HOME=str(scratch / "home"), CODEX_HOME=str(scratch / "home/codex"),
XDG_CONFIG_HOME=str(scratch / "home/config"), XDG_DATA_HOME=str(scratch / "home/data"),
XDG_CACHE_HOME=str(scratch / "home/cache"), XDG_STATE_HOME=str(scratch / "home/state"),
LOOPX_BIN_DIR=str(scratch / "bin"), LOOPX_RELEASES_DIR=str(scratch / "releases"),
LOOPX_MAN_ROOT=str(scratch / "man"), LOOPX_SKILLS_DIR=str(scratch / "skills"),
LOOPX_REGISTRY=str(scratch / "registry.json"), LOOPX_RUNTIME_ROOT=str(scratch / "runtime"),
LOOPX_INSTALL_CANARY="0", LOOPX_PROMOTE_DEFAULT="1", LOOPX_PREBUILT_RUNTIME="1",
LOOPX_INSTALL_SLASH_COMMANDS="0", LOOPX_INSTALL_REVALIDATE_EXTENSIONS="0",
LOOPX_RESOLVED_SOURCE_GIT_COMMIT=manifest["source_revision"], LOOPX_REF=manifest["channel"],
LOOPX_PYTHON=sys.executable, LOOPX_USAGE_PING="0", LOOPX_UPDATE_EVENTS="1")
(scratch / "home").mkdir()
tools = scratch / "tools"
tools.mkdir()
for name in ("npm", "npx"):
command = tools / name
command.write_text("#!/bin/sh\necho 'Frontend build tools must not run during runtime installation' >&2\nexit 91\n")
command.chmod(0o755)
env["PATH"] = str(tools) + os.pathsep + env.get("PATH", "")
results = []
for _ in range(2):
result = subprocess.run(["bash", str(source / "scripts/install-local.sh")], env=env,
text=True, capture_output=True, timeout=180)
if result.returncode:
raise RuntimeError("Isolated runtime install failed:\n" + result.stdout[-4000:] + result.stderr[-4000:])
results.append(result.returncode)
cli = scratch / "bin/loopx"
def read(*args):
result = subprocess.run([str(cli), "--format", "json", *args], env=env,
text=True, capture_output=True, timeout=60, check=True)
return json.loads(result.stdout)
doctor = read("doctor", "--installation-only")
skills = read("workflow-skills", "--skills-dir", str(scratch / "skills"))
if not doctor.get("ok") or not skills.get("ok"):
raise RuntimeError("Installed runtime/skills readback failed")
release = cli.resolve().parents[1]
default_contract = validate_default_contract(observe_default_contract(release))
if manifest.get("default_contract") != default_contract:
raise ValueError("Observed runtime default contract does not match the candidate")
for name in ("LICENSE", "NOTICE", "LICENSE-MIT"):
assert (release / name).read_bytes() == (source / name).read_bytes()
source_record = json.loads((release / "release.json").read_text())["source"]
assert source_record["git_commit"] == manifest["source_revision"]
assert source_record["ref"] == manifest["channel"]
# Every preserved skill reference and TS input is supplied by the same
# committed archive; validate the exact Chat bundle through its owner.
subprocess.run([sys.executable, str(release / "scripts/chat_bundle.py"), "verify", "--source"],
env=env, check=True, stdout=subprocess.DEVNULL)
bundle = json.loads((release / "loopx/web/chat/bundle-manifest.json").read_text())
assert bundle["source_revision"] == manifest["source_revision"]
# Exercise the installed delivery owner, not a development file server.
subprocess.run([sys.executable, "-c", """
import hashlib
import json
import threading
from urllib.request import urlopen
from loopx.chat_server import ChatHTTPServer, ChatRequestHandler, default_chat_assets_dir
assets = default_chat_assets_dir()
manifest = json.loads((assets / 'bundle-manifest.json').read_text())
server = ChatHTTPServer(('127.0.0.1', 0), ChatRequestHandler)
server.assets_dir, server.verbose = assets, False
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
for name, digest in manifest['files'].items():
with urlopen(f'http://127.0.0.1:{server.server_port}/chat/{name}', timeout=10) as response:
assert response.status == 200
assert hashlib.sha256(response.read()).hexdigest() == digest, name
finally:
server.shutdown()
server.server_close()
worker.join()
"""], env={**env, "PYTHONPATH": str(release)}, cwd=release,
check=True, timeout=60, stdout=subprocess.DEVNULL)
# Inject a post-switch executable failure at the manpage chmod step.
# Only a disposable candidate is touched, never a real installation.
real_chmod = shutil.which("chmod")
failing_chmod = tools / "chmod"
failing_chmod.write_text(f"#!{sys.executable}\n" +
"import os,subprocess,sys\nfrom pathlib import Path\n" +
f"subprocess.run([{real_chmod!r}, *sys.argv[1:]], check=True)\n" +
"if sys.argv[1] == '0644':\n" +
" entry = Path(os.environ['LOOPX_BIN_DIR']) / 'loopx'\n" +
" entry.resolve().chmod(0o644)\n")
failing_chmod.chmod(0o755)
failed = subprocess.run(["bash", str(source / "scripts/install-local.sh")], env=env,
text=True, capture_output=True, timeout=180)
if failed.returncode == 0 or cli.resolve().parents[1] != release:
raise RuntimeError("Activation failure did not preserve the previous executable: " + failed.stderr[-3000:])
assert read("doctor", "--installation-only")["ok"]
subprocess.run([sys.executable, "-c",
"from loopx.control_plane.effect_runtime import restart_effect_runtime; "
"restart_effect_runtime(wait_for_exit=True)"],
env={**env, "PYTHONPATH": str(release)}, cwd=release,
check=True, timeout=15, stdout=subprocess.DEVNULL)
return {"ok": True, "source_revision": manifest["source_revision"], "bytes": manifest["size"],
"default_contract": default_contract,
"channel": manifest["channel"], "sha256": manifest["sha256"],
"clean_install": results[0] == 0, "upgrade": results[1] == 0,
"doctor": True, "skills": True, "frontend_bundle_contract": True, "frontend_http": True,
"no_frontend_build_tools": True, "license_notices": True, "activation_failure_restored": True}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", type=Path)
print(json.dumps(qualify(parser.parse_args().directory)))