Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 8 additions & 13 deletions pm-stack/opencode-claimant/Makefile
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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..."
Expand All @@ -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}')"
56 changes: 56 additions & 0 deletions pm-stack/opencode-claimant/run_hermetic_tests.py
Original file line number Diff line number Diff line change
@@ -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)
77 changes: 77 additions & 0 deletions pm-stack/opencode-claimant/test_harness_safety.py
Original file line number Diff line number Diff line change
@@ -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()
121 changes: 9 additions & 112 deletions pm-stack/opencode-claimant/test_slice1.sh
Original file line number Diff line number Diff line change
@@ -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"
Loading