#!/usr/bin/env python3 """Thin v1 staging: build, deploy equipo-staging, run the staging runner unit on this machine with the real Claude CLI, and run the headless suite. scripts/staging-thin.py build # instance (linux/arm64) + runner (linux/amd64) for HEAD scripts/staging-thin.py release # the restage, in order: idle check, runners, then the instance scripts/staging-thin.py deploy # env + carlos deploy --swap hold, wait for the version scripts/staging-thin.py signin # owner and suite sign-in by logged mail, suite device bearer scripts/staging-thin.py runner # both runner units: config, enrolment, start scripts/staging-thin.py suite [scenario,...] scripts/staging-thin.py stop # stop both staging runner units scripts/staging-thin.py cleanup-suite-runners # one-off: remove stale suite people and their runners Two people use staging. The owner (the claude-a binding's person) chats there and has the owner's runner unit, which stays running. The headless suite signs in as its own owner (SUITE, added by the owner's session) with its own runner unit, so the suite never writes into the owner's conversation. Only the owner's runner may create repositories. The suite's runner reads the production runner's forge credential file in place for the repositories it advertises. The owner's runner has its own agent-wide file, amadan.json under the staging root, made at each install from the same agent bearer and git PAT: it merges into every repository the hub lets the agent reach, including the ones it creates for jobs. Production's file is never changed. Only equipo-staging in Oficina on the flagship console, and only the staging runner units, are ever touched. Cookies, bearers and sign-in links are kept in 0600 files under the staging root and never printed. """ from contextlib import contextmanager import fcntl import hashlib import html import http.cookiejar import json import os from pathlib import Path import re import secrets import shlex import shutil import subprocess import sys import time import tempfile import urllib.parse import urllib.request APP, ACCOUNT, CONSOLE = 'equipo-staging', 'bds', 'https://console.carloku.com' HOST = 'equipo-staging.bds.oncarlos.com' ORIGIN = 'https://' + HOST UNIT = 'equipo-runner-staging.service' ROOT = Path.home() / '.local/share/equipo-runner-staging' SUITE = 'suite@equipo-staging.invalid' SUITE_UNIT = 'equipo-runner-staging-suite.service' SUITE_ROOT = ROOT / 'suite' PROD_ENV = Path.home() / '.local/share/equipo-runner/service.env' REPO = Path(__file__).resolve().parent.parent MARKER = '# equipo staging runner (thin v1)' # Base's origins whose Assistant hosts this instance accepts (PUT # /api/v1/assistant/host): staging Base, and where it moves under oficina.works. ASSISTANT_HOSTS = 'https://base.bds.oncarlos.com,https://base.oficina.works' def run(args, *, env=None, timeout=900, check=True, quiet=False, log=None): """With log, the whole output is kept there (redacted, 0600) and a failure reports go test's failed tests (failures) and the log's path instead of the output's last 2000 characters.""" result = subprocess.run(args, cwd=REPO, env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout) if log is not None: private(log, redact(result.stdout)) if check and result.returncode: # Never echo argv: secrets set takes a value in it. what = f'{Path(args[0]).name} {args[1] if len(args) > 1 else ""} failed ({result.returncode})' if log is not None: raise RuntimeError(f'{what}; full output in {log}\n{redact(failures(result.stdout))}') raise RuntimeError(f'{what}: {redact(result.stdout)[-2000:]}') if not quiet: print(redact(result.stdout), end='', flush=True) return result.stdout FAILURE_TAIL = 8192 def failures(output): """Each failed test's own lines from go test -v output, the last FAILURE_TAIL characters of each, then any panic (a test timeout is one). go test -v names the test a line belongs to with === RUN, CONT and NAME; a test's --- FAIL line follows its lines. Failed scenarios come before their parent test's own lines.""" lines, current, kept, panic = {}, None, [], None for line in output.splitlines(): if panic is not None: panic.append(line) continue m = re.match(r'^=== (RUN|CONT|NAME)\s+(\S+)', line) if m: current = m.group(2) lines.setdefault(current, []) continue m = re.match(r'^\s*--- FAIL: (\S+) ', line) if m: own = '\n'.join(lines.get(m.group(1), [])) if len(own) > FAILURE_TAIL: own = '...' + own[-FAILURE_TAIL:] kept.append((m.group(1), line.strip() + ('\n' + own if own else ''))) current = None continue if line.startswith('panic: '): panic = [line] continue if re.match(r'^\s*--- (PASS|SKIP): ', line): current = None elif current is not None: lines[current].append(line) names = [name for name, _ in kept] parents = lambda name: any(other.startswith(name + '/') for other in names) out = [text for name, text in kept if not parents(name)] + [text for name, text in kept if parents(name)] if panic is not None: out.append('\n'.join(panic)[:FAILURE_TAIL]) return '\n'.join(out) if out else '(no failed test named; see the log)' def redact(text): text = re.sub(r'https?://[^\s"\\]+/auth/(verify|callback)\?[^\s"\\]+', '[sign-in link redacted]', text) return re.sub(r'equipo\.person\.v1\.[A-Za-z0-9_-]+', '[bearer redacted]', text) def carlos(verb, *args, quiet=False): return run(['carlos', *verb.split(), '--app', APP, '--account', ACCOUNT, '--console', CONSOLE, *args], quiet=quiet) def private(path, text): path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, 'w') as f: f.write(text) os.chmod(path, 0o600) def head(): sha = run(['git', 'rev-parse', '--short', 'HEAD'], quiet=True).strip() if run(['git', 'status', '--porcelain', '--untracked-files=no'], quiet=True).strip(): raise RuntimeError('commit first: staging runs exact commits') return sha def read_env(path): out = {} for line in path.read_text().splitlines(): if '=' in line and not line.startswith('#'): k, v = line.split('=', 1) out[k] = shlex.split(v)[0] return out def claude_a(): bindings = json.loads(Path(read_env(PROD_ENV)['EQUIPO_ACCOUNT_BINDINGS_PATH']).read_text()) 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'] if len(chosen) != 1: raise RuntimeError('need exactly one claude-a / paul@tito.io / 2.1.312 binding') return chosen[0] def sha256(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def overlaps(a, b): a, b = Path(a).resolve(), Path(b).resolve() return a == b or a in b.parents or b in a.parents def refuse_shared_roots(): """Staging and production runners never share state, scratch or workspace roots.""" prod = read_env(PROD_ENV) for key in ('EQUIPO_RUNNER_STATE_DIR', 'EQUIPO_WORKSPACE_ROOT', 'EQUIPO_SCRATCH_ROOT'): theirs = prod.get(key) if not theirs: raise RuntimeError('production runner config lacks ' + key) for root in (ROOT, SUITE_ROOT): for mine in ('state', 'work', 'scratch', 'sessions'): if overlaps(theirs, root / mine): raise RuntimeError(f'staging {mine} overlaps the production runner {key}') for mine in ('state', 'work', 'scratch', 'sessions'): if overlaps(ROOT / mine, SUITE_ROOT / mine): raise RuntimeError(f'the two staging runners share {mine}') def build(): """The exact `make release` artifacts production would receive.""" sha = head() source = read_env(PROD_ENV) # The release check pins the installed provider binaries; their paths # come from the runner configuration (paths only, no credentials). env = dict(os.environ, **{k: v for k, v in source.items() if k in { 'EQUIPO_CLAUDE_PATH', 'EQUIPO_CODEX_PATH', 'EQUIPO_CODEX_CODE_MODE_HOST_PATH', 'EQUIPO_BWRAP_PATH'}}) run(['make', 'release'], env=env, timeout=1800) release = REPO / 'releases' / f'equipo-runner-linux-amd64-{sha}' runner = ROOT / 'releases' / sha runner.mkdir(parents=True, exist_ok=True, mode=0o700) # The preview scanner sits beside the runner, which looks for it there. for name in ('equipo-runner', 'equipo-tool-proxy', 'gitleaks'): shutil.copy2(release / name, runner / name) provenance(sha) # The page renderer as users get it: published on the forge under the # tag linked into the runner (scripts/publish-renderer.sh publish). # Downloaded in full, without credentials (never a HEAD: the forge # counts a redirect as a download), and required to be the release's # bytes, which provenance just held to the build. A release whose # renderer is not published stops here, before staging installs # anything, so production cannot ship without it. published = runner / 'published-renderer' run(['scripts/publish-renderer.sh', 'check', str(release), str(published)], timeout=2400) # Unpacked by the staged runner from that download and held to the pin # linked into it (both staging runners use it); verify-installed # renders a page with it. run([str(runner / 'equipo-runner'), 'install-renderer', str(published / 'renderer.tar.gz')]) print(f'built {sha}: {instance_binary(sha)} and {runner}') return sha def provenance(sha): """The digests the release build recorded, after checking that the release artifacts, and staging's copies of the runner, tool proxy and preview scanner, are still those bytes. Nothing is deployed or installed without it.""" run(['python3', 'scripts/staged-artifacts.py', 'verify', sha]) made = json.loads((REPO / 'releases' / f'equipo-linux-arm64-{sha}.manifest.json').read_text())['sha256'] for name, key in (('equipo-runner', 'runner'), ('equipo-tool-proxy', 'tool_proxy'), ('gitleaks', 'gitleaks')): path = ROOT / 'releases' / sha / name if not path.is_file() or sha256(path) != made[key]: raise RuntimeError(f'staging holds another {name} than the {sha} release built') return made def instance_binary(sha): return REPO / 'releases' / f'equipo-linux-arm64-{sha}' def home_config(): home = json.loads((ROOT / 'home-config.json').read_text()) if (not isinstance(home, dict) or set(home) != {'EQUIPO_HOME_ISSUER', 'EQUIPO_HOME_CONSUMER_ID', 'EQUIPO_HOME_KEYS_BASE64', 'EQUIPO_HOME_DEK_BASE64'} or home['EQUIPO_HOME_ISSUER'] != 'https://oficina-id-staging.bds.oncarlos.com' or home['EQUIPO_HOME_CONSUMER_ID'] != 'equipo-staging' or not all(isinstance(value, str) and value for value in home.values())): raise RuntimeError('invalid staging home configuration') return home def set_home_config(home): try: result = subprocess.run(['carlos', 'env', 'set', '--app', APP, '--account', ACCOUNT, '--console', CONSOLE, '--no-prompt', *(name + '=' + value for name, value in home.items())], cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60) except (OSError, subprocess.TimeoutExpired): raise RuntimeError('could not set staging home configuration') from None if result.returncode: raise RuntimeError('could not set staging home configuration') def deploy(home=None): home = home_config() if home is None else home sha = head() binary = instance_binary(sha) if not binary.exists(): raise RuntimeError('build first') if sha256(binary) != provenance(sha)['instance']: raise RuntimeError(f'the instance is not the one the {sha} release built') if 'EQUIPO_INSTANCE_KEY' not in carlos('secrets list', quiet=True): carlos('secrets set', 'EQUIPO_INSTANCE_KEY=' + secrets.token_urlsafe(48), quiet=True) # gitleaks:allow (generated, never stored in source) owner = claude_a()['person_id'] backup() # The suite person (SUITE, *.invalid) is a test identity: its tasks # are listed only to itself and never paired with anyone's as a # duplicate. The thin core has no teams within an instance to move it # into, so it is hidden instead (UX1-PROGRESS.md). carlos('env set', '--no-prompt', 'EQUIPO_ORIGIN=' + ORIGIN, 'EQUIPO_OWNERS=' + owner, 'EQUIPO_EXECUTION_ENABLED=1', 'EQUIPO_EXECUTION_MARKER_PATH=/data/instances/' + HOST + '/execution/witness', 'EQUIPO_ALLOW_LOGGED_MAIL=1', 'EQUIPO_TEST_PEOPLE=.invalid', 'EQUIPO_ASSISTANT_HOSTS=' + ASSISTANT_HOSTS) set_home_config(home) carlos('deploy', '--target', 'linux-arm64', '--swap', 'hold', '--version', sha, '--timeout', '5m', '--no-prompt', str(binary)) deadline = time.monotonic() + 120 while True: try: with urllib.request.urlopen(ORIGIN + '/api/version', timeout=15) as r: if r.read().decode().strip() == sha: private(ROOT / 'deployed.json', json.dumps({'version': sha, 'instance_sha256': sha256(binary)})) print('serving', sha) return except (OSError, ValueError): pass if time.monotonic() > deadline: raise RuntimeError('staging does not report ' + sha) time.sleep(2) def backup(): """A copy of staging's database before every deploy (a release may change data on start: it combines duplicate tasks), kept 0600 under the staging root; the newest five are kept.""" folder = ROOT / 'backups' folder.mkdir(parents=True, exist_ok=True, mode=0o700) out = folder / ('equipo-' + time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '.db') carlos('db pull', '--out', str(out), quiet=True) os.chmod(out, 0o600) for old in sorted(folder.glob('equipo-*.db'))[:-5]: old.unlink() print('backed up', out) class FormParser: """Reads the inputs of the first form posting to action.""" def __init__(self, page, action): m = re.search(r'
', page, re.S) if not m: raise RuntimeError('no form for ' + action) self.fields = {} for tag in re.findall(r']*>', m.group(1)): name = re.search(r'name="([^"]*)"', tag) value = re.search(r'value="([^"]*)"', tag) if name: self.fields[html.unescape(name.group(1))] = html.unescape(value.group(1)) if value else '' def logged_mail(): return run(['carlos', 'logs', '--app', APP, '--account', ACCOUNT, '--console', CONSOLE, '--grep', 'NOT SENT', '--since', '10m', '-n', '50'], quiet=True) def signin_links(logs, address, before): """Sign-in links logged for address, oldest first, minus those in before.""" found = [l for l in re.findall(r'[^\n]*' + re.escape(ORIGIN) + r'/auth/(?:verify|callback)\?[^\s"\\]+[^\n]*', logs) if address in l or urllib.parse.quote(address) in l] links = [re.search(re.escape(ORIGIN) + r'/auth/(?:verify|callback)\?[^\s"\\]+', l).group() for l in found] return [l for l in links if l not in before] def mail_signin(address, cookie_path): """Sign address in by logged mail; the session cookie goes to a 0600 file.""" jar = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar)) opener.addheaders = [('Origin', ORIGIN), ('Sec-Fetch-Site', 'same-origin')] # The door's email way: with Oficina ID configured, a plain /signin # offers Continue with Oficina ID first and has no email form. page = opener.open(ORIGIN + '/signin?way=email', timeout=30).read().decode() form = FormParser(page, '/auth/begin').fields form.update(address=address, force='1') # A link logged before this sign-in began was already used (by an # earlier run); taking it leaves no session. before = set(signin_links(logged_mail(), address, set())) time.sleep(4) # the sign-in proof has a minimum age opener.open(ORIGIN + '/auth/begin', urllib.parse.urlencode(form).encode(), timeout=30).read() link = None deadline = time.monotonic() + 120 while link is None: fresh = signin_links(logged_mail(), address, before) if fresh: link = fresh[-1] elif time.monotonic() > deadline: raise RuntimeError('no logged sign-in mail for ' + address) else: time.sleep(3) page = opener.open(link, timeout=30).read().decode() if 'action="/auth/verify"' in page: fields = FormParser(page, '/auth/verify').fields opener.open(ORIGIN + '/auth/verify', urllib.parse.urlencode(fields).encode(), timeout=30).read() cookies = [c for c in jar if 'session' in c.name] if not cookies: raise RuntimeError('sign-in did not set a session for ' + address) cookie = '; '.join(f'{c.name}={c.value}' for c in cookies) private(cookie_path, cookie) return cookie def setup_test(cookie, **extra): env = dict(os.environ, CGO_ENABLED='0', EQUIPO_STAGING_ORIGIN=ORIGIN, EQUIPO_STAGING_COOKIE=cookie, **extra) run(['go', 'test', './internal/stagingtest', '-run', '^TestStagingSetup$', '-count=1', '-v'], env=env) def signin(): """The owner signs in (their session adds the suite's owner and approves the owner's runner); the suite signs in as itself and gets the bearer.""" owner = mail_signin(claude_a()['person_id'], ROOT / 'cookie') setup_test(owner, EQUIPO_STAGING_ADD_OWNER=SUITE) suite = mail_signin(SUITE, SUITE_ROOT / 'cookie') setup_test(suite, EQUIPO_STAGING_TOKEN_FILE=str(SUITE_ROOT / 'token')) print('owner and suite signed in; suite device bearer saved') def instance_id(): req = urllib.request.Request(ORIGIN + '/api/v1/me', headers={'Authorization': 'Bearer ' + (SUITE_ROOT / 'token').read_text().strip()}) with urllib.request.urlopen(req, timeout=30) as r: return json.load(r)['team_id'] def deployed(): with urllib.request.urlopen(ORIGIN + '/api/version', timeout=30) as r: return r.read().decode().strip() def runner(sha=None): # The runners match the instance staging is serving, or, in a release, # the one about to be swapped in (runners first, then the instance). sha = sha or deployed() release = ROOT / 'releases' / sha if not (release / 'equipo-runner').exists(): raise RuntimeError('build first') refuse_shared_roots() provenance(sha) owner = claude_a()['person_id'] install(sha, release, ROOT, UNIT, owner, ROOT / 'cookie', create=True) install(sha, release, SUITE_ROOT, SUITE_UNIT, SUITE, SUITE_ROOT / 'cookie', create=False) def install(sha, release, root, unit_name, person, cookie_path, create): unit = Path.home() / '.config/systemd/user' / unit_name if unit.exists() and MARKER not in unit.read_text(): raise RuntimeError('refusing to replace an unrecognised ' + unit_name) for name in ['state', 'work', 'scratch', 'sessions', 'config', 'accounts']: (root / name).mkdir(parents=True, exist_ok=True, mode=0o700) binding = dict(claude_a(), person_id=person) private(root / 'config/bindings.json', json.dumps([binding] + added_in_app(root, person))) source = read_env(PROD_ENV) env = {k: v for k, v in source.items() if k in { 'EQUIPO_CLAUDE_PATH', 'EQUIPO_CODEX_PATH', 'EQUIPO_CODEX_CODE_MODE_HOST_PATH', 'EQUIPO_BWRAP_PATH', 'EQUIPO_GIT_PATH', 'EQUIPO_AMADAN_PATH', 'EQUIPO_GO_BINARY', 'EQUIPO_GO_ROOT', 'EQUIPO_CLAUDE_MODEL'}} # Only the forge credential's repository names and the agent's reach # leave the runner. The suite reads production's file in place; the # owner's runner, which creates repositories, has the agent-wide one. credential = source['EQUIPO_AMADAN_CREDENTIAL_PATH'] if root == ROOT: credential = str(agent_credential(credential)) env.update(EQUIPO_ORIGIN=ORIGIN, EQUIPO_INSTANCE_ID=instance_id(), EQUIPO_MACHINE_LABEL='docs-t1 staging', EQUIPO_RUNNER_STATE_DIR=str(root / 'state'), EQUIPO_WORKSPACE_ROOT=str(root / 'work'), EQUIPO_SCRATCH_ROOT=str(root / 'scratch'), EQUIPO_ACCOUNT_BINDINGS_PATH=str(root / 'config/bindings.json'), EQUIPO_AMADAN_CREDENTIAL_PATH=credential, EQUIPO_TOOL_PROXY_PATH=str(release / 'equipo-tool-proxy'), EQUIPO_ACCOUNTS_ROOT=str(root / 'accounts'), EQUIPO_RUNNER_CREATE_REPOS='1' if create else '0') carlos = shutil.which('carlos') or str(Path.home() / '.local/bin/carlos') if root == ROOT and Path(carlos).is_file(): # The owner's runner pairs with this machine's CARLOS devbox for # previews (links on the tailnet); the suite's never publishes. env.update(EQUIPO_PREVIEW_HOST='devbox', EQUIPO_CARLOS_PATH=carlos) # It also publishes merged websites on Carloku (account oficina, # channel edge), with this user's signed-in carlos, and only after # the person answers the publish card. env.update(EQUIPO_SITE_HOST='carloku') if root == ROOT: # The owner's runner has the pinned Pi (metered connections). The # release's install-pi is idempotent: it returns at once when the # tree under pi/ already matches its pins, and otherwise installs # it and checks the digests, so a restage never leaves Pi missing. run([str(release / 'equipo-runner'), 'install-pi', str(root / 'pi')]) env.update(EQUIPO_PI_ROOT=str(root / 'pi')) # And the pinned OpenCode (OpenCode Go connections), the same way: # install-opencode keeps a tree under opencode/ that verifies # against its pins and fetches nothing; otherwise it installs and # checks it. The suite's runner gets neither harness. run([str(release / 'equipo-runner'), 'install-opencode', str(root / 'opencode')]) env.update(EQUIPO_OPENCODE_ROOT=str(root / 'opencode')) private(root / 'service.env', ''.join(f'{k}={json.dumps(v)}\n' for k, v in sorted(env.items()))) # Before enrolment or the unit starts anything: the runner holds every # program in this configuration (bubblewrap, claude, codex and its code # mode host, the tool proxy) to the digests of its release. run([str(release / 'equipo-runner'), 'verify-installed'], env=dict(os.environ, **env)) unit.parent.mkdir(parents=True, exist_ok=True) unit.write_text(MARKER + '\n[Unit]\nDescription=Equipo staging runner\n[Service]\nType=simple\n' f'EnvironmentFile={root / "service.env"}\nExecStart={release / "equipo-runner"} run\n' 'Restart=on-failure\nRestartSec=5\nRestartPreventExitStatus=3\nTimeoutStopSec=45\n' 'KillMode=control-group\nUMask=0077\nNoNewPrivileges=yes\n') run(['systemctl', '--user', 'daemon-reload']) if not (root / 'state/credentials.json').exists(): # A pending enrolment for another instance is stale; start over. (root / 'state/enrolment.json').unlink(missing_ok=True) enrol(release, env, cookie_path) private(root / 'installed.json', json.dumps({'version': sha, 'runner_sha256': sha256(release / 'equipo-runner'), 'tool_proxy_sha256': sha256(release / 'equipo-tool-proxy')})) run(['systemctl', '--user', 'restart', unit_name]) print(unit_name, sha, 'started') def agent_credential(source): """Staging's own forge credential file: production's agent, bearer and git PAT as one agent-wide entry, mode 0600. The hub decides which repositories that reaches. A file of per-repository entries only lets the runner merge into those repositories: a merge into one it created for a job was refused before it reached the hub. Values are never printed.""" data = json.loads(Path(source).read_text()) if data.get('api'): pairs = {(data.get('api'), data.get('git'))} else: pairs = {(e.get('api'), e.get('git')) if isinstance(e, dict) else (e, None) for e in (data.get('repositories') or {}).values()} agent = data.get('agent') if len(pairs) != 1 or not all(isinstance(v, str) and v for v in [agent, *next(iter(pairs))]): raise RuntimeError('the production forge credential has no single agent bearer and git PAT') api, git = next(iter(pairs)) path = ROOT / 'amadan.json' private(path, json.dumps({'agent': agent, 'api': api, 'git': git})) return path def added_in_app(root, person): """Connections added in the app (Connections slice 1) live in the staging root's own accounts directory and survive a restage. The suite person runs on the owner's in-app Codex account the way it runs on claude-a: the same home, read in place, never copied.""" def kept(path, home_root): try: rows = json.loads(path.read_text()) except (FileNotFoundError, ValueError): return [] return [b for b in rows if b.get('local_id') != 'claude-a' and Path(b.get('provider_home', '/')).parent == home_root] own = kept(root / 'config/bindings.json', root / 'accounts') if root == SUITE_ROOT: owner = [dict(b, person_id=person) for b in kept(ROOT / 'config/bindings.json', ROOT / 'accounts') if b.get('provider') == 'codex'] own = [b for b in own if b.get('provider') != 'codex'] + owner return own def enrol(release, env, cookie_path): cookie = cookie_path.read_text().strip() 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) proc.stdout.readline() code = proc.stdout.readline().strip() if not re.fullmatch(r'[A-Z0-9-]{4,16}', code): proc.kill() raise RuntimeError('enrol printed no user code: ' + redact(code)) setup_test(cookie, EQUIPO_STAGING_ENROL_CODE=code) if proc.wait(timeout=120) != 0: raise RuntimeError('enrolment failed: ' + redact(proc.stdout.read())) print('staging runner enrolled') CANCEL_WAIT = 120 # A fresh suite person: suite-