import importlib.util import json import os from pathlib import Path import tempfile import sys import unittest from unittest.mock import patch sys.dont_write_bytecode = True spec = importlib.util.spec_from_file_location('staging', Path(__file__).with_name('staging-thin.py')) staging = importlib.util.module_from_spec(spec) spec.loader.exec_module(staging) class SuiteTest(unittest.TestCase): def test_fresh_runs_and_green_record(self): with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder: root = Path(folder) suite_root = root / 'suite' (suite_root / 'config').mkdir(parents=True) bindings = suite_root / 'config/bindings.json' original = json.dumps([{'local_id': 'claude-a', 'person_id': 'old.invalid'}, {'local_id': 'codex-app', 'person_id': 'old.invalid'}]) bindings.write_text(original) service = suite_root / 'service.env' original_service = 'EQUIPO_TOOL_PROXY_PATH="/installed/equipo-tool-proxy"\nEQUIPO_RUNNER_STATE_DIR="/existing/state"\n' service.write_text(original_service) addresses, runs, cleaned, records, enrolled, retired = [], [], [], [], [], [] fail = False report_mode = "valid" def mail(address, path): staging.private(path, 'cookie') return 'cookie' def setup(cookie, **extra): if 'EQUIPO_STAGING_ADD_OWNER' in extra: addresses.append(extra['EQUIPO_STAGING_ADD_OWNER']) if 'EQUIPO_STAGING_TOKEN_FILE' in extra: staging.private(Path(extra['EQUIPO_STAGING_TOKEN_FILE']), 'fresh-token') if 'EQUIPO_STAGING_REMOVE_SUITE' in extra: # Retired by the owner, after its tasks were cleaned up. self.assertEqual(cookie, 'cookie') self.assertEqual(cleaned[-1], extra['EQUIPO_STAGING_REMOVE_SUITE']) retired.append(extra['EQUIPO_STAGING_REMOVE_SUITE']) def run(args, **kwargs): if 'is-active' in args: return 'active\n' if '^TestStaging$' in args: env = kwargs['env'] runs.append(env) self.assertEqual(kwargs['log'].parent, root / 'suite-logs') self.assertIn(env['EQUIPO_STAGING_RUN_ID'], kwargs['log'].name) self.assertEqual(env['EQUIPO_STAGING_TOKEN'], 'fresh-token') self.assertGreaterEqual(int(env['EQUIPO_STAGING_TURN_LIMIT']), 25) running = staging.read_env(service) self.assertTrue(all(b['person_id'] == addresses[-1] for b in json.loads(Path(running['EQUIPO_ACCOUNT_BINDINGS_PATH']).read_text()))) state = Path(running['EQUIPO_RUNNER_STATE_DIR']) self.assertEqual((state / 'person').read_text(), addresses[-1]) self.assertEqual(running['EQUIPO_RUNNER_CREATE_REPOS'], '0') if fail: raise RuntimeError('scenario failed') if report_mode != 'missing': Path(env['EQUIPO_HEADLESS_REPORT']).write_text('{}' if report_mode == 'valid' else 'broken') return '' def enrol(release, env, cookie): enrolled.append(addresses[-1]) self.assertEqual(cookie.read_text(), 'cookie') self.assertEqual(release, Path('/installed')) state = Path(env['EQUIPO_RUNNER_STATE_DIR']) self.assertEqual(list(state.iterdir()), []) self.assertNotEqual(str(state), '/existing/state') (state / 'person').write_text(addresses[-1]) with patch.multiple(staging, ROOT=root, SUITE_ROOT=suite_root), \ patch.object(staging, 'mail_signin', side_effect=mail), \ patch.object(staging, 'setup_test', side_effect=setup), \ patch.object(staging, 'claude_a', return_value={'person_id': 'owner@example.com'}), \ patch.object(staging, 'run', side_effect=run), \ patch.object(staging, 'enrol', side_effect=enrol), \ patch.object(staging, 'cleanup_suite', side_effect=lambda token, person: cleaned.append(person)), \ patch.object(staging, 'record_running', side_effect=lambda: records.append(True)), \ patch.dict(os.environ, {}, clear=False): os.environ.pop('EQUIPO_STAGING_TURN_LIMIT', None) os.environ['TMPDIR'] = str(root) staging.suite() staging.suite('2_project') fail = True with self.assertRaisesRegex(RuntimeError, 'scenario failed'): staging.suite() fail = False report_mode = 'missing' with self.assertRaises(FileNotFoundError): staging.suite() report_mode = 'broken' with self.assertRaises(json.JSONDecodeError): staging.suite() self.assertEqual(len(set(addresses)), 5) self.assertTrue(all(a.startswith('suite-') and a.endswith('@equipo-staging.invalid') for a in addresses)) self.assertEqual(enrolled, addresses) self.assertEqual(cleaned, addresses) # Every run's person, and with it the runner it enrolled, is # removed at the end, a failed run's too (2026-11-28: 32 suite # runners were left enrolled on staging). self.assertEqual(retired, addresses) self.assertEqual(len(records), 1) self.assertEqual(bindings.read_text(), original) self.assertEqual(service.read_text(), original_service) self.assertEqual(len({e['EQUIPO_STAGING_RUN_ID'] for e in runs}), 5) self.assertFalse(list(root.glob('equipo-suite-*'))) def test_cleanup_only_this_person_and_continues_after_failure(self): person = 'suite-run@equipo-staging.invalid' tasks = [dict(id='ours-1', creator=person, stage='noted'), dict(id='human', creator='owner@example.com', stage='in_progress'), dict(id='old', creator='suite-old@equipo-staging.invalid', stage='noted'), dict(id='ours-done', creator=person, stage='done'), dict(id='ours-2', creator=person, stage='in_progress')] requests = [] from io import BytesIO def respond(req, **kwargs): requests.append(req) if req.full_url.endswith('/tasks'): return BytesIO(json.dumps({'items': tasks}).encode()) if 'ours-1' in req.full_url: raise OSError('temporary failure') return BytesIO(b'{}') def settle(seconds): # The runner confirms termination a little later. tasks[-1]['stage'] = 'cancelled' with patch.object(staging.urllib.request, 'urlopen', side_effect=respond), \ patch.object(staging.time, 'sleep', side_effect=settle): staging.cleanup_suite('test-token', person) self.assertEqual([r.method for r in requests], ['GET', 'POST', 'POST', 'GET', 'GET']) self.assertEqual([r.full_url.rsplit('/', 2)[-2] for r in requests[1:3]], ['ours-1', 'ours-2']) self.assertTrue(all(r.get_header('Authorization') == 'Bearer test-token' for r in requests)) def test_cleanup_waits_for_running_steps_to_stop(self): # A cancel only finishes once the runner confirms; stopping the # suite runner first strands the step and blocks every release. person = 'suite-run@equipo-staging.invalid' tasks = [dict(id='ours', creator=person, stage='in_progress')] from io import BytesIO clock = [0.0] def respond(req, **kwargs): if req.full_url.endswith('/tasks'): return BytesIO(json.dumps({'items': tasks}).encode()) return BytesIO(b'{}') def sleep(seconds): clock[0] += seconds with patch.object(staging.urllib.request, 'urlopen', side_effect=respond), \ patch.object(staging.time, 'sleep', side_effect=sleep), \ patch.object(staging.time, 'monotonic', side_effect=lambda: clock[0]): staging.cleanup_suite('test-token', person) self.assertGreaterEqual(clock[0], staging.CANCEL_WAIT) def test_retire_failure_does_not_hide_the_run(self): # A removal that fails is said, and the run's own outcome stands. def setup(cookie, **extra): raise RuntimeError('HTTP 500') with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder, \ patch.object(staging, 'mail_signin', return_value='cookie'), \ patch.object(staging, 'claude_a', return_value={'person_id': 'owner@example.com'}), \ patch.object(staging, 'setup_test', side_effect=setup), \ patch('builtins.print') as said: staging.retire_suite('suite-run@equipo-staging.invalid', Path(folder) / 'owner-cookie') self.assertIn('suite retire', said.call_args[0][0]) with self.assertRaises(ValueError): staging.retire_suite('owner@example.com', Path('/nowhere')) def test_stale_suite_runners_are_retired_counting_only(self): # The one-off cleanup: suite people whose runners are still # enrolled, read from staging's database copy, are removed by the # owner in one pass; only counts are printed, never an address. counts = iter(['count=32\n', 'count=0\n']) sql, removed = [], [] def carlos(verb, *args, quiet=False): sql.append(args[-1]) if "group_concat" in args[-1]: return "header\npersons=suite-a@equipo-staging.invalid,suite-b@equipo-staging.invalid,owner@example.com\n" return next(counts) def setup(cookie, **extra): removed.append(extra['EQUIPO_STAGING_REMOVE_SUITE']) with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder, \ patch.object(staging, 'ROOT', Path(folder)), \ patch.object(staging, 'carlos', side_effect=carlos), \ patch.object(staging, 'mail_signin', return_value='cookie'), \ patch.object(staging, 'claude_a', return_value={'person_id': 'owner@example.com'}), \ patch.object(staging, 'setup_test', side_effect=setup), \ patch.object(staging.time, 'sleep'), \ patch('builtins.print') as said: staging.cleanup_suite_runners() self.assertEqual(removed, ['suite-a@equipo-staging.invalid,suite-b@equipo-staging.invalid']) self.assertTrue(all("LIKE 'suite-%@equipo-staging.invalid'" in q and 'revoked_at IS NULL' in q for q in sql)) out = ' '.join(str(c.args[0]) for c in said.call_args_list) self.assertNotIn('@', out) self.assertIn('32', out) self.assertIn('2', out) self.assertIn('0', out) def test_in_flight_ignores_suite_people(self): seen = [] def carlos(verb, *args, quiet=False): seen.append(args[-1]) return '0/0\n' with patch.object(staging, 'carlos', side_effect=carlos): self.assertEqual(staging.in_flight(), (0, 0)) self.assertIn("task_id NOT IN (SELECT id FROM chat_tasks WHERE creator LIKE 'suite-%@equipo-staging.invalid')", seen[0]) def test_signin_ignores_links_logged_before_it_began(self): origin = staging.ORIGIN old = origin + '/auth/verify?t=old' new = origin + '/auth/verify?t=new' other = origin + '/auth/verify?t=other' logs = '\n'.join(['NOT SENT to a@example.com: ' + old, 'NOT SENT to b@example.com: ' + other, 'NOT SENT to a@example.com: ' + new]) before = set(staging.signin_links(logs.split('\n')[0], 'a@example.com', set())) self.assertEqual(staging.signin_links(logs, 'a@example.com', before), [new]) self.assertEqual(staging.signin_links(logs.split('\n')[0], 'a@example.com', before), []) # What go test -v prints when a staging scenario fails: the failure lines, # then far more than 2000 characters of passing chatter and timing logs. FAILED_RUN = '''=== RUN TestStaging === RUN TestStaging/7_stream_resume scenarios_test.go:530: model turns used: 1 (total 3) === RUN TestStaging/8_instance_restart scenarios_test.go:380: restart: carlos restart failed: exit status 1 second line of the same message scenarios_test.go:385: sign-in https://x.invalid/auth/verify?token=abc kept panic.go:694: model turns used: 1 (total 4) === NAME TestStaging scenarios_test.go:536: model turns used: 4 ''' + ''.join(f' scenarios_test.go:540: timing {i}: {{"first_token": "1.2s", "turn": "3.4s"}}\n' for i in range(200)) + '''--- FAIL: TestStaging (300.00s) --- PASS: TestStaging/7_stream_resume (12.00s) --- FAIL: TestStaging/8_instance_restart (240.00s) FAIL FAIL\tequipo/internal/headless\t300.123s FAIL ''' class FailureOutputTest(unittest.TestCase): def test_failed_scenario_keeps_its_message_and_the_full_log(self): with scratch() as folder: root = Path(folder) log = root / 'suite-logs' / 'run.log' fake = root / 'fake.txt' fake.write_text(FAILED_RUN) with self.assertRaises(RuntimeError) as caught: staging.run([sys.executable, '-c', 'import sys; sys.stdout.write(open(sys.argv[1]).read()); sys.exit(1)', str(fake)], log=log) message = str(caught.exception) self.assertIn('--- FAIL: TestStaging/8_instance_restart (240.00s)', message) self.assertIn('carlos restart failed: exit status 1', message) self.assertIn('second line of the same message', message) self.assertIn('scenarios_test.go:385', message) # The failed scenario comes before its parent's chatter. self.assertLess(message.index('--- FAIL: TestStaging/8_instance_restart'), message.index('--- FAIL: TestStaging (')) self.assertNotIn('7_stream_resume', message) self.assertIn(str(log), message) self.assertNotIn('token=abc', message) # The log is the whole output, redacted, private. self.assertEqual(log.stat().st_mode & 0o777, 0o600) text = log.read_text() self.assertIn('timing 199', text) self.assertIn('7_stream_resume', text) self.assertNotIn('token=abc', text) def test_a_long_failure_keeps_its_last_lines(self): lines = ['=== RUN TestStaging/cancel'] + [f' scenarios_test.go:416: line {i:05d} ' + 'x' * 80 for i in range(1000)] + ['--- FAIL: TestStaging/cancel (60.50s)'] summary = staging.failures('\n'.join(lines) + '\n') self.assertIn('line 00999', summary) self.assertNotIn('line 00000', summary) self.assertLess(len(summary), 3 * staging.FAILURE_TAIL) def test_a_panic_or_timeout_is_kept(self): out = '=== RUN TestStaging/cancel\npanic: test timed out after 90m0s\n\trunning tests:\n\t\tTestStaging/cancel (1h29m)\n' self.assertIn('panic: test timed out after 90m0s', staging.failures(out)) self.assertIn('TestStaging/cancel (1h29m)', staging.failures(out)) def test_success_writes_the_log_too(self): with scratch() as folder: log = Path(folder) / 'suite-logs' / 'ok.log' staging.run([sys.executable, '-c', 'print("--- PASS: TestStaging (1.00s)")'], log=log, quiet=True) self.assertIn('--- PASS', log.read_text()) def scratch(): return tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) class ReleaseTest(unittest.TestCase): """What the staging runner is installed with.""" def release(self, repo, sha): built = repo / 'releases' / f'equipo-runner-linux-amd64-{sha}' built.mkdir(parents=True) for name in ('equipo-runner', 'equipo-tool-proxy', 'gitleaks'): (built / name).write_bytes(name.encode() + b' bytes') (built / name).chmod(0o700) made = {k: staging.sha256(built / n) for k, n in (('runner', 'equipo-runner'), ('tool_proxy', 'equipo-tool-proxy'), ('gitleaks', 'gitleaks'))} (repo / 'releases' / f'equipo-linux-arm64-{sha}.manifest.json').write_text(json.dumps({'sha256': made})) return built def test_build_installs_the_preview_scanner_beside_the_runner(self): # The runner looks for gitleaks next to its own executable; without # it every preview fails with preview_scanner. with scratch() as folder: repo, root = Path(folder) / 'repo', Path(folder) / 'root' built = self.release(repo, 'abc1234') prod = Path(folder) / 'prod.env' prod.write_text('EQUIPO_CLAUDE_PATH="/bin/claude"\n') with patch.multiple(staging, REPO=repo, ROOT=root, PROD_ENV=prod), \ patch.object(staging, 'head', return_value='abc1234'), \ patch.object(staging, 'run', return_value=''): staging.build() scanner = root / 'releases/abc1234/gitleaks' self.assertEqual(scanner.read_bytes(), (built / 'gitleaks').read_bytes()) self.assertTrue(os.access(scanner, os.X_OK)) def test_build_installs_the_renderer_beside_the_runner(self): # The published renderer is downloaded in full and held to the # release (publish-renderer.sh check), after provenance and before # anything is installed; the staged runner unpacks that download # beside itself (install-renderer); verify-installed then checks # the tree and renders the fixture page with it. with scratch() as folder: repo, root = Path(folder) / 'repo', Path(folder) / 'root' built = self.release(repo, 'abc1234') prod = Path(folder) / 'prod.env' prod.write_text('EQUIPO_CLAUDE_PATH="/bin/claude"\n') with patch.multiple(staging, REPO=repo, ROOT=root, PROD_ENV=prod), \ patch.object(staging, 'head', return_value='abc1234'), \ patch.object(staging, 'run', return_value='') as run: staging.build() calls = [c.args[0] for c in run.call_args_list] published = root / 'releases/abc1234/published-renderer' check = ['scripts/publish-renderer.sh', 'check', str(built), str(published)] install = [str(root / 'releases/abc1234/equipo-runner'), 'install-renderer', str(published / 'renderer.tar.gz')] self.assertIn(check, calls) self.assertIn(install, calls) # After the provenance check, which holds the runner to the # release, and the published asset's check. verify = ['python3', 'scripts/staged-artifacts.py', 'verify', 'abc1234'] self.assertLess(calls.index(verify), calls.index(check)) self.assertLess(calls.index(check), calls.index(install)) def test_provenance_holds_the_scanner_to_the_release(self): with scratch() as folder: repo, root = Path(folder) / 'repo', Path(folder) / 'root' built = self.release(repo, 'abc1234') installed = root / 'releases/abc1234' installed.mkdir(parents=True) for name in ('equipo-runner', 'equipo-tool-proxy', 'gitleaks'): (installed / name).write_bytes((built / name).read_bytes()) with patch.multiple(staging, REPO=repo, ROOT=root), patch.object(staging, 'run', return_value=''): self.assertIn('gitleaks', staging.provenance('abc1234')) (installed / 'gitleaks').write_bytes(b'another scanner') with self.assertRaisesRegex(RuntimeError, 'gitleaks'): staging.provenance('abc1234') (installed / 'gitleaks').unlink() with self.assertRaisesRegex(RuntimeError, 'gitleaks'): staging.provenance('abc1234') class CredentialTest(unittest.TestCase): """The owner's runner merges into repositories it creates for jobs.""" API, GIT = 'agent-bearer-not-for-print', 'agent-pat-not-for-print' def production(self, folder, repositories): path = Path(folder) / 'prod/amadan.json' staging.private(path, json.dumps({'agent': 'equipo-docs-t1~paul@example.com', 'repositories': repositories})) prod = Path(folder) / 'prod/service.env' prod.write_text(f'EQUIPO_AMADAN_CREDENTIAL_PATH="{path}"\nEQUIPO_GIT_PATH="/usr/bin/git"\n') return path, prod def test_owner_runner_gets_an_agent_wide_credential_and_production_keeps_its_own(self): with scratch() as folder: shared = {'api': self.API, 'git': self.GIT} source, prod = self.production(folder, {'amadan.net/oficina/equipo': shared, 'amadan.net/oficina/docs': shared}) before = source.read_bytes() root, home = Path(folder) / 'root', Path(folder) / 'home' release = Path(folder) / 'release' release.mkdir() for r in (root, root / 'suite'): (r / 'state').mkdir(parents=True) (r / 'state/credentials.json').write_text('{}') out = [] with patch.multiple(staging, ROOT=root, SUITE_ROOT=root / 'suite', PROD_ENV=prod), \ patch.object(staging.Path, 'home', return_value=home), \ patch.object(staging, 'run', return_value=''), \ patch.object(staging, 'instance_id', return_value='INSTANCE'), \ patch.object(staging, 'claude_a', return_value={'local_id': 'claude-a'}), \ patch.object(staging, 'added_in_app', return_value=[]), \ patch.object(staging, 'sha256', return_value='digest'), \ patch('builtins.print', side_effect=lambda *a, **k: out.append(' '.join(map(str, a)))): staging.install('abc1234', release, root, staging.UNIT, 'owner@example.com', root / 'cookie', create=True) staging.install('abc1234', release, root / 'suite', staging.SUITE_UNIT, staging.SUITE, root / 'suite/cookie', create=False) owner = Path(staging.read_env(root / 'service.env')['EQUIPO_AMADAN_CREDENTIAL_PATH']) self.assertEqual(owner, root / 'amadan.json') self.assertEqual(owner.stat().st_mode & 0o777, 0o600) self.assertEqual(json.loads(owner.read_text()), {'agent': 'equipo-docs-t1~paul@example.com', 'api': self.API, 'git': self.GIT}) self.assertEqual(staging.read_env(root / 'suite/service.env')['EQUIPO_AMADAN_CREDENTIAL_PATH'], str(source)) self.assertEqual(source.read_bytes(), before) self.assertFalse(any(self.API in line or self.GIT in line for line in out)) def test_refuses_without_one_bearer_and_one_git_pat(self): for name, repositories in (('two bearers', {'amadan.net/a/b': {'api': 'one', 'git': 'pat'}, 'amadan.net/a/c': {'api': 'two', 'git': 'pat'}}), ('legacy, no git', {'amadan.net/a/b': 'bearer-only'}), ('empty', {})): with self.subTest(name), scratch() as folder: source, _ = self.production(folder, repositories) root = Path(folder) / 'root' with patch.object(staging, 'ROOT', root): with self.assertRaisesRegex(RuntimeError, 'agent bearer'): staging.agent_credential(source) self.assertFalse((root / 'amadan.json').exists()) def test_keeps_an_agent_wide_entry_production_already_has(self): with scratch() as folder: source = Path(folder) / 'amadan.json' staging.private(source, json.dumps({'agent': 'a~p@example.com', 'api': self.API, 'git': self.GIT, 'repositories': {'amadan.net/a/b': {'api': 'old', 'git': 'old'}}})) root = Path(folder) / 'root' with patch.object(staging, 'ROOT', root): written = staging.agent_credential(source) self.assertEqual(json.loads(written.read_text()), {'agent': 'a~p@example.com', 'api': self.API, 'git': self.GIT}) if __name__ == '__main__': unittest.main()