#!/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']*action="' + re.escape(action) + 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-@equipo-staging.invalid. Only these # are ever removed by the harness (never the owner or SUITE). SUITE_PEOPLE = "person LIKE 'suite-%@equipo-staging.invalid'" def suite_person(address): return re.fullmatch(r'suite-[a-z0-9-]+@equipo-staging\.invalid', address) is not None def retire_suite(person, cookie_path): """Remove a run's suite person, which the harness added as an owner: an inactive member has every runner it enrolled revoked. The owner's session does it. A failure is said, never raised over the run's own outcome; the one-off cleanup catches what is left.""" if not suite_person(person): raise ValueError('not a suite person') try: owner = mail_signin(claude_a()['person_id'], cookie_path) setup_test(owner, EQUIPO_STAGING_REMOVE_SUITE=person) except Exception as error: print('suite retire: ' + redact(str(error)), flush=True) def stale_suite_runners(): out = carlos('db query', '--sql', "SELECT 'count=' || count(*) FROM runners WHERE revoked_at IS NULL AND " + SUITE_PEOPLE, quiet=True) m = re.search(r'^count=(\d+)\s*$', out, re.M) if not m: raise RuntimeError('could not count the suite runners') return int(m.group(1)) def cleanup_suite_runners(): """One-off, staging only: suite people whose runners are still enrolled (runs before 2026-11-28 never removed them) are removed by the owner, which revokes those runners. Prints counts only.""" before = stale_suite_runners() out = carlos('db query', '--sql', "SELECT 'persons=' || coalesce(group_concat(DISTINCT person), '') FROM runners WHERE revoked_at IS NULL AND " + SUITE_PEOPLE, quiet=True) m = re.search(r'^persons=(.*)$', out, re.M) if not m: raise RuntimeError('could not list the suite people') people = sorted({p for p in m.group(1).strip().split(',') if suite_person(p)}) if people: with tempfile.TemporaryDirectory(prefix='equipo-suite-', dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder: owner = mail_signin(claude_a()['person_id'], Path(folder) / 'owner-cookie') setup_test(owner, EQUIPO_STAGING_REMOVE_SUITE=','.join(people)) after = before # The database copy catches up with the instance. for _ in range(10): after = stale_suite_runners() if after == 0 or not people: break time.sleep(15) print(f'stale suite runners: {before} before, {after} after; suite people removed: {len(people)}', flush=True) def cleanup_suite(token, person): def request(path, method='GET'): req = urllib.request.Request(ORIGIN + '/api/v1' + path, method=method, headers={'Authorization': 'Bearer ' + token, 'Idempotency-Key': secrets.token_hex(16)}) with urllib.request.urlopen(req, timeout=30) as response: return json.load(response) try: tasks = request('/tasks')['items'] except Exception as error: print('suite cleanup: ' + redact(str(error)), flush=True) return cancelled = set() for task in tasks: if task['creator'] != person or task['stage'] in ('done', 'cancelled'): continue try: request('/tasks/' + urllib.parse.quote(task['id'], safe='') + '/cancel', 'POST') cancelled.add(task['id']) except Exception as error: print('suite cleanup ' + task['id'] + ': ' + redact(str(error)), flush=True) # A running step ends only when its runner confirms termination, and # the suite runner is stopped and its state deleted straight after # this. Wait for the confirmations, or the steps stay in flight forever. deadline = time.monotonic() + CANCEL_WAIT while cancelled: try: ended = {t['id'] for t in request('/tasks')['items'] if t['stage'] in ('done', 'cancelled')} except Exception as error: print('suite cleanup: ' + redact(str(error)), flush=True) ended = set() cancelled -= ended if not cancelled: break if time.monotonic() >= deadline: print('suite cleanup: still stopping ' + ', '.join(sorted(cancelled)), flush=True) break time.sleep(2) @contextmanager def fresh_suite(): run_id = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()).lower() + '-' + secrets.token_hex(6) person = 'suite-' + run_id + '@equipo-staging.invalid' bindings = SUITE_ROOT / 'config/bindings.json' original_bindings = json.loads(bindings.read_text()) service = SUITE_ROOT / 'service.env' original_service = service.read_text() env = read_env(service) # Reuse the installed binary, but enrol fresh state for this person. active = run(['systemctl', '--user', 'is-active', SUITE_UNIT], check=False, quiet=True).strip() == 'active' with tempfile.TemporaryDirectory(prefix='equipo-suite-', dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder: root = Path(folder) owner = mail_signin(claude_a()['person_id'], root / 'owner-cookie') setup_test(owner, EQUIPO_STAGING_ADD_OWNER=person) cookie = mail_signin(person, root / 'cookie') setup_test(cookie, EQUIPO_STAGING_TOKEN_FILE=str(root / 'token')) token = (root / 'token').read_text().strip() for key, directory in (('EQUIPO_RUNNER_STATE_DIR', 'state'), ('EQUIPO_WORKSPACE_ROOT', 'work'), ('EQUIPO_SCRATCH_ROOT', 'scratch'), ('EQUIPO_ACCOUNTS_ROOT', 'accounts')): (root / directory).mkdir(mode=0o700) env[key] = str(root / directory) env['EQUIPO_ACCOUNT_BINDINGS_PATH'] = str(root / 'bindings.json') env['EQUIPO_RUNNER_CREATE_REPOS'] = '0' private(root / 'bindings.json', json.dumps([dict(b, person_id=person) for b in original_bindings])) enrol(Path(env['EQUIPO_TOOL_PROXY_PATH']).parent, env, root / 'cookie') try: run(['systemctl', '--user', 'stop', SUITE_UNIT]) private(service, ''.join(f'{k}={json.dumps(v)}\n' for k, v in sorted(env.items()))) run(['systemctl', '--user', 'start', SUITE_UNIT]) print('suite run ' + run_id + ' as ' + person, flush=True) yield run_id, token finally: try: cleanup_suite(token, person) finally: run(['systemctl', '--user', 'stop', SUITE_UNIT]) private(service, original_service) # Its runner enrolment goes with the person, so suite # runners never pile up on staging. retire_suite(person, root / 'owner-cookie') if active: run(['systemctl', '--user', 'start', SUITE_UNIT]) def suite(only=''): with fresh_suite() as (run_id, token): suite_run(only, run_id, token) def suite_run(only, run_id, token): restart = f'carlos restart --app {APP} --account {ACCOUNT} --console {CONSOLE}' env = dict(os.environ, CGO_ENABLED='0', EQUIPO_STAGING_ORIGIN=ORIGIN, EQUIPO_STAGING_TOKEN=token, EQUIPO_STAGING_RUNNER_START=f'systemctl --user start {SUITE_UNIT}', EQUIPO_STAGING_RUNNER_STOP=f'systemctl --user stop {SUITE_UNIT}', EQUIPO_STAGING_RUNNER_RESTART=f'systemctl --user restart {SUITE_UNIT}', # A real crash: SIGKILL to the runner process only; its # namespaces die with it. The unit restarts on failure. EQUIPO_STAGING_RUNNER_KILL=f'systemctl --user kill --kill-whom=main --signal=SIGKILL {SUITE_UNIT} && sleep 1', EQUIPO_STAGING_INSTANCE_RESTART=restart, # Observed 11-17 turns on 2026-11-19; allow retries and headroom. EQUIPO_STAGING_TURN_LIMIT=os.environ.get('EQUIPO_STAGING_TURN_LIMIT', '30'), EQUIPO_STAGING_RUN_ID=run_id, EQUIPO_STAGING_SCENARIOS=only, EQUIPO_STAGING_PROJECT=os.environ.get('EQUIPO_STAGING_PROJECT', 'oficina/equipo'), # What the person says in the live Engineering scenarios: a # real bug in a repository the agent reaches; the step pushes # its own branch and nothing merges. 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.'), # The step crash and the step cancel each ask for their own # small, true change, so no two of a run's tasks read alike # (similar tasks are combined). The cancelled one never pushes. 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.'), 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.'), # Slice 4: tasks already pushed that the upgrade judges (no # new message), and what the person says in the live review # and checks scenario. EQUIPO_STAGING_REVIEW_TASKS=os.environ.get('EQUIPO_STAGING_REVIEW_TASKS', ''), EQUIPO_STAGING_REVIEW_WITNESS=os.environ.get('EQUIPO_STAGING_REVIEW_WITNESS', ''), # Slice 4c: what the person says in the live merge witness # (a repository whose own checks pass; Equipo merges it). EQUIPO_STAGING_MERGE_WITNESS=os.environ.get('EQUIPO_STAGING_MERGE_WITNESS', ''), # Connections slice 1: what the suite person says in the live # coordinator turn that should run on Codex (claude-a limited). EQUIPO_STAGING_CONN_WITNESS=os.environ.get('EQUIPO_STAGING_CONN_WITNESS', ''), EQUIPO_HEADLESS_REPORT=str(ROOT / 'report.json')) report = ROOT / 'report.json' report.unlink(missing_ok=True) try: # The whole output stays under the staging root: a failure reports # each failed scenario's own lines and this path. run(['go', 'test', './internal/headless', '-run', '^TestStaging$', '-count=1', '-v', '-timeout', '90m'], env=env, timeout=5600, log=ROOT / 'suite-logs' / (run_id + '.log')) finally: if report.exists(): print(report.read_text(), flush=True) json.loads(report.read_text()) # A missing or malformed report never records. if not only: record_running() def record_running(): """Record what staging actually ran: the deployed instance and the installed, running runners and tool proxy, each checked again now.""" sha = deployed() deployed_rec = json.loads((ROOT / 'deployed.json').read_text()) release = ROOT / 'releases' / sha for root, unit in ((ROOT, UNIT), (SUITE_ROOT, SUITE_UNIT)): installed = json.loads((root / 'installed.json').read_text()) if deployed_rec['version'] != sha or installed['version'] != sha: raise RuntimeError('staging is not serving the deployed and installed version') if sha256(release / 'equipo-runner') != installed['runner_sha256'] or sha256(release / 'equipo-tool-proxy') != installed['tool_proxy_sha256']: raise RuntimeError('installed runner files changed since install') if unit == SUITE_UNIT: # The suite's crash scenario may leave it restarting; start it. run(['systemctl', '--user', 'start', unit]) time.sleep(2) pid = run(['systemctl', '--user', 'show', '-p', 'MainPID', '--value', unit], quiet=True).strip() if not pid.isdigit() or pid == '0' or sha256(f'/proc/{pid}/exe') != installed['runner_sha256']: raise RuntimeError(f'the running {unit} is not the installed one') env = read_env(root / 'service.env') if Path(env['EQUIPO_TOOL_PROXY_PATH']) != release / 'equipo-tool-proxy': raise RuntimeError(f'{unit} uses another tool proxy') run(['python3', 'scripts/staged-artifacts.py', 'record', sha, '--instance', deployed_rec['instance_sha256'], '--runner', installed['runner_sha256'], '--tool-proxy', installed['tool_proxy_sha256']]) def stop(): for unit in (UNIT, SUITE_UNIT): run(['systemctl', '--user', 'stop', unit], check=False) IDLE_WAIT = 40 * 60 def in_flight(): """Steps queued or running, and merge steps among them, read from a copy of staging's database (read-only).""" # Suite people are torn down after each run, with their runners; a step # one of them left behind can never finish, so it never holds a release. real = ("state IN ('queued','running') AND task_id NOT IN (SELECT id FROM chat_tasks " "WHERE creator LIKE 'suite-%@equipo-staging.invalid')") out = carlos('db query', '--sql', "SELECT (SELECT count(*) FROM chat_steps WHERE " + real + ")||'/'||" "(SELECT count(*) FROM chat_steps WHERE specialist='merge' AND " + real + ")", quiet=True) m = re.search(r'^(\d+)/(\d+)\s*$', out.strip().splitlines()[-1] if out.strip() else '') if not m: raise RuntimeError('could not read the steps in flight') return int(m.group(1)), int(m.group(2)) def release(): """The restage, in this order (2026-11-11): a release kills nothing. 1. HEAD is a descendant of what staging serves, and it is built. 2. Nothing is in flight: no step queued or running and no merge (a merge needs its runner on the instance it started with). Waits up to IDLE_WAIT, checking each minute. 3. Both runner units restart on HEAD's runner, immediately after that check. They reconnect to the instance still serving and speak its protocol; a runner restart is what fails a running step (runner_restarted), so it happens while nothing runs. 4. The instance swaps to HEAD. A swap ends the runners' connections but not their processes: steps keep running and report on reconnect. Steps dispatched after the swap are never cut by a runner restart, which is why the runners go first. """ home = home_config() sha = head() served = deployed() full = run(['git', 'rev-parse', sha], quiet=True).strip() if subprocess.run(['git', 'merge-base', '--is-ancestor', served, full], cwd=REPO).returncode != 0: raise RuntimeError(f'{sha} does not descend from {served}, which staging serves') if not instance_binary(sha).exists(): raise RuntimeError('build first') deadline = time.monotonic() + IDLE_WAIT while True: steps, merges = in_flight() if steps == 0 and merges == 0: break if time.monotonic() > deadline: raise RuntimeError(f'still in flight after {IDLE_WAIT // 60} minutes: {steps} steps, {merges} merges') print(f'in flight: {steps} steps, {merges} merges; waiting', flush=True) time.sleep(60) print('nothing in flight; runners first', flush=True) runner(sha) deploy(home) def main(): if len(sys.argv) < 2: print(__doc__) return 2 ROOT.mkdir(parents=True, exist_ok=True, mode=0o700) SUITE_ROOT.mkdir(parents=True, exist_ok=True, mode=0o700) lock = (ROOT / 'gate.lock').open('a') fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) os.umask(0o077) step = sys.argv[1] try: {'build': build, 'release': release, 'deploy': deploy, 'signin': signin, 'runner': runner, 'stop': stop, 'cleanup-suite-runners': cleanup_suite_runners, 'suite': lambda: suite(sys.argv[2] if len(sys.argv) > 2 else '')}[step]() return 0 except Exception as error: print(f'FAIL {step}: {redact(str(error))}', file=sys.stderr, flush=True) return 1 if __name__ == '__main__': sys.exit(main())