From 16c2c05f1cca9dbba83c10b373827e2940610b47 Mon Sep 17 00:00:00 2001 From: Aster Date: Sun, 15 Nov 2026 23:24:27 -0600 Subject: [PATCH] test(claimant): isolate Slice 1 harness from live state (#8742) --- pm-stack/opencode-claimant/Makefile | 21 +- .../opencode-claimant/run_hermetic_tests.py | 56 +++++ .../opencode-claimant/test_harness_safety.py | 77 ++++++ pm-stack/opencode-claimant/test_slice1.sh | 121 +-------- pm-stack/opencode-claimant/verify_slice1.sh | 234 +----------------- 5 files changed, 158 insertions(+), 351 deletions(-) create mode 100644 pm-stack/opencode-claimant/run_hermetic_tests.py create mode 100644 pm-stack/opencode-claimant/test_harness_safety.py diff --git a/pm-stack/opencode-claimant/Makefile b/pm-stack/opencode-claimant/Makefile index 26b440cd88..0f6d1b66ec 100644 --- a/pm-stack/opencode-claimant/Makefile +++ b/pm-stack/opencode-claimant/Makefile @@ -1,6 +1,6 @@ # Makefile for OpenCode Claimant/Executor -.PHONY: all install clean test-poll test-claimant shadow live shadow-mode test-requirements +.PHONY: all install clean test-poll test-claimant shadow live shadow-mode test-requirements test test-harness all: claimant.py poll.py chmod +x claimant.py poll.py @@ -14,15 +14,14 @@ clean: rm -f ~/.local/state/opencode-claimant/*.lock @echo "Lock files cleaned" -test-poll: - @echo "Testing poll.py functions..." - python3 poll.py --candidates - python3 poll.py --cap-only - python3 poll.py --stuck-bound +# All test aliases are offline; none invokes an operator entry point. +test-poll test-claimant test-requirements: test -test-claimant: - @echo "Testing claimant execution..." - python3 claimant.py --dry-run +test: + python3 -I run_hermetic_tests.py + +test-harness: + python3 -I test_harness_safety.py shadow: @echo "Running in SHADOW mode..." @@ -37,7 +36,3 @@ shadow-mode: @echo "Setting mode to SHADOW..." echo "shadow" > ~/.local/state/opencode-claimant/mode @echo "Mode set to shadow" - -test-requirements: - @echo "Running requirements test suite..." - python3 -c "import sys; sys.path.insert(0, '.'); from claimant import QUEUES, poll; print('✅ Constants verified'); print(f' QUEUES: {len(QUEUES)} queues'); print(f' CONCURRENCY_CAP: {poll.CAP}')" diff --git a/pm-stack/opencode-claimant/run_hermetic_tests.py b/pm-stack/opencode-claimant/run_hermetic_tests.py new file mode 100644 index 0000000000..478d5b515b --- /dev/null +++ b/pm-stack/opencode-claimant/run_hermetic_tests.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Offline claimant/poll tests (#8742). No arguments, no live smoke mode. + +Oracle: existing mocked unit suites, plus explicit fail-closed I/O guards. +The guard is process-local and cannot affect an operator's running claimant. +""" +import sys + +if len(sys.argv) != 1: + print("usage: run_hermetic_tests.py (no arguments)", file=sys.stderr) + raise SystemExit(2) + +import importlib.util +import os +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +sys.dont_write_bytecode = True +violations = [] + + +def guard(event, args): + if event in {"subprocess.Popen", "os.system", "os.exec", "os.posix_spawn", "os.fork"} or event.startswith("socket."): + violations.append(event) + raise RuntimeError("offline test attempted external I/O: " + event) + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +with tempfile.TemporaryDirectory(prefix="claimant-offline-") as tmp: + # Reset all inherited service/credential overrides before module imports. + os.environ.clear() + os.environ.update(HOME=tmp, XDG_STATE_HOME=tmp + "/state", XDG_CONFIG_HOME=tmp + "/config", + OPENCODE_AUTH_FILE=tmp + "/absent-auth.json") + # Tests using tempfile also write inside the disposable tree. + tempfile.tempdir = tmp + sys.addaudithook(guard) + suite = unittest.TestSuite() + for name, path in (("offline_claimant", ROOT / "test_claimant.py"), + ("offline_poll", ROOT / "test_poll.py"), + ("offline_mode", ROOT / "test" / "test_claimant.py")): + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(load(name, path))) + result = unittest.TextTestRunner(verbosity=2).run(suite) + # Even code that catches the guard exception cannot turn an attempted + # real queue/server call into a successful offline check. + if violations: + print("Forbidden external I/O attempted: " + ", ".join(violations), file=sys.stderr) + status = 0 if result.wasSuccessful() and not violations else 1 +raise SystemExit(status) diff --git a/pm-stack/opencode-claimant/test_harness_safety.py b/pm-stack/opencode-claimant/test_harness_safety.py new file mode 100644 index 0000000000..ea215d82ec --- /dev/null +++ b/pm-stack/opencode-claimant/test_harness_safety.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Black-box regression tests for the offline harness, never the live claimant.""" +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parent + + +class HarnessSafetyTests(unittest.TestCase): + def run_harness(self, script, arguments=(), injected_test=None): + with tempfile.TemporaryDirectory(prefix="claimant-harness-check-") as tmp: + base = Path(tmp) + home = base / "operator-home" + mode = home / ".local/state/opencode-claimant/mode" + mode.parent.mkdir(parents=True) + mode.write_bytes(b"live\noperator-sentinel\x00") + before = {str(p.relative_to(home)): p.read_bytes() + for p in home.rglob("*") if p.is_file()} + source = ROOT + if injected_test is not None: + source = base / "fixture" + source.mkdir() + for name in (script, "run_hermetic_tests.py"): + shutil.copyfile(ROOT / name, source / name) + (source / "test").mkdir() + (source / "test_claimant.py").write_text(injected_test) + (source / "test_poll.py").write_text("") + (source / "test/test_claimant.py").write_text("") + env = dict(os.environ, HOME=str(home), + XDG_STATE_HOME=str(home / "state"), + OPENCODE_AUTH_FILE=str(home / "auth-must-not-be-read"), + OPENCODE_URL="http://127.0.0.1:1") + proc = subprocess.run(["bash", str(source / script), *arguments], + env=env, capture_output=True, text=True, timeout=30) + after = {str(p.relative_to(home)): p.read_bytes() + for p in home.rglob("*") if p.is_file()} + self.assertEqual(before, after, proc.stderr) + return proc + + def test_existing_suites_pass_and_leave_operator_home_unchanged(self): + for script in ("test_slice1.sh", "verify_slice1.sh"): + with self.subTest(script=script): + result = self.run_harness(script) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Ran ", result.stderr) + + def test_arguments_rejected_before_tests(self): + for script in ("test_slice1.sh", "verify_slice1.sh"): + result = self.run_harness(script, ("--live",)) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertNotIn("Ran ", result.stderr) + + def test_test_failure_preserves_operator_home(self): + fixture = "import unittest\nclass Failure(unittest.TestCase):\n def test_fail(self): self.fail('forced failure')\n" + for script in ("test_slice1.sh", "verify_slice1.sh"): + result = self.run_harness(script, injected_test=fixture) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("forced failure", result.stderr) + + def test_caught_network_or_process_attempt_still_fails_runner(self): + for statement in ("import socket; socket.socket()", + "import subprocess; subprocess.run(['must-not-execute'])"): + fixture = ("import unittest\nclass Guard(unittest.TestCase):\n" + " def test_attempt(self):\n try:\n " + statement + + "\n except RuntimeError: pass\n") + result = self.run_harness("test_slice1.sh", injected_test=fixture) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("Forbidden external I/O attempted", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/pm-stack/opencode-claimant/test_slice1.sh b/pm-stack/opencode-claimant/test_slice1.sh index 60d1cd5841..03135df3f8 100755 --- a/pm-stack/opencode-claimant/test_slice1.sh +++ b/pm-stack/opencode-claimant/test_slice1.sh @@ -1,112 +1,9 @@ -#!/bin/bash -# Simple test to verify slice 1 implementation works correctly - -set -e - -echo "=== Testing OpenCode Lane Claimant/Executor - Slice 1 ===" -echo - -# Test 1: Run in shadow mode (should work without errors) -echo "Test 1: Running in shadow mode..." -python3 pm-stack/opencode-claimant/claimant.py -if [ $? -eq 0 ]; then - echo "✓ Shadow mode execution successful" -else - echo "✗ Shadow mode execution failed" - exit 1 -fi -echo - -# Test 2: Verify fire log was created -echo "Test 2: Verifying fire log creation..." -if [ -f ~/.local/state/opencode-claimant/fires.jsonl ]; then - echo "✓ Fire log created at ~/.local/state/opencode-claimant/fires.jsonl" - - # Show last fire entry - echo "Last fire entry:" - tail -1 ~/.local/state/opencode-claimant/fires.jsonl | python3 -m json.tool || echo "(JSON formatting failed, but file exists)" -else - echo "✗ Fire log not created" - exit 1 -fi -echo - -# Test 3: Test poll.py output -echo "Test 3: Testing poll.py output..." -python3 pm-stack/opencode-claimant/poll.py >/tmp/poll_output.json 2>/dev/null -if [ $? -eq 0 ]; then - echo "✓ poll.py executed successfully" - - # Check for required fields (poll.py outputs to stdout, warnings to stderr) - python3 <<'EOF' -import json -with open('/tmp/poll_output.json') as f: - data = json.load(f) - assert 'queues' in data, 'Missing queues field' - assert 'candidates' in data, 'Missing candidates field' - assert 'stuck_bound' in data, 'Missing stuck_bound field' - assert 'cap_room' in data, 'Missing cap_room field' - assert 'live_root_sessions' in data, 'Missing live_root_sessions field' - assert 'active_root_sessions' in data, 'Missing active_root_sessions field' - print('✓ poll.py output contains all required fields') -EOF -else - echo "✗ poll.py execution failed" - exit 1 -fi -echo - -# Test 4: Test mode switching -echo "Test 4: Testing mode switching..." - -# Test shadow mode -echo "shadow" >~/.local/state/opencode-claimant/mode -python3 pm-stack/opencode-claimant/claimant.py >/dev/null 2>&1 -if [ $? -eq 0 ]; then - echo "✓ Explicit shadow mode works" -else - echo "✗ Explicit shadow mode failed" - exit 1 -fi - -# Test live mode -echo "live" >~/.local/state/opencode-claimant/mode -python3 pm-stack/opencode-claimant/claimant.py >/dev/null 2>&1 -if [ $? -eq 0 ]; then - echo "✓ Explicit live mode works" -else - echo "✗ Explicit live mode failed" - exit 1 -fi - -# Clean up -rm -f ~/.local/state/opencode-claimant/mode - -echo - -# Test 5: Verify constants -echo "Test 5: Verifying constants..." -if grep -q "CONCURRENCY_CAP = 36" pm-stack/opencode-claimant/claimant.py; then - echo "✓ CONCURRENCY_CAP = 36" -else - echo "✗ CONCURRENCY_CAP not set correctly" - exit 1 -fi - -if grep -q "LAUNCHED_BY_RECOVERY_ZERO_MESSAGE" pm-stack/opencode-claimant/claimant.py; then - echo "✓ Zero-message recovery constant defined" -else - echo "✗ Zero-message recovery constant missing" - exit 1 -fi - -if grep -q "LAUNCHED_BY_RECOVERY_GONE_SESSION" pm-stack/opencode-claimant/claimant.py; then - echo "✓ Gone-session recovery constant defined" -else - echo "✗ Gone-session recovery constant missing" - exit 1 -fi - -echo -echo "=== All Tests Passed! ===" -echo "OpenCode lane claimant/executor slice 1 is working correctly." +#!/usr/bin/env bash +# Offline compatibility entry point (#8742). No arguments or live smoke mode. +set -euo pipefail +if (( $# != 0 )); then + printf 'usage: %s (no arguments)\n' "${0##*/}" >&2 + exit 2 +fi +script_dir=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +exec python3 -I "$script_dir/run_hermetic_tests.py" diff --git a/pm-stack/opencode-claimant/verify_slice1.sh b/pm-stack/opencode-claimant/verify_slice1.sh index 72791c2659..03135df3f8 100755 --- a/pm-stack/opencode-claimant/verify_slice1.sh +++ b/pm-stack/opencode-claimant/verify_slice1.sh @@ -1,227 +1,9 @@ -#!/bin/bash -# Verification script for OpenCode lane claimant/executor slice 1 (#3026) - -set -e - -echo "=== OpenCode Lane Claimant/Executor - Slice 1 Verification ===" -echo - -# Colors -GREEN='\033[0;32m' -RED='\033[0;31m' -NC='\033[0m' # No Color - -success_count=0 -total_checks=0 - -check() { - total_checks=$((total_checks + 1)) - if [ $? -eq 0 ]; then - echo -e "${GREEN}✓${NC} $1" - success_count=$((success_count + 1)) - return 0 - else - echo -e "${RED}✗${NC} $1" - return 1 - fi -} - -echo "1. File Structure Verification" -echo "-------------------------------" - -[ -f "pm-stack/opencode-claimant/claimant.py" ] && check "claimant.py exists" || echo "✗ claimant.py missing" -[ -f "pm-stack/opencode-claimant/poll.py" ] && check "poll.py exists" || echo "✗ poll.py missing" -[ -f "pm-stack/opencode-claimant/README.md" ] && check "README.md exists" || echo "✗ README.md missing" -[ -f "pm-stack/opencode-claimant/Makefile" ] && check "Makefile exists" || echo "✗ Makefile missing" - -echo -echo "2. Script Executability" -echo "-----------------------" - -chmod +x pm-stack/opencode-claimant/claimant.py 2>/dev/null -chmod +x pm-stack/opencode-claimant/poll.py 2>/dev/null -[ -x "pm-stack/opencode-claimant/claimant.py" ] && check "claimant.py is executable" || echo "✗ claimant.py not executable" -[ -x "pm-stack/opencode-claimant/poll.py" ] && check "poll.py is executable" || echo "✗ poll.py not executable" - -echo -echo "3. Mode File Handling" -echo "---------------------" - -# Test shadow mode (default) -echo "test" >~/.local/state/opencode-claimant/mode -python3 pm-stack/opencode-claimant/claimant.py >/dev/null 2>&1 -[ $? -eq 0 ] && check "Shadow mode works (no mutations)" || echo "✗ Shadow mode failed" - -# Test live mode -echo "live" >~/.local/state/opencode-claimant/mode -python3 pm-stack/opencode-claimant/claimant.py >/dev/null 2>&1 -[ $? -eq 0 ] && check "Live mode works (no errors)" || echo "✗ Live mode failed" - -# Clean up -rm -f ~/.local/state/opencode-claimant/mode - -echo -echo "4. Poll.py Functionality" -echo "-----------------------" - -# Test poll.py output format -output=$(python3 pm-stack/opencode-claimant/poll.py 2>/dev/null) -echo "$output" | grep -q "queues" && check "poll.py outputs 'queues' field" || echo "✗ poll.py missing 'queues' field" -echo "$output" | grep -q "candidates" && check "poll.py outputs 'candidates' field" || echo "✗ poll.py missing 'candidates' field" -echo "$output" | grep -q "stuck_bound" && check "poll.py outputs 'stuck_bound' field" || echo "✗ poll.py missing 'stuck_bound' field" -echo "$output" | grep -q "cap_room" && check "poll.py outputs 'cap_room' field" || echo "✗ poll.py missing 'cap_room' field" -echo "$output" | grep -q "live_root_sessions" && check "poll.py outputs 'live_root_sessions' field" || echo "✗ poll.py missing 'live_root_sessions' field" -echo "$output" | grep -q "active_root_sessions" && check "poll.py outputs 'active_root_sessions' field" || echo "✗ poll.py missing 'active_root_sessions' field" - -# Test JSON validity -python3 </dev/null 2>&1 -[ -f ~/.local/state/opencode-claimant/fires.jsonl ] && check "Fire log created" || echo "✗ Fire log not created" - -# Check fire log format -if [ -f ~/.local/state/opencode-claimant/fires.jsonl ]; then - last_line=$(tail -1 ~/.local/state/opencode-claimant/fires.jsonl) - echo "$last_line" | grep -q "timestamp" && check "Fire log contains 'timestamp'" || echo "✗ Fire log missing 'timestamp'" - echo "$last_line" | grep -q "mode" && check "Fire log contains 'mode'" || echo "✗ Fire log missing 'mode'" - echo "$last_line" | grep -q "candidates_seen" && check "Fire log contains 'candidates_seen'" || echo "✗ Fire log missing 'candidates_seen'" - echo "$last_line" | grep -q "sessions_launched" && check "Fire log contains 'sessions_launched'" || echo "✗ Fire log missing 'sessions_launched'" - echo "$last_line" | grep -q "cap_room" && check "Fire log contains 'cap_room'" || echo "✗ Fire log missing 'cap_room'" - echo "$last_line" | grep -q "skips" && check "Fire log contains 'skips'" || echo "✗ Fire log missing 'skips'" -fi - -echo -echo "6. Constants Verification" -echo "-------------------------" - -# Check CONCURRENCY_CAP -grep -q "CONCURRENCY_CAP = 36" pm-stack/opencode-claimant/claimant.py && check "CONCURRENCY_CAP = 36" || echo "✗ CONCURRENCY_CAP not set to 36" - -# Check recovery launched_by values -grep -q "LAUNCHED_BY_RECOVERY_ZERO_MESSAGE" pm-stack/opencode-claimant/claimant.py && check "Zero-message recovery constant defined" || echo "✗ Zero-message recovery constant missing" -grep -q "LAUNCHED_BY_RECOVERY_GONE_SESSION" pm-stack/opencode-claimant/claimant.py && check "Gone-session recovery constant defined" || echo "✗ Gone-session recovery constant missing" - -# Check QUEUES -grep -q "repo-health-code-pilot" pm-stack/opencode-claimant/claimant.py && check "All four queues defined" || echo "✗ Queue definitions missing" - -echo -echo "7. Step Implementation Verification" -echo "-----------------------------------" - -# Check supervision step -grep -q "def supervision_step" pm-stack/opencode-claimant/claimant.py && check "Supervision step implemented" || echo "✗ Supervision step missing" - -# Check gate step -grep -q "def gate_step" pm-stack/opencode-claimant/claimant.py && check "Gate step implemented" || echo "✗ Gate step missing" - -# Check cap step -grep -q "def cap_step" pm-stack/opencode-claimant/claimant.py && check "Cap step implemented" || echo "✗ Cap step missing" - -# Check launch step -grep -q "def launch_step" pm-stack/opencode-claimant/claimant.py && check "Launch step implemented" || echo "✗ Launch step missing" - -# Check log_fire function -grep -q "def log_fire" pm-stack/opencode-claimant/claimant.py && check "Logging function implemented" || echo "✗ Logging function missing" - -echo -echo "8. Key Features Verification" -echo "-----------------------------" - -# Check session creation with correct shape -grep -q '"location": {' pm-stack/opencode-claimant/claimant.py && check "Session creation uses correct location shape" || echo "✗ Session location shape incorrect" - -grep -q '"model": {' pm-stack/opencode-claimant/claimant.py && check "Session creation uses correct model shape" || echo "✗ Session model shape incorrect" - -# Check atomic bind operation -grep -q "bind_result = subprocess.run" pm-stack/opencode-claimant/claimant.py && check "Atomic bind operation implemented" || echo "✗ Atomic bind operation missing" - -# Check recovery operations -grep -q "opencode-claimant-recovery:zero-message-deleted" pm-stack/opencode-claimant/claimant.py && check "Zero-message recovery implemented" || echo "✗ Zero-message recovery missing" -grep -q "opencode-claimant-recovery:gone-session" pm-stack/opencode-claimant/claimant.py && check "Gone-session recovery implemented" || echo "✗ Gone-session recovery missing" - -# Check session location verification -grep -q 'location.*directory' pm-stack/opencode-claimant/claimant.py && check "Session location verification implemented" || echo "✗ Session location verification missing" - -# Check cap room calculation -grep -q "cap_room" pm-stack/opencode-claimant/claimant.py && check "Cap room calculation implemented" || echo "✗ Cap room calculation missing" - -echo -echo "9. Documentation Verification" -echo "------------------------------" - -[ -s "pm-stack/opencode-claimant/README.md" ] && check "README.md exists and is not empty" || echo "✗ README.md missing or empty" -[ -s "pm-stack/opencode-claimant/SLICE1_COMPLETION_REPORT.md" ] && check "Slice 1 completion report exists" || echo "✗ Completion report missing" - -echo -echo "10. Mode Handling" -echo "----------------" - -# Test default mode (missing file) -rm -f ~/.local/state/opencode-claimant/mode -output=$(python3 -c " -import sys -sys.path.insert(0, 'pm-stack/opencode-claimant') -from claimant import read_mode -mode = read_mode() -print(mode) -") -[ "$output" = "shadow" ] && check "Default mode is 'shadow'" || echo "✗ Default mode not 'shadow' (got: $output)" - -# Test explicit shadow mode -echo "shadow" >~/.local/state/opencode-claimant/mode -output=$(python3 -c " -import sys -sys.path.insert(0, 'pm-stack/opencode-claimant') -from claimant import read_mode -mode = read_mode() -print(mode) -") -[ "$output" = "shadow" ] && check "Explicit shadow mode works" || echo "✗ Explicit shadow mode failed (got: $output)" - -# Test explicit live mode -echo "live" >~/.local/state/opencode-claimant/mode -output=$(python3 -c " -import sys -sys.path.insert(0, 'pm-stack/opencode-claimant') -from claimant import read_mode -mode = read_mode() -print(mode) -") -[ "$output" = "live" ] && check "Explicit live mode works" || echo "✗ Explicit live mode failed (got: $output)" - -# Clean up -rm -f ~/.local/state/opencode-claimant/mode - -echo -echo "==========================================" -echo "Verification Complete: $success_count / $total_checks checks passed" -echo "==========================================" - -if [ $success_count -eq $total_checks ]; then - echo -e "${GREEN}✓ All checks passed! Slice 1 implementation is complete.${NC}" - exit 0 -else - echo -e "${RED}✗ Some checks failed. Please review the output above.${NC}" - exit 1 +#!/usr/bin/env bash +# Offline compatibility entry point (#8742). No arguments or live smoke mode. +set -euo pipefail +if (( $# != 0 )); then + printf 'usage: %s (no arguments)\n' "${0##*/}" >&2 + exit 2 fi +script_dir=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +exec python3 -I "$script_dir/run_hermetic_tests.py"