| 1 | #!/usr/bin/env python3 |
| 2 | """Thin v1 staging: build, deploy equipo-staging, run the staging runner |
| 3 | unit on this machine with the real Claude CLI, and run the headless suite. |
| 4 | |
| 5 | scripts/staging-thin.py build # instance (linux/arm64) + runner (linux/amd64) for HEAD |
| 6 | scripts/staging-thin.py release # the restage, in order: idle check, runners, then the instance |
| 7 | scripts/staging-thin.py deploy # env + carlos deploy --swap hold, wait for the version |
| 8 | scripts/staging-thin.py signin # owner and suite sign-in by logged mail, suite device bearer |
| 9 | scripts/staging-thin.py runner # both runner units: config, enrolment, start |
| 10 | scripts/staging-thin.py suite [scenario,...] |
| 11 | scripts/staging-thin.py stop # stop both staging runner units |
| 12 | scripts/staging-thin.py cleanup-suite-runners # one-off: remove stale suite people and their runners |
| 13 | |
| 14 | Two people use staging. The owner (the claude-a binding's person) chats |
| 15 | there and has the owner's runner unit, which stays running. The headless |
| 16 | suite signs in as its own owner (SUITE, added by the owner's session) with |
| 17 | its own runner unit, so the suite never writes into the owner's |
| 18 | conversation. Only the owner's runner may create repositories. The |
| 19 | suite's runner reads the production runner's forge credential file in |
| 20 | place for the repositories it advertises. The owner's runner has its own |
| 21 | agent-wide file, amadan.json under the staging root, made at each install |
| 22 | from the same agent bearer and git PAT: it merges into every repository |
| 23 | the hub lets the agent reach, including the ones it creates for jobs. |
| 24 | Production's file is never changed. |
| 25 | |
| 26 | Only equipo-staging in Oficina on the flagship console, and only the |
| 27 | staging runner units, are ever touched. Cookies, bearers and sign-in links |
| 28 | are kept in 0600 files under the staging root and never printed. |
| 29 | """ |
| 30 | from contextlib import contextmanager |
| 31 | import fcntl |
| 32 | import hashlib |
| 33 | import html |
| 34 | import http.cookiejar |
| 35 | import json |
| 36 | import os |
| 37 | from pathlib import Path |
| 38 | import re |
| 39 | import secrets |
| 40 | import shlex |
| 41 | import shutil |
| 42 | import subprocess |
| 43 | import sys |
| 44 | import time |
| 45 | import tempfile |
| 46 | import urllib.parse |
| 47 | import urllib.request |
| 48 | |
| 49 | APP, ACCOUNT, CONSOLE = 'equipo-staging', 'bds', 'https://console.carloku.com' |
| 50 | HOST = 'equipo-staging.bds.oncarlos.com' |
| 51 | ORIGIN = 'https://' + HOST |
| 52 | UNIT = 'equipo-runner-staging.service' |
| 53 | ROOT = Path.home() / '.local/share/equipo-runner-staging' |
| 54 | SUITE = 'suite@equipo-staging.invalid' |
| 55 | SUITE_UNIT = 'equipo-runner-staging-suite.service' |
| 56 | SUITE_ROOT = ROOT / 'suite' |
| 57 | PROD_ENV = Path.home() / '.local/share/equipo-runner/service.env' |
| 58 | REPO = Path(__file__).resolve().parent.parent |
| 59 | MARKER = '# equipo staging runner (thin v1)' |
| 60 | # Base's origins whose Assistant hosts this instance accepts (PUT |
| 61 | # /api/v1/assistant/host): staging Base, and where it moves under oficina.works. |
| 62 | ASSISTANT_HOSTS = 'https://base.bds.oncarlos.com,https://base.oficina.works' |
| 63 | |
| 64 | |
| 65 | def run(args, *, env=None, timeout=900, check=True, quiet=False, log=None): |
| 66 | """With log, the whole output is kept there (redacted, 0600) and a |
| 67 | failure reports go test's failed tests (failures) and the log's path |
| 68 | instead of the output's last 2000 characters.""" |
| 69 | result = subprocess.run(args, cwd=REPO, env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout) |
| 70 | if log is not None: |
| 71 | private(log, redact(result.stdout)) |
| 72 | if check and result.returncode: |
| 73 | # Never echo argv: secrets set takes a value in it. |
| 74 | what = f'{Path(args[0]).name} {args[1] if len(args) > 1 else ""} failed ({result.returncode})' |
| 75 | if log is not None: |
| 76 | raise RuntimeError(f'{what}; full output in {log}\n{redact(failures(result.stdout))}') |
| 77 | raise RuntimeError(f'{what}: {redact(result.stdout)[-2000:]}') |
| 78 | if not quiet: |
| 79 | print(redact(result.stdout), end='', flush=True) |
| 80 | return result.stdout |
| 81 | |
| 82 | |
| 83 | FAILURE_TAIL = 8192 |
| 84 | |
| 85 | |
| 86 | def failures(output): |
| 87 | """Each failed test's own lines from go test -v output, the last |
| 88 | FAILURE_TAIL characters of each, then any panic (a test timeout is |
| 89 | one). go test -v names the test a line belongs to with === RUN, CONT |
| 90 | and NAME; a test's --- FAIL line follows its lines. Failed scenarios |
| 91 | come before their parent test's own lines.""" |
| 92 | lines, current, kept, panic = {}, None, [], None |
| 93 | for line in output.splitlines(): |
| 94 | if panic is not None: |
| 95 | panic.append(line) |
| 96 | continue |
| 97 | m = re.match(r'^=== (RUN|CONT|NAME)\s+(\S+)', line) |
| 98 | if m: |
| 99 | current = m.group(2) |
| 100 | lines.setdefault(current, []) |
| 101 | continue |
| 102 | m = re.match(r'^\s*--- FAIL: (\S+) ', line) |
| 103 | if m: |
| 104 | own = '\n'.join(lines.get(m.group(1), [])) |
| 105 | if len(own) > FAILURE_TAIL: |
| 106 | own = '...' + own[-FAILURE_TAIL:] |
| 107 | kept.append((m.group(1), line.strip() + ('\n' + own if own else ''))) |
| 108 | current = None |
| 109 | continue |
| 110 | if line.startswith('panic: '): |
| 111 | panic = [line] |
| 112 | continue |
| 113 | if re.match(r'^\s*--- (PASS|SKIP): ', line): |
| 114 | current = None |
| 115 | elif current is not None: |
| 116 | lines[current].append(line) |
| 117 | names = [name for name, _ in kept] |
| 118 | parents = lambda name: any(other.startswith(name + '/') for other in names) |
| 119 | out = [text for name, text in kept if not parents(name)] + [text for name, text in kept if parents(name)] |
| 120 | if panic is not None: |
| 121 | out.append('\n'.join(panic)[:FAILURE_TAIL]) |
| 122 | return '\n'.join(out) if out else '(no failed test named; see the log)' |
| 123 | |
| 124 | |
| 125 | def redact(text): |
| 126 | text = re.sub(r'https?://[^\s"\\]+/auth/(verify|callback)\?[^\s"\\]+', '[sign-in link redacted]', text) |
| 127 | return re.sub(r'equipo\.person\.v1\.[A-Za-z0-9_-]+', '[bearer redacted]', text) |
| 128 | |
| 129 | |
| 130 | def carlos(verb, *args, quiet=False): |
| 131 | return run(['carlos', *verb.split(), '--app', APP, '--account', ACCOUNT, '--console', CONSOLE, *args], quiet=quiet) |
| 132 | |
| 133 | |
| 134 | def private(path, text): |
| 135 | path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 136 | fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) |
| 137 | with os.fdopen(fd, 'w') as f: |
| 138 | f.write(text) |
| 139 | os.chmod(path, 0o600) |
| 140 | |
| 141 | |
| 142 | def head(): |
| 143 | sha = run(['git', 'rev-parse', '--short', 'HEAD'], quiet=True).strip() |
| 144 | if run(['git', 'status', '--porcelain', '--untracked-files=no'], quiet=True).strip(): |
| 145 | raise RuntimeError('commit first: staging runs exact commits') |
| 146 | return sha |
| 147 | |
| 148 | |
| 149 | def read_env(path): |
| 150 | out = {} |
| 151 | for line in path.read_text().splitlines(): |
| 152 | if '=' in line and not line.startswith('#'): |
| 153 | k, v = line.split('=', 1) |
| 154 | out[k] = shlex.split(v)[0] |
| 155 | return out |
| 156 | |
| 157 | |
| 158 | def claude_a(): |
| 159 | bindings = json.loads(Path(read_env(PROD_ENV)['EQUIPO_ACCOUNT_BINDINGS_PATH']).read_text()) |
| 160 | chosen = [b for b in bindings if b.get('local_id') == 'claude-a' and b.get('provider') == 'claude' and b.get('account_id') == 'paul@tito.io' and b.get('expected_identity', {}).get('provider_version') == '2.1.312'] |
| 161 | if len(chosen) != 1: |
| 162 | raise RuntimeError('need exactly one claude-a / paul@tito.io / 2.1.312 binding') |
| 163 | return chosen[0] |
| 164 | |
| 165 | |
| 166 | def sha256(path): |
| 167 | return hashlib.sha256(Path(path).read_bytes()).hexdigest() |
| 168 | |
| 169 | |
| 170 | def overlaps(a, b): |
| 171 | a, b = Path(a).resolve(), Path(b).resolve() |
| 172 | return a == b or a in b.parents or b in a.parents |
| 173 | |
| 174 | |
| 175 | def refuse_shared_roots(): |
| 176 | """Staging and production runners never share state, scratch or workspace roots.""" |
| 177 | prod = read_env(PROD_ENV) |
| 178 | for key in ('EQUIPO_RUNNER_STATE_DIR', 'EQUIPO_WORKSPACE_ROOT', 'EQUIPO_SCRATCH_ROOT'): |
| 179 | theirs = prod.get(key) |
| 180 | if not theirs: |
| 181 | raise RuntimeError('production runner config lacks ' + key) |
| 182 | for root in (ROOT, SUITE_ROOT): |
| 183 | for mine in ('state', 'work', 'scratch', 'sessions'): |
| 184 | if overlaps(theirs, root / mine): |
| 185 | raise RuntimeError(f'staging {mine} overlaps the production runner {key}') |
| 186 | for mine in ('state', 'work', 'scratch', 'sessions'): |
| 187 | if overlaps(ROOT / mine, SUITE_ROOT / mine): |
| 188 | raise RuntimeError(f'the two staging runners share {mine}') |
| 189 | |
| 190 | |
| 191 | def build(): |
| 192 | """The exact `make release` artifacts production would receive.""" |
| 193 | sha = head() |
| 194 | source = read_env(PROD_ENV) |
| 195 | # The release check pins the installed provider binaries; their paths |
| 196 | # come from the runner configuration (paths only, no credentials). |
| 197 | env = dict(os.environ, **{k: v for k, v in source.items() if k in { |
| 198 | 'EQUIPO_CLAUDE_PATH', 'EQUIPO_CODEX_PATH', 'EQUIPO_CODEX_CODE_MODE_HOST_PATH', 'EQUIPO_BWRAP_PATH'}}) |
| 199 | run(['make', 'release'], env=env, timeout=1800) |
| 200 | release = REPO / 'releases' / f'equipo-runner-linux-amd64-{sha}' |
| 201 | runner = ROOT / 'releases' / sha |
| 202 | runner.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 203 | # The preview scanner sits beside the runner, which looks for it there. |
| 204 | for name in ('equipo-runner', 'equipo-tool-proxy', 'gitleaks'): |
| 205 | shutil.copy2(release / name, runner / name) |
| 206 | provenance(sha) |
| 207 | # The page renderer as users get it: published on the forge under the |
| 208 | # tag linked into the runner (scripts/publish-renderer.sh publish). |
| 209 | # Downloaded in full, without credentials (never a HEAD: the forge |
| 210 | # counts a redirect as a download), and required to be the release's |
| 211 | # bytes, which provenance just held to the build. A release whose |
| 212 | # renderer is not published stops here, before staging installs |
| 213 | # anything, so production cannot ship without it. |
| 214 | published = runner / 'published-renderer' |
| 215 | run(['scripts/publish-renderer.sh', 'check', str(release), str(published)], timeout=2400) |
| 216 | # Unpacked by the staged runner from that download and held to the pin |
| 217 | # linked into it (both staging runners use it); verify-installed |
| 218 | # renders a page with it. |
| 219 | run([str(runner / 'equipo-runner'), 'install-renderer', str(published / 'renderer.tar.gz')]) |
| 220 | print(f'built {sha}: {instance_binary(sha)} and {runner}') |
| 221 | return sha |
| 222 | |
| 223 | |
| 224 | def provenance(sha): |
| 225 | """The digests the release build recorded, after checking that the |
| 226 | release artifacts, and staging's copies of the runner, tool proxy and |
| 227 | preview scanner, are still those bytes. Nothing is deployed or |
| 228 | installed without it.""" |
| 229 | run(['python3', 'scripts/staged-artifacts.py', 'verify', sha]) |
| 230 | made = json.loads((REPO / 'releases' / f'equipo-linux-arm64-{sha}.manifest.json').read_text())['sha256'] |
| 231 | for name, key in (('equipo-runner', 'runner'), ('equipo-tool-proxy', 'tool_proxy'), ('gitleaks', 'gitleaks')): |
| 232 | path = ROOT / 'releases' / sha / name |
| 233 | if not path.is_file() or sha256(path) != made[key]: |
| 234 | raise RuntimeError(f'staging holds another {name} than the {sha} release built') |
| 235 | return made |
| 236 | |
| 237 | |
| 238 | def instance_binary(sha): |
| 239 | return REPO / 'releases' / f'equipo-linux-arm64-{sha}' |
| 240 | |
| 241 | |
| 242 | def home_config(): |
| 243 | home = json.loads((ROOT / 'home-config.json').read_text()) |
| 244 | if (not isinstance(home, dict) or |
| 245 | set(home) != {'EQUIPO_HOME_ISSUER', 'EQUIPO_HOME_CONSUMER_ID', |
| 246 | 'EQUIPO_HOME_KEYS_BASE64', 'EQUIPO_HOME_DEK_BASE64'} or |
| 247 | home['EQUIPO_HOME_ISSUER'] != 'https://oficina-id-staging.bds.oncarlos.com' or |
| 248 | home['EQUIPO_HOME_CONSUMER_ID'] != 'equipo-staging' or |
| 249 | not all(isinstance(value, str) and value for value in home.values())): |
| 250 | raise RuntimeError('invalid staging home configuration') |
| 251 | return home |
| 252 | |
| 253 | |
| 254 | def set_home_config(home): |
| 255 | try: |
| 256 | result = subprocess.run(['carlos', 'env', 'set', '--app', APP, '--account', ACCOUNT, |
| 257 | '--console', CONSOLE, '--no-prompt', |
| 258 | *(name + '=' + value for name, value in home.items())], |
| 259 | cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, |
| 260 | timeout=60) |
| 261 | except (OSError, subprocess.TimeoutExpired): |
| 262 | raise RuntimeError('could not set staging home configuration') from None |
| 263 | if result.returncode: |
| 264 | raise RuntimeError('could not set staging home configuration') |
| 265 | |
| 266 | |
| 267 | def deploy(home=None): |
| 268 | home = home_config() if home is None else home |
| 269 | sha = head() |
| 270 | binary = instance_binary(sha) |
| 271 | if not binary.exists(): |
| 272 | raise RuntimeError('build first') |
| 273 | if sha256(binary) != provenance(sha)['instance']: |
| 274 | raise RuntimeError(f'the instance is not the one the {sha} release built') |
| 275 | if 'EQUIPO_INSTANCE_KEY' not in carlos('secrets list', quiet=True): |
| 276 | carlos('secrets set', 'EQUIPO_INSTANCE_KEY=' + secrets.token_urlsafe(48), quiet=True) # gitleaks:allow (generated, never stored in source) |
| 277 | owner = claude_a()['person_id'] |
| 278 | backup() |
| 279 | # The suite person (SUITE, *.invalid) is a test identity: its tasks |
| 280 | # are listed only to itself and never paired with anyone's as a |
| 281 | # duplicate. The thin core has no teams within an instance to move it |
| 282 | # into, so it is hidden instead (UX1-PROGRESS.md). |
| 283 | carlos('env set', '--no-prompt', 'EQUIPO_ORIGIN=' + ORIGIN, 'EQUIPO_OWNERS=' + owner, |
| 284 | 'EQUIPO_EXECUTION_ENABLED=1', 'EQUIPO_EXECUTION_MARKER_PATH=/data/instances/' + HOST + '/execution/witness', |
| 285 | 'EQUIPO_ALLOW_LOGGED_MAIL=1', 'EQUIPO_TEST_PEOPLE=.invalid', |
| 286 | 'EQUIPO_ASSISTANT_HOSTS=' + ASSISTANT_HOSTS) |
| 287 | set_home_config(home) |
| 288 | carlos('deploy', '--target', 'linux-arm64', '--swap', 'hold', '--version', sha, '--timeout', '5m', '--no-prompt', str(binary)) |
| 289 | deadline = time.monotonic() + 120 |
| 290 | while True: |
| 291 | try: |
| 292 | with urllib.request.urlopen(ORIGIN + '/api/version', timeout=15) as r: |
| 293 | if r.read().decode().strip() == sha: |
| 294 | private(ROOT / 'deployed.json', json.dumps({'version': sha, 'instance_sha256': sha256(binary)})) |
| 295 | print('serving', sha) |
| 296 | return |
| 297 | except (OSError, ValueError): |
| 298 | pass |
| 299 | if time.monotonic() > deadline: |
| 300 | raise RuntimeError('staging does not report ' + sha) |
| 301 | time.sleep(2) |
| 302 | |
| 303 | |
| 304 | def backup(): |
| 305 | """A copy of staging's database before every deploy (a release may |
| 306 | change data on start: it combines duplicate tasks), kept 0600 under |
| 307 | the staging root; the newest five are kept.""" |
| 308 | folder = ROOT / 'backups' |
| 309 | folder.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 310 | out = folder / ('equipo-' + time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '.db') |
| 311 | carlos('db pull', '--out', str(out), quiet=True) |
| 312 | os.chmod(out, 0o600) |
| 313 | for old in sorted(folder.glob('equipo-*.db'))[:-5]: |
| 314 | old.unlink() |
| 315 | print('backed up', out) |
| 316 | |
| 317 | |
| 318 | class FormParser: |
| 319 | """Reads the inputs of the first form posting to action.""" |
| 320 | def __init__(self, page, action): |
| 321 | m = re.search(r'<form[^>]*action="' + re.escape(action) + r'"[^>]*>(.*?)</form>', page, re.S) |
| 322 | if not m: |
| 323 | raise RuntimeError('no form for ' + action) |
| 324 | self.fields = {} |
| 325 | for tag in re.findall(r'<input[^>]*>', m.group(1)): |
| 326 | name = re.search(r'name="([^"]*)"', tag) |
| 327 | value = re.search(r'value="([^"]*)"', tag) |
| 328 | if name: |
| 329 | self.fields[html.unescape(name.group(1))] = html.unescape(value.group(1)) if value else '' |
| 330 | |
| 331 | |
| 332 | def logged_mail(): |
| 333 | return run(['carlos', 'logs', '--app', APP, '--account', ACCOUNT, '--console', CONSOLE, '--grep', 'NOT SENT', '--since', '10m', '-n', '50'], quiet=True) |
| 334 | |
| 335 | |
| 336 | def signin_links(logs, address, before): |
| 337 | """Sign-in links logged for address, oldest first, minus those in before.""" |
| 338 | found = [l for l in re.findall(r'[^\n]*' + re.escape(ORIGIN) + r'/auth/(?:verify|callback)\?[^\s"\\]+[^\n]*', logs) |
| 339 | if address in l or urllib.parse.quote(address) in l] |
| 340 | links = [re.search(re.escape(ORIGIN) + r'/auth/(?:verify|callback)\?[^\s"\\]+', l).group() for l in found] |
| 341 | return [l for l in links if l not in before] |
| 342 | |
| 343 | |
| 344 | def mail_signin(address, cookie_path): |
| 345 | """Sign address in by logged mail; the session cookie goes to a 0600 file.""" |
| 346 | jar = http.cookiejar.CookieJar() |
| 347 | opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar)) |
| 348 | opener.addheaders = [('Origin', ORIGIN), ('Sec-Fetch-Site', 'same-origin')] |
| 349 | # The door's email way: with Oficina ID configured, a plain /signin |
| 350 | # offers Continue with Oficina ID first and has no email form. |
| 351 | page = opener.open(ORIGIN + '/signin?way=email', timeout=30).read().decode() |
| 352 | form = FormParser(page, '/auth/begin').fields |
| 353 | form.update(address=address, force='1') |
| 354 | # A link logged before this sign-in began was already used (by an |
| 355 | # earlier run); taking it leaves no session. |
| 356 | before = set(signin_links(logged_mail(), address, set())) |
| 357 | time.sleep(4) # the sign-in proof has a minimum age |
| 358 | opener.open(ORIGIN + '/auth/begin', urllib.parse.urlencode(form).encode(), timeout=30).read() |
| 359 | link = None |
| 360 | deadline = time.monotonic() + 120 |
| 361 | while link is None: |
| 362 | fresh = signin_links(logged_mail(), address, before) |
| 363 | if fresh: |
| 364 | link = fresh[-1] |
| 365 | elif time.monotonic() > deadline: |
| 366 | raise RuntimeError('no logged sign-in mail for ' + address) |
| 367 | else: |
| 368 | time.sleep(3) |
| 369 | page = opener.open(link, timeout=30).read().decode() |
| 370 | if 'action="/auth/verify"' in page: |
| 371 | fields = FormParser(page, '/auth/verify').fields |
| 372 | opener.open(ORIGIN + '/auth/verify', urllib.parse.urlencode(fields).encode(), timeout=30).read() |
| 373 | cookies = [c for c in jar if 'session' in c.name] |
| 374 | if not cookies: |
| 375 | raise RuntimeError('sign-in did not set a session for ' + address) |
| 376 | cookie = '; '.join(f'{c.name}={c.value}' for c in cookies) |
| 377 | private(cookie_path, cookie) |
| 378 | return cookie |
| 379 | |
| 380 | |
| 381 | def setup_test(cookie, **extra): |
| 382 | env = dict(os.environ, CGO_ENABLED='0', EQUIPO_STAGING_ORIGIN=ORIGIN, EQUIPO_STAGING_COOKIE=cookie, **extra) |
| 383 | run(['go', 'test', './internal/stagingtest', '-run', '^TestStagingSetup$', '-count=1', '-v'], env=env) |
| 384 | |
| 385 | |
| 386 | def signin(): |
| 387 | """The owner signs in (their session adds the suite's owner and approves |
| 388 | the owner's runner); the suite signs in as itself and gets the bearer.""" |
| 389 | owner = mail_signin(claude_a()['person_id'], ROOT / 'cookie') |
| 390 | setup_test(owner, EQUIPO_STAGING_ADD_OWNER=SUITE) |
| 391 | suite = mail_signin(SUITE, SUITE_ROOT / 'cookie') |
| 392 | setup_test(suite, EQUIPO_STAGING_TOKEN_FILE=str(SUITE_ROOT / 'token')) |
| 393 | print('owner and suite signed in; suite device bearer saved') |
| 394 | |
| 395 | |
| 396 | def instance_id(): |
| 397 | req = urllib.request.Request(ORIGIN + '/api/v1/me', headers={'Authorization': 'Bearer ' + (SUITE_ROOT / 'token').read_text().strip()}) |
| 398 | with urllib.request.urlopen(req, timeout=30) as r: |
| 399 | return json.load(r)['team_id'] |
| 400 | |
| 401 | |
| 402 | def deployed(): |
| 403 | with urllib.request.urlopen(ORIGIN + '/api/version', timeout=30) as r: |
| 404 | return r.read().decode().strip() |
| 405 | |
| 406 | |
| 407 | def runner(sha=None): |
| 408 | # The runners match the instance staging is serving, or, in a release, |
| 409 | # the one about to be swapped in (runners first, then the instance). |
| 410 | sha = sha or deployed() |
| 411 | release = ROOT / 'releases' / sha |
| 412 | if not (release / 'equipo-runner').exists(): |
| 413 | raise RuntimeError('build first') |
| 414 | refuse_shared_roots() |
| 415 | provenance(sha) |
| 416 | owner = claude_a()['person_id'] |
| 417 | install(sha, release, ROOT, UNIT, owner, ROOT / 'cookie', create=True) |
| 418 | install(sha, release, SUITE_ROOT, SUITE_UNIT, SUITE, SUITE_ROOT / 'cookie', create=False) |
| 419 | |
| 420 | |
| 421 | def install(sha, release, root, unit_name, person, cookie_path, create): |
| 422 | unit = Path.home() / '.config/systemd/user' / unit_name |
| 423 | if unit.exists() and MARKER not in unit.read_text(): |
| 424 | raise RuntimeError('refusing to replace an unrecognised ' + unit_name) |
| 425 | for name in ['state', 'work', 'scratch', 'sessions', 'config', 'accounts']: |
| 426 | (root / name).mkdir(parents=True, exist_ok=True, mode=0o700) |
| 427 | binding = dict(claude_a(), person_id=person) |
| 428 | private(root / 'config/bindings.json', json.dumps([binding] + added_in_app(root, person))) |
| 429 | source = read_env(PROD_ENV) |
| 430 | env = {k: v for k, v in source.items() if k in { |
| 431 | 'EQUIPO_CLAUDE_PATH', 'EQUIPO_CODEX_PATH', 'EQUIPO_CODEX_CODE_MODE_HOST_PATH', 'EQUIPO_BWRAP_PATH', |
| 432 | 'EQUIPO_GIT_PATH', 'EQUIPO_AMADAN_PATH', 'EQUIPO_GO_BINARY', 'EQUIPO_GO_ROOT', 'EQUIPO_CLAUDE_MODEL'}} |
| 433 | # Only the forge credential's repository names and the agent's reach |
| 434 | # leave the runner. The suite reads production's file in place; the |
| 435 | # owner's runner, which creates repositories, has the agent-wide one. |
| 436 | credential = source['EQUIPO_AMADAN_CREDENTIAL_PATH'] |
| 437 | if root == ROOT: |
| 438 | credential = str(agent_credential(credential)) |
| 439 | env.update(EQUIPO_ORIGIN=ORIGIN, EQUIPO_INSTANCE_ID=instance_id(), EQUIPO_MACHINE_LABEL='docs-t1 staging', |
| 440 | EQUIPO_RUNNER_STATE_DIR=str(root / 'state'), EQUIPO_WORKSPACE_ROOT=str(root / 'work'), |
| 441 | EQUIPO_SCRATCH_ROOT=str(root / 'scratch'), EQUIPO_ACCOUNT_BINDINGS_PATH=str(root / 'config/bindings.json'), |
| 442 | EQUIPO_AMADAN_CREDENTIAL_PATH=credential, |
| 443 | EQUIPO_TOOL_PROXY_PATH=str(release / 'equipo-tool-proxy'), |
| 444 | EQUIPO_ACCOUNTS_ROOT=str(root / 'accounts'), |
| 445 | EQUIPO_RUNNER_CREATE_REPOS='1' if create else '0') |
| 446 | carlos = shutil.which('carlos') or str(Path.home() / '.local/bin/carlos') |
| 447 | if root == ROOT and Path(carlos).is_file(): |
| 448 | # The owner's runner pairs with this machine's CARLOS devbox for |
| 449 | # previews (links on the tailnet); the suite's never publishes. |
| 450 | env.update(EQUIPO_PREVIEW_HOST='devbox', EQUIPO_CARLOS_PATH=carlos) |
| 451 | # It also publishes merged websites on Carloku (account oficina, |
| 452 | # channel edge), with this user's signed-in carlos, and only after |
| 453 | # the person answers the publish card. |
| 454 | env.update(EQUIPO_SITE_HOST='carloku') |
| 455 | if root == ROOT: |
| 456 | # The owner's runner has the pinned Pi (metered connections). The |
| 457 | # release's install-pi is idempotent: it returns at once when the |
| 458 | # tree under pi/ already matches its pins, and otherwise installs |
| 459 | # it and checks the digests, so a restage never leaves Pi missing. |
| 460 | run([str(release / 'equipo-runner'), 'install-pi', str(root / 'pi')]) |
| 461 | env.update(EQUIPO_PI_ROOT=str(root / 'pi')) |
| 462 | # And the pinned OpenCode (OpenCode Go connections), the same way: |
| 463 | # install-opencode keeps a tree under opencode/ that verifies |
| 464 | # against its pins and fetches nothing; otherwise it installs and |
| 465 | # checks it. The suite's runner gets neither harness. |
| 466 | run([str(release / 'equipo-runner'), 'install-opencode', str(root / 'opencode')]) |
| 467 | env.update(EQUIPO_OPENCODE_ROOT=str(root / 'opencode')) |
| 468 | private(root / 'service.env', ''.join(f'{k}={json.dumps(v)}\n' for k, v in sorted(env.items()))) |
| 469 | # Before enrolment or the unit starts anything: the runner holds every |
| 470 | # program in this configuration (bubblewrap, claude, codex and its code |
| 471 | # mode host, the tool proxy) to the digests of its release. |
| 472 | run([str(release / 'equipo-runner'), 'verify-installed'], env=dict(os.environ, **env)) |
| 473 | unit.parent.mkdir(parents=True, exist_ok=True) |
| 474 | unit.write_text(MARKER + '\n[Unit]\nDescription=Equipo staging runner\n[Service]\nType=simple\n' |
| 475 | f'EnvironmentFile={root / "service.env"}\nExecStart={release / "equipo-runner"} run\n' |
| 476 | 'Restart=on-failure\nRestartSec=5\nRestartPreventExitStatus=3\nTimeoutStopSec=45\n' |
| 477 | 'KillMode=control-group\nUMask=0077\nNoNewPrivileges=yes\n') |
| 478 | run(['systemctl', '--user', 'daemon-reload']) |
| 479 | if not (root / 'state/credentials.json').exists(): |
| 480 | # A pending enrolment for another instance is stale; start over. |
| 481 | (root / 'state/enrolment.json').unlink(missing_ok=True) |
| 482 | enrol(release, env, cookie_path) |
| 483 | private(root / 'installed.json', json.dumps({'version': sha, 'runner_sha256': sha256(release / 'equipo-runner'), |
| 484 | 'tool_proxy_sha256': sha256(release / 'equipo-tool-proxy')})) |
| 485 | run(['systemctl', '--user', 'restart', unit_name]) |
| 486 | print(unit_name, sha, 'started') |
| 487 | |
| 488 | |
| 489 | def agent_credential(source): |
| 490 | """Staging's own forge credential file: production's agent, bearer and |
| 491 | git PAT as one agent-wide entry, mode 0600. The hub decides which |
| 492 | repositories that reaches. A file of per-repository entries only lets |
| 493 | the runner merge into those repositories: a merge into one it created |
| 494 | for a job was refused before it reached the hub. Values are never |
| 495 | printed.""" |
| 496 | data = json.loads(Path(source).read_text()) |
| 497 | if data.get('api'): |
| 498 | pairs = {(data.get('api'), data.get('git'))} |
| 499 | else: |
| 500 | pairs = {(e.get('api'), e.get('git')) if isinstance(e, dict) else (e, None) |
| 501 | for e in (data.get('repositories') or {}).values()} |
| 502 | agent = data.get('agent') |
| 503 | if len(pairs) != 1 or not all(isinstance(v, str) and v for v in [agent, *next(iter(pairs))]): |
| 504 | raise RuntimeError('the production forge credential has no single agent bearer and git PAT') |
| 505 | api, git = next(iter(pairs)) |
| 506 | path = ROOT / 'amadan.json' |
| 507 | private(path, json.dumps({'agent': agent, 'api': api, 'git': git})) |
| 508 | return path |
| 509 | |
| 510 | |
| 511 | def added_in_app(root, person): |
| 512 | """Connections added in the app (Connections slice 1) live in the |
| 513 | staging root's own accounts directory and survive a restage. The |
| 514 | suite person runs on the owner's in-app Codex account the way it runs |
| 515 | on claude-a: the same home, read in place, never copied.""" |
| 516 | def kept(path, home_root): |
| 517 | try: |
| 518 | rows = json.loads(path.read_text()) |
| 519 | except (FileNotFoundError, ValueError): |
| 520 | return [] |
| 521 | return [b for b in rows if b.get('local_id') != 'claude-a' and Path(b.get('provider_home', '/')).parent == home_root] |
| 522 | own = kept(root / 'config/bindings.json', root / 'accounts') |
| 523 | if root == SUITE_ROOT: |
| 524 | owner = [dict(b, person_id=person) for b in kept(ROOT / 'config/bindings.json', ROOT / 'accounts') if b.get('provider') == 'codex'] |
| 525 | own = [b for b in own if b.get('provider') != 'codex'] + owner |
| 526 | return own |
| 527 | |
| 528 | |
| 529 | def enrol(release, env, cookie_path): |
| 530 | cookie = cookie_path.read_text().strip() |
| 531 | proc = subprocess.Popen([str(release / 'equipo-runner'), 'enrol'], env=dict(env, PATH=os.environ['PATH'], HOME=str(Path.home())), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) |
| 532 | proc.stdout.readline() |
| 533 | code = proc.stdout.readline().strip() |
| 534 | if not re.fullmatch(r'[A-Z0-9-]{4,16}', code): |
| 535 | proc.kill() |
| 536 | raise RuntimeError('enrol printed no user code: ' + redact(code)) |
| 537 | setup_test(cookie, EQUIPO_STAGING_ENROL_CODE=code) |
| 538 | if proc.wait(timeout=120) != 0: |
| 539 | raise RuntimeError('enrolment failed: ' + redact(proc.stdout.read())) |
| 540 | print('staging runner enrolled') |
| 541 | |
| 542 | |
| 543 | CANCEL_WAIT = 120 |
| 544 | |
| 545 | # A fresh suite person: suite-<run id>@equipo-staging.invalid. Only these |
| 546 | # are ever removed by the harness (never the owner or SUITE). |
| 547 | SUITE_PEOPLE = "person LIKE 'suite-%@equipo-staging.invalid'" |
| 548 | |
| 549 | |
| 550 | def suite_person(address): |
| 551 | return re.fullmatch(r'suite-[a-z0-9-]+@equipo-staging\.invalid', address) is not None |
| 552 | |
| 553 | |
| 554 | def retire_suite(person, cookie_path): |
| 555 | """Remove a run's suite person, which the harness added as an owner: |
| 556 | an inactive member has every runner it enrolled revoked. The owner's |
| 557 | session does it. A failure is said, never raised over the run's own |
| 558 | outcome; the one-off cleanup catches what is left.""" |
| 559 | if not suite_person(person): |
| 560 | raise ValueError('not a suite person') |
| 561 | try: |
| 562 | owner = mail_signin(claude_a()['person_id'], cookie_path) |
| 563 | setup_test(owner, EQUIPO_STAGING_REMOVE_SUITE=person) |
| 564 | except Exception as error: |
| 565 | print('suite retire: ' + redact(str(error)), flush=True) |
| 566 | |
| 567 | |
| 568 | def stale_suite_runners(): |
| 569 | out = carlos('db query', '--sql', "SELECT 'count=' || count(*) FROM runners WHERE revoked_at IS NULL AND " + SUITE_PEOPLE, quiet=True) |
| 570 | m = re.search(r'^count=(\d+)\s*$', out, re.M) |
| 571 | if not m: |
| 572 | raise RuntimeError('could not count the suite runners') |
| 573 | return int(m.group(1)) |
| 574 | |
| 575 | |
| 576 | def cleanup_suite_runners(): |
| 577 | """One-off, staging only: suite people whose runners are still |
| 578 | enrolled (runs before 2026-11-28 never removed them) are removed by |
| 579 | the owner, which revokes those runners. Prints counts only.""" |
| 580 | before = stale_suite_runners() |
| 581 | out = carlos('db query', '--sql', "SELECT 'persons=' || coalesce(group_concat(DISTINCT person), '') FROM runners WHERE revoked_at IS NULL AND " + SUITE_PEOPLE, quiet=True) |
| 582 | m = re.search(r'^persons=(.*)$', out, re.M) |
| 583 | if not m: |
| 584 | raise RuntimeError('could not list the suite people') |
| 585 | people = sorted({p for p in m.group(1).strip().split(',') if suite_person(p)}) |
| 586 | if people: |
| 587 | with tempfile.TemporaryDirectory(prefix='equipo-suite-', dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder: |
| 588 | owner = mail_signin(claude_a()['person_id'], Path(folder) / 'owner-cookie') |
| 589 | setup_test(owner, EQUIPO_STAGING_REMOVE_SUITE=','.join(people)) |
| 590 | after = before |
| 591 | # The database copy catches up with the instance. |
| 592 | for _ in range(10): |
| 593 | after = stale_suite_runners() |
| 594 | if after == 0 or not people: |
| 595 | break |
| 596 | time.sleep(15) |
| 597 | print(f'stale suite runners: {before} before, {after} after; suite people removed: {len(people)}', flush=True) |
| 598 | |
| 599 | |
| 600 | def cleanup_suite(token, person): |
| 601 | def request(path, method='GET'): |
| 602 | req = urllib.request.Request(ORIGIN + '/api/v1' + path, method=method, |
| 603 | headers={'Authorization': 'Bearer ' + token, |
| 604 | 'Idempotency-Key': secrets.token_hex(16)}) |
| 605 | with urllib.request.urlopen(req, timeout=30) as response: |
| 606 | return json.load(response) |
| 607 | try: |
| 608 | tasks = request('/tasks')['items'] |
| 609 | except Exception as error: |
| 610 | print('suite cleanup: ' + redact(str(error)), flush=True) |
| 611 | return |
| 612 | cancelled = set() |
| 613 | for task in tasks: |
| 614 | if task['creator'] != person or task['stage'] in ('done', 'cancelled'): |
| 615 | continue |
| 616 | try: |
| 617 | request('/tasks/' + urllib.parse.quote(task['id'], safe='') + '/cancel', 'POST') |
| 618 | cancelled.add(task['id']) |
| 619 | except Exception as error: |
| 620 | print('suite cleanup ' + task['id'] + ': ' + redact(str(error)), flush=True) |
| 621 | # A running step ends only when its runner confirms termination, and |
| 622 | # the suite runner is stopped and its state deleted straight after |
| 623 | # this. Wait for the confirmations, or the steps stay in flight forever. |
| 624 | deadline = time.monotonic() + CANCEL_WAIT |
| 625 | while cancelled: |
| 626 | try: |
| 627 | ended = {t['id'] for t in request('/tasks')['items'] if t['stage'] in ('done', 'cancelled')} |
| 628 | except Exception as error: |
| 629 | print('suite cleanup: ' + redact(str(error)), flush=True) |
| 630 | ended = set() |
| 631 | cancelled -= ended |
| 632 | if not cancelled: |
| 633 | break |
| 634 | if time.monotonic() >= deadline: |
| 635 | print('suite cleanup: still stopping ' + ', '.join(sorted(cancelled)), flush=True) |
| 636 | break |
| 637 | time.sleep(2) |
| 638 | |
| 639 | |
| 640 | @contextmanager |
| 641 | def fresh_suite(): |
| 642 | run_id = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()).lower() + '-' + secrets.token_hex(6) |
| 643 | person = 'suite-' + run_id + '@equipo-staging.invalid' |
| 644 | bindings = SUITE_ROOT / 'config/bindings.json' |
| 645 | original_bindings = json.loads(bindings.read_text()) |
| 646 | service = SUITE_ROOT / 'service.env' |
| 647 | original_service = service.read_text() |
| 648 | env = read_env(service) |
| 649 | # Reuse the installed binary, but enrol fresh state for this person. |
| 650 | active = run(['systemctl', '--user', 'is-active', SUITE_UNIT], check=False, quiet=True).strip() == 'active' |
| 651 | with tempfile.TemporaryDirectory(prefix='equipo-suite-', dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder: |
| 652 | root = Path(folder) |
| 653 | owner = mail_signin(claude_a()['person_id'], root / 'owner-cookie') |
| 654 | setup_test(owner, EQUIPO_STAGING_ADD_OWNER=person) |
| 655 | cookie = mail_signin(person, root / 'cookie') |
| 656 | setup_test(cookie, EQUIPO_STAGING_TOKEN_FILE=str(root / 'token')) |
| 657 | token = (root / 'token').read_text().strip() |
| 658 | for key, directory in (('EQUIPO_RUNNER_STATE_DIR', 'state'), |
| 659 | ('EQUIPO_WORKSPACE_ROOT', 'work'), |
| 660 | ('EQUIPO_SCRATCH_ROOT', 'scratch'), |
| 661 | ('EQUIPO_ACCOUNTS_ROOT', 'accounts')): |
| 662 | (root / directory).mkdir(mode=0o700) |
| 663 | env[key] = str(root / directory) |
| 664 | env['EQUIPO_ACCOUNT_BINDINGS_PATH'] = str(root / 'bindings.json') |
| 665 | env['EQUIPO_RUNNER_CREATE_REPOS'] = '0' |
| 666 | private(root / 'bindings.json', json.dumps([dict(b, person_id=person) for b in original_bindings])) |
| 667 | enrol(Path(env['EQUIPO_TOOL_PROXY_PATH']).parent, env, root / 'cookie') |
| 668 | try: |
| 669 | run(['systemctl', '--user', 'stop', SUITE_UNIT]) |
| 670 | private(service, ''.join(f'{k}={json.dumps(v)}\n' for k, v in sorted(env.items()))) |
| 671 | run(['systemctl', '--user', 'start', SUITE_UNIT]) |
| 672 | print('suite run ' + run_id + ' as ' + person, flush=True) |
| 673 | yield run_id, token |
| 674 | finally: |
| 675 | try: |
| 676 | cleanup_suite(token, person) |
| 677 | finally: |
| 678 | run(['systemctl', '--user', 'stop', SUITE_UNIT]) |
| 679 | private(service, original_service) |
| 680 | # Its runner enrolment goes with the person, so suite |
| 681 | # runners never pile up on staging. |
| 682 | retire_suite(person, root / 'owner-cookie') |
| 683 | if active: |
| 684 | run(['systemctl', '--user', 'start', SUITE_UNIT]) |
| 685 | |
| 686 | |
| 687 | def suite(only=''): |
| 688 | with fresh_suite() as (run_id, token): |
| 689 | suite_run(only, run_id, token) |
| 690 | |
| 691 | |
| 692 | def suite_run(only, run_id, token): |
| 693 | restart = f'carlos restart --app {APP} --account {ACCOUNT} --console {CONSOLE}' |
| 694 | env = dict(os.environ, CGO_ENABLED='0', EQUIPO_STAGING_ORIGIN=ORIGIN, EQUIPO_STAGING_TOKEN=token, |
| 695 | EQUIPO_STAGING_RUNNER_START=f'systemctl --user start {SUITE_UNIT}', |
| 696 | EQUIPO_STAGING_RUNNER_STOP=f'systemctl --user stop {SUITE_UNIT}', |
| 697 | EQUIPO_STAGING_RUNNER_RESTART=f'systemctl --user restart {SUITE_UNIT}', |
| 698 | # A real crash: SIGKILL to the runner process only; its |
| 699 | # namespaces die with it. The unit restarts on failure. |
| 700 | EQUIPO_STAGING_RUNNER_KILL=f'systemctl --user kill --kill-whom=main --signal=SIGKILL {SUITE_UNIT} && sleep 1', |
| 701 | EQUIPO_STAGING_INSTANCE_RESTART=restart, |
| 702 | # Observed 11-17 turns on 2026-11-19; allow retries and headroom. |
| 703 | EQUIPO_STAGING_TURN_LIMIT=os.environ.get('EQUIPO_STAGING_TURN_LIMIT', '30'), |
| 704 | EQUIPO_STAGING_RUN_ID=run_id, |
| 705 | EQUIPO_STAGING_SCENARIOS=only, |
| 706 | EQUIPO_STAGING_PROJECT=os.environ.get('EQUIPO_STAGING_PROJECT', 'oficina/equipo'), |
| 707 | # What the person says in the live Engineering scenarios: a |
| 708 | # real bug in a repository the agent reaches; the step pushes |
| 709 | # its own branch and nothing merges. |
| 710 | EQUIPO_STAGING_WITNESS=os.environ.get('EQUIPO_STAGING_WITNESS', 'Bug in oficina/equipo: README.md never links to the API reference, so device developers cannot find it. Add one line to the README pointing to docs/api/equipo-v1.md. Change only README.md.'), |
| 711 | # The step crash and the step cancel each ask for their own |
| 712 | # small, true change, so no two of a run's tasks read alike |
| 713 | # (similar tasks are combined). The cancelled one never pushes. |
| 714 | EQUIPO_STAGING_CRASH_WITNESS=os.environ.get('EQUIPO_STAGING_CRASH_WITNESS', 'Bug in oficina/equipo: docs/plan-3-acceptance.md has no title; its first line is the copy marker. Add the line "# Plan 3 acceptance" above that marker and keep the marker as it is. Change only docs/plan-3-acceptance.md.'), |
| 715 | EQUIPO_STAGING_CANCEL_WITNESS=os.environ.get('EQUIPO_STAGING_CANCEL_WITNESS', 'Bug in oficina/equipo: docs/mac-runner.md has no list of its sections, so a person cannot see the steps and the troubleshooting at a glance. Add a short list of all its section headings, as they are when you start, after the opening paragraphs. Change only docs/mac-runner.md.'), |
| 716 | # Slice 4: tasks already pushed that the upgrade judges (no |
| 717 | # new message), and what the person says in the live review |
| 718 | # and checks scenario. |
| 719 | EQUIPO_STAGING_REVIEW_TASKS=os.environ.get('EQUIPO_STAGING_REVIEW_TASKS', ''), |
| 720 | EQUIPO_STAGING_REVIEW_WITNESS=os.environ.get('EQUIPO_STAGING_REVIEW_WITNESS', ''), |
| 721 | # Slice 4c: what the person says in the live merge witness |
| 722 | # (a repository whose own checks pass; Equipo merges it). |
| 723 | EQUIPO_STAGING_MERGE_WITNESS=os.environ.get('EQUIPO_STAGING_MERGE_WITNESS', ''), |
| 724 | # Connections slice 1: what the suite person says in the live |
| 725 | # coordinator turn that should run on Codex (claude-a limited). |
| 726 | EQUIPO_STAGING_CONN_WITNESS=os.environ.get('EQUIPO_STAGING_CONN_WITNESS', ''), |
| 727 | EQUIPO_HEADLESS_REPORT=str(ROOT / 'report.json')) |
| 728 | report = ROOT / 'report.json' |
| 729 | report.unlink(missing_ok=True) |
| 730 | try: |
| 731 | # The whole output stays under the staging root: a failure reports |
| 732 | # each failed scenario's own lines and this path. |
| 733 | run(['go', 'test', './internal/headless', '-run', '^TestStaging$', '-count=1', '-v', '-timeout', '90m'], env=env, timeout=5600, |
| 734 | log=ROOT / 'suite-logs' / (run_id + '.log')) |
| 735 | finally: |
| 736 | if report.exists(): |
| 737 | print(report.read_text(), flush=True) |
| 738 | json.loads(report.read_text()) # A missing or malformed report never records. |
| 739 | if not only: |
| 740 | record_running() |
| 741 | |
| 742 | |
| 743 | def record_running(): |
| 744 | """Record what staging actually ran: the deployed instance and the |
| 745 | installed, running runners and tool proxy, each checked again now.""" |
| 746 | sha = deployed() |
| 747 | deployed_rec = json.loads((ROOT / 'deployed.json').read_text()) |
| 748 | release = ROOT / 'releases' / sha |
| 749 | for root, unit in ((ROOT, UNIT), (SUITE_ROOT, SUITE_UNIT)): |
| 750 | installed = json.loads((root / 'installed.json').read_text()) |
| 751 | if deployed_rec['version'] != sha or installed['version'] != sha: |
| 752 | raise RuntimeError('staging is not serving the deployed and installed version') |
| 753 | if sha256(release / 'equipo-runner') != installed['runner_sha256'] or sha256(release / 'equipo-tool-proxy') != installed['tool_proxy_sha256']: |
| 754 | raise RuntimeError('installed runner files changed since install') |
| 755 | if unit == SUITE_UNIT: |
| 756 | # The suite's crash scenario may leave it restarting; start it. |
| 757 | run(['systemctl', '--user', 'start', unit]) |
| 758 | time.sleep(2) |
| 759 | pid = run(['systemctl', '--user', 'show', '-p', 'MainPID', '--value', unit], quiet=True).strip() |
| 760 | if not pid.isdigit() or pid == '0' or sha256(f'/proc/{pid}/exe') != installed['runner_sha256']: |
| 761 | raise RuntimeError(f'the running {unit} is not the installed one') |
| 762 | env = read_env(root / 'service.env') |
| 763 | if Path(env['EQUIPO_TOOL_PROXY_PATH']) != release / 'equipo-tool-proxy': |
| 764 | raise RuntimeError(f'{unit} uses another tool proxy') |
| 765 | run(['python3', 'scripts/staged-artifacts.py', 'record', sha, '--instance', deployed_rec['instance_sha256'], |
| 766 | '--runner', installed['runner_sha256'], '--tool-proxy', installed['tool_proxy_sha256']]) |
| 767 | |
| 768 | |
| 769 | def stop(): |
| 770 | for unit in (UNIT, SUITE_UNIT): |
| 771 | run(['systemctl', '--user', 'stop', unit], check=False) |
| 772 | |
| 773 | |
| 774 | IDLE_WAIT = 40 * 60 |
| 775 | |
| 776 | |
| 777 | def in_flight(): |
| 778 | """Steps queued or running, and merge steps among them, read from a |
| 779 | copy of staging's database (read-only).""" |
| 780 | # Suite people are torn down after each run, with their runners; a step |
| 781 | # one of them left behind can never finish, so it never holds a release. |
| 782 | real = ("state IN ('queued','running') AND task_id NOT IN (SELECT id FROM chat_tasks " |
| 783 | "WHERE creator LIKE 'suite-%@equipo-staging.invalid')") |
| 784 | out = carlos('db query', '--sql', "SELECT (SELECT count(*) FROM chat_steps WHERE " + real + ")||'/'||" |
| 785 | "(SELECT count(*) FROM chat_steps WHERE specialist='merge' AND " + real + ")", quiet=True) |
| 786 | m = re.search(r'^(\d+)/(\d+)\s*$', out.strip().splitlines()[-1] if out.strip() else '') |
| 787 | if not m: |
| 788 | raise RuntimeError('could not read the steps in flight') |
| 789 | return int(m.group(1)), int(m.group(2)) |
| 790 | |
| 791 | |
| 792 | def release(): |
| 793 | """The restage, in this order (2026-11-11): a release kills nothing. |
| 794 | |
| 795 | 1. HEAD is a descendant of what staging serves, and it is built. |
| 796 | 2. Nothing is in flight: no step queued or running and no merge (a |
| 797 | merge needs its runner on the instance it started with). Waits up |
| 798 | to IDLE_WAIT, checking each minute. |
| 799 | 3. Both runner units restart on HEAD's runner, immediately after that |
| 800 | check. They reconnect to the instance still serving and speak its |
| 801 | protocol; a runner restart is what fails a running step |
| 802 | (runner_restarted), so it happens while nothing runs. |
| 803 | 4. The instance swaps to HEAD. A swap ends the runners' connections |
| 804 | but not their processes: steps keep running and report on |
| 805 | reconnect. Steps dispatched after the swap are never cut by a |
| 806 | runner restart, which is why the runners go first. |
| 807 | """ |
| 808 | home = home_config() |
| 809 | sha = head() |
| 810 | served = deployed() |
| 811 | full = run(['git', 'rev-parse', sha], quiet=True).strip() |
| 812 | if subprocess.run(['git', 'merge-base', '--is-ancestor', served, full], cwd=REPO).returncode != 0: |
| 813 | raise RuntimeError(f'{sha} does not descend from {served}, which staging serves') |
| 814 | if not instance_binary(sha).exists(): |
| 815 | raise RuntimeError('build first') |
| 816 | deadline = time.monotonic() + IDLE_WAIT |
| 817 | while True: |
| 818 | steps, merges = in_flight() |
| 819 | if steps == 0 and merges == 0: |
| 820 | break |
| 821 | if time.monotonic() > deadline: |
| 822 | raise RuntimeError(f'still in flight after {IDLE_WAIT // 60} minutes: {steps} steps, {merges} merges') |
| 823 | print(f'in flight: {steps} steps, {merges} merges; waiting', flush=True) |
| 824 | time.sleep(60) |
| 825 | print('nothing in flight; runners first', flush=True) |
| 826 | runner(sha) |
| 827 | deploy(home) |
| 828 | |
| 829 | |
| 830 | def main(): |
| 831 | if len(sys.argv) < 2: |
| 832 | print(__doc__) |
| 833 | return 2 |
| 834 | ROOT.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 835 | SUITE_ROOT.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 836 | lock = (ROOT / 'gate.lock').open('a') |
| 837 | fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 838 | os.umask(0o077) |
| 839 | step = sys.argv[1] |
| 840 | try: |
| 841 | {'build': build, 'release': release, 'deploy': deploy, 'signin': signin, 'runner': runner, 'stop': stop, |
| 842 | 'cleanup-suite-runners': cleanup_suite_runners, |
| 843 | 'suite': lambda: suite(sys.argv[2] if len(sys.argv) > 2 else '')}[step]() |
| 844 | return 0 |
| 845 | except Exception as error: |
| 846 | print(f'FAIL {step}: {redact(str(error))}', file=sys.stderr, flush=True) |
| 847 | return 1 |
| 848 | |
| 849 | |
| 850 | if __name__ == '__main__': |
| 851 | sys.exit(main()) |
| 852 | |