The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Exercise the ARM Harness workspace from fresh Fedora and Asahi fixtures (#765)
Deef519261d1881
diff --git a/.github/workflows/os-arm-session.yml b/.github/workflows/os-arm-session.ymlnew file mode 100644index 000000000..c04a8fb4c--- /dev/null+++ b/.github/workflows/os-arm-session.yml@@ -0,0 +1,88 @@+name: Harness OS ARM graphical session++on:+ workflow_dispatch:+ inputs:+ prepare_only:+ description: 'Prepare a private fixture for accelerated local acceptance; does not claim a passing VM test'+ type: boolean+ default: true+ push:+ branches: ['os-polish/arm-graphical']+ paths:+ - 'os/tests/arm_session*'+ - 'os/tests/test_arm_session.py'+ - 'os/tests/arm-session.lock.json'+ - '.github/workflows/os-arm-session.yml'++permissions:+ contents: read++concurrency:+ group: harness-arm-session-${{ github.ref }}+ cancel-in-progress: false++jobs:+ session:+ runs-on: ubuntu-24.04-arm+ timeout-minutes: 45+ steps:+ - uses: actions/checkout@v7+ with:+ fetch-depth: 0+ - uses: actions/setup-node@v7+ with:+ node-version: 22.23.2+ cache: npm+ cache-dependency-path: cli/package-lock.json+ - uses: dtolnay/rust-toolchain@stable+ with:+ targets: aarch64-unknown-linux-musl+ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2+ with:+ workspaces: tui+ shared-key: tui-aarch64-unknown-linux-musl+ cache-bin: false+ - name: Boot tools and portable OS checks+ run: |+ df -h . "$RUNNER_TEMP"+ sudo apt-get update -qq+ sudo apt-get install -y --no-install-recommends musl-tools qemu-system-arm \+ e2fsprogs rpm libarchive-tools zstd gnupg python3-pil tesseract-ocr+ if [ -c /dev/kvm ]; then sudo chown "$USER" /dev/kvm; fi+ make -C os check+ - name: Build the exact native Harness runtime+ run: bash os/tools/build-runtime.sh+ - name: Prepare the fresh fixture or exercise the full graphical session+ env:+ PREPARE_ONLY: ${{ github.event_name == 'push' || inputs.prepare_only }}+ run: |+ args=()+ if [[ "$PREPARE_ONLY" == true ]]; then args+=(--prepare-only); fi+ python3 os/tests/arm_session.py --runtime os/work/runtime \+ --output os/test-results/arm-session "${args[@]}"+ - name: Retain graphical session evidence only+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: harness-arm-graphical-session+ path: |+ os/work/runtime/source.json+ os/test-results/arm-session/receipt.json+ os/test-results/arm-session/host.log+ os/test-results/arm-session/packages.tsv+ os/test-results/arm-session/agent-lock.json+ os/test-results/arm-session/first-boot/+ os/test-results/arm-session/second-boot/+ if-no-files-found: error+ retention-days: 14+ compression-level: 6+ - name: Retain the private fixture for accelerated acceptance+ if: success() && (github.event_name == 'push' || inputs.prepare_only)+ uses: actions/upload-artifact@v6+ with:+ name: harness-arm-session-fixture+ path: os/test-results/arm-session/fixture/+ if-no-files-found: error+ retention-days: 3+ compression-level: 0diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.mdindex 58c34c056..82b64e9e7 100644--- a/os/DEVELOPMENT.md+++ b/os/DEVELOPMENT.md@@ -531,6 +531,70 @@ test or hardware installation. It does not test Apple firmware, storage, GPU,audio, Wi-Fi or Raspberry Pi boot. Keep ARM payloads out of the PC installer andupdate feed until each platform has its own packaging and installation path.+### Reproducible ARM graphical session++The **Harness OS ARM graphical session** workflow assembles a fresh Fedora Minimal+userspace and boots the shared labwc/foot/Harness session under the signed 16 KiB+Asahi kernel. This extends the console-only kernel check above; it is a private+VM prototype, not an Apple Silicon installer or a supported hardware image.++`tests/arm-session.lock.json` pins the Fedora container and extra graphical kernel+modules. The builder verifies kernel package signatures and hashes, checks the+exact clean ARM runtime, installs signed Fedora packages without weak dependencies,+and records their versions and the upstream-default OpenCode lockfile. Fedora+repositories remain mutable; this is not a claim of an immutable package snapshot.++The tracked fixture accounts for Fedora's browser executable and labwc action+name. It selects shared session files explicitly and excludes the PC installer,+update timer, pacman configuration and x86 driver hooks. Its empty-password account+and root console exist only on the private regular-file disk and local QEMU socket;+no host block device, SSH service or public listener is exposed. These test settings+must never enter a hardware image.++The acceptance path starts offline, opens a terminal with actual Super+t input,+then connects and waits for the default agent and two terminal panes. It asks+OpenCode to create a Python program and HTML counter, independently executes the+program, clicks the counter in sandboxed native Chromium, and returns to the same+agent with Super+b. A second cold boot must accept keyboard input and preserve+the project's exact bytes. Receipts, framebuffer captures and logs survive failures;+the writable private disk/container are removed. A passing run establishes this VM sequence+only, not hardware installation, GPU acceleration, suspend or Fedora recovery.++```sh+python3 os/tests/arm_session.py --runtime os/work/runtime \+ --output os/test-results/arm-session+```++Use a native ARM Linux runner with the tools listed in `os-arm-session.yml`.+The two recorded hosted ARM runs lacked KVM; the second TCG run reached Wi-Fi and+accepted real keyboard input, but failed with a blank OpenCode pane. That failure+is retained and is not graphical acceptance.++The workflow defaults to `prepare_only=true`, which uploads an unbooted, compressed+private test disk and kernel with their hashes and exact source identity. Its+receipt says **prepared**, never **passed**. Download `harness-arm-session-fixture`+from that run, check out its exact source commit, and run the unchanged acceptance+on a native ARM Linux machine with KVM or an Apple Silicon Mac with HVF:++```sh+python3 os/tests/arm_session.py --fixture /path/to/harness-arm-session-fixture \+ --output os/test-results/arm-session-local+```++This needs QEMU, zstd, Tesseract and Python with Pillow. The runner verifies both+compressed and decompressed disk hashes, then boots a disposable writable copy.+It records the accelerator, real agent/browser interaction and the second boot.+The prepared fixture has an empty test password and must never be installed on+hardware or published as an OS release. Preparation and acceptance have separate+receipts. Set `prepare_only=false` to exercise the full sequence on the CI runner.+When correcting test assertions, an existing immutable fixture can be selected+explicitly with `--fixture-source FULL_PRODUCER_SHA`. Its hashes are still checked;+the acceptance receipt records the image source and test source separately. This+tests that older image, not product changes in the newer test checkout.++Apple firmware provisioning, physical drivers, platform installation and Fedora+update/recovery integration remain separate work before releasing this port.+## Mac support targetsIntel Macs and Apple Silicon are both intended OS targets. They share the Harnessdiff --git a/os/tests/arm-session.lock.json b/os/tests/arm-session.lock.jsonnew file mode 100644index 000000000..38334c663--- /dev/null+++ b/os/tests/arm-session.lock.json@@ -0,0 +1,10 @@+{+ "schema": 1,+ "scope": "Disposable Fedora graphical session; not an ARM installer or update package",+ "root_image": "registry.fedoraproject.org/fedora-minimal@sha256:481d1f308c3d4c0dc98b9b58613163be04271a137ffeae3d398a8c029c46b259",+ "graphics_modules": {+ "url": "https://packages.redhat.com/api/pulp-content/public-copr/@asahi/kernel/fedora-44-aarch64/Packages/k/kernel-16k-modules-7.1.13-402.asahi.fc44.aarch64.rpm",+ "bytes": 63647565,+ "sha256": "f1ad7d48c66f2d3224d724b2bbff63b2a5da9b1200327d319507725c31ff0b1d"+ }+}diff --git a/os/tests/arm_session.py b/os/tests/arm_session.pynew file mode 100644index 000000000..0c7e49b1f--- /dev/null+++ b/os/tests/arm_session.py@@ -0,0 +1,588 @@+#!/usr/bin/env python3+"""Build and exercise a private Fedora/Asahi graphical VM from tracked inputs.++This is a session prototype, not a board installer or an update artifact. It never+opens a host block device. Every fresh disk belongs to this disposable test.+"""+import argparse+from concurrent.futures import ThreadPoolExecutor+import json+import os+from pathlib import Path+import platform+import re+import select+import shlex+import shutil+import subprocess+import tempfile+import time+import xml.etree.ElementTree as ET++from arm_boot import check_arm_image, digest, download, zboot_payload+from vm import VM++ROOT = Path(__file__).resolve().parents[2]+USER = 'runuser -u me -- env XDG_RUNTIME_DIR=/run/user/1000 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus '+++def frame_contains(output, expected, absent=()):+ expected = [expected] if isinstance(expected, str) else expected+ visible = ' '.join(output.casefold().split())+ return (all(' '.join(word.casefold().split()) in visible for word in expected) and+ not any(word.casefold() in visible for word in absent))+++def runtime_identity(runtime, commit):+ info = json.loads((runtime / 'source.json').read_text())+ if (info.get('dirty') is not False or info.get('source_commit') != commit or+ info.get('architecture') != 'aarch64' or info.get('target') != 'aarch64-unknown-linux-musl'):+ raise ValueError('Use the clean native ARM runtime from this source commit.')+ if set(info.get('files', {})) != {'harness-tui', 'cli.js', 'notify.mjs'}:+ raise ValueError('Runtime is incomplete.')+ for name, identity in info['files'].items():+ path = runtime / name+ if path.is_symlink() or not path.is_file() or path.stat().st_size != identity['bytes'] or digest(path) != identity['sha256']:+ raise ValueError('Runtime checksum mismatch: ' + name)+ with (runtime / 'harness-tui').open('rb') as handle:+ header = handle.read(20)+ if header[:6] != b'\x7fELF\x02\x01' or int.from_bytes(header[18:20], 'little') != 183:+ raise ValueError('The terminal must be a little-endian ARM64 ELF executable.')+ return info+++def stage(runtime, destination, commit):+ info = runtime_identity(runtime, commit)+ # Deliberately select the shared session only. Do not transplant pacman,+ # BIOS/EFI installation, x86 driver hooks, or PC update services into Fedora.+ paths = [+ 'etc/profile.d/harness-os.sh', 'etc/sudoers.d/20-harness-network',+ 'etc/NetworkManager/conf.d/10-dns.conf', 'etc/chromium/policies/managed/harness.json',+ 'etc/skel/projects/AGENTS.md', 'usr/bin/hn', 'usr/bin/harness', 'usr/bin/hn-browser',+ 'usr/share/harness-os/foot.ini', 'usr/share/harness-os/tmux.conf',+ 'usr/share/harness-os/guide.md', 'usr/share/harness-os/AGENTS.md',+ *['usr/share/harness-os/labwc/' + name for name in ['autostart', 'shutdown', 'rc.xml']],+ *['usr/lib/harness-os/' + name for name in+ ['session', 'session-settings.py', 'runtime-path', 'wait-runtime', 'virtio-2d', 'open-wifi']],+ *['usr/lib/systemd/user/' + name for name in+ ['hn-screen.service', 'harness-daemon.service', 'harness-idle.service']],+ ]+ for name in paths:+ target = destination / name+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(ROOT / 'os/root' / name, target)+ for source, name in [+ *[('os/' + name + '.py', 'usr/lib/harness-os/' + name + '.py') for name in+ ['onboarding', 'network', 'projects', 'hardware']],+ ('os/tools/hn-os', 'usr/bin/hn-os'), ('tui/README.md', 'usr/share/harness-os/guide/tui.md'),+ ('LICENSE', 'usr/share/licenses/harness-os/LICENSE'),+ ]:+ target = destination / name+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(ROOT / source, target)+ library = destination / 'usr/lib/harness'+ library.mkdir(parents=True)+ for source, target in [('harness-tui', 'harness-tui'), ('cli.js', 'cli.mjs'), ('notify.mjs', 'notify.mjs')]:+ shutil.copy2(runtime / source, library / target)+ (library / 'hn').symlink_to('harness-tui')+ info['files'] = {p.name: {'bytes': p.stat().st_size, 'sha256': digest(p)}+ for p in library.iterdir() if not p.is_symlink()}+ (destination / 'usr/share/harness-os/runtime.json').write_text(json.dumps(info, indent=2) + '\n')+ (destination / 'usr/lib/systemd/user/harness-os.target').write_text(+ '[Unit]\nDescription=Private ARM Harness session\n'+ 'Wants=hn-screen.service harness-idle.service\nAfter=graphical-session-pre.target\n')+ config = destination / 'usr/share/harness-os/labwc/rc.xml'+ tree = ET.parse(config)+ keyboard = tree.getroot().find('keyboard')+ for binding in list(keyboard.findall('keybind')):+ if binding.get('key') in ['W-i', 'W-u']:+ keyboard.remove(binding)+ for action in tree.findall('.//action'):+ if action.get('name') == 'NextWindowImmediate':+ action.set('name', 'NextWindow') # Fedora's labwc 0.9.6 action name.+ tree.write(config, encoding='unicode')+ browser = destination / 'usr/bin/hn-browser'+ browser.write_text(browser.read_text().replace('/usr/bin/chromium ', '/usr/bin/chromium-browser '))+ tmux = destination / 'usr/share/harness-os/tmux.conf'+ tmux.write_text('\n'.join(line for line in tmux.read_text().splitlines() if not line.startswith('bind U ')) + '\n')+ for directory in ['usr/bin', 'usr/lib/harness-os']:+ for path in (destination / directory).iterdir():+ path.chmod(0o755)+ for name in ['autostart', 'shutdown']:+ (destination / 'usr/share/harness-os/labwc' / name).chmod(0o755)+ (library / 'harness-tui').chmod(0o755)+ (destination / 'etc/sudoers.d/20-harness-network').chmod(0o440)+ return {'runtime': info, 'files': {str(p.relative_to(destination)): digest(p)+ for p in sorted(destination.rglob('*')) if p.is_file() and not p.is_symlink()}}+++class SessionVM(VM):+ def __init__(self, folder, disk, kernel):+ if not disk.is_file() or disk.is_symlink():+ raise ValueError('The private VM disk must be a regular file.')+ self.folder, self.disk, self.kernel = folder, disk, kernel+ folder.mkdir()+ self.control = tempfile.TemporaryDirectory(prefix='hn-arm-session-', dir='/tmp')+ self.control_path = Path(self.control.name)+ self.log = (folder / 'serial.log').open('ab', buffering=0)+ self.stderr = (folder / 'qemu.log').open('ab', buffering=0)+ self.serial = self.qmp = self.qmp_file = self.process = None+ self.boot_count = 0+ self.shell_ready = False++ def start(self, offline=False):+ self.started = time.monotonic()+ self.boot_count += 1+ accelerator = ('hvf' if platform.system() == 'Darwin' and platform.machine() == 'arm64'+ else 'kvm' if os.access('/dev/kvm', os.R_OK | os.W_OK) else 'tcg')+ self.accelerator = accelerator+ cpu = 'host' if accelerator in ['kvm', 'hvf'] else 'cortex-a76'+ args = ['qemu-system-aarch64', '-machine', 'virt,gic-version=3', '-accel', accelerator,+ '-cpu', cpu, '-smp', '2', '-m', '3072', '-nodefaults', '-display', 'none', '-no-reboot',+ '-kernel', str(self.kernel), '-append', 'root=/dev/vda rw console=tty0 console=ttyAMA0 loglevel=3 panic=1',+ '-drive', f'file={self.disk},format=raw,if=none,id=root', '-device', 'virtio-blk-pci,drive=root,serial=HARNESS_ARM_TEST',+ '-device', 'virtio-gpu-pci', '-device', 'virtio-keyboard-pci', '-device', 'virtio-tablet-pci',+ '-netdev', 'user,id=net', '-device', 'virtio-net-pci,netdev=net,id=hnnet,romfile=',+ '-serial', f'unix:{self.control_path / "serial.sock"},server=on,wait=off',+ '-qmp', f'unix:{self.control_path / "qmp.sock"},server=on,wait=off']+ (self.folder / 'command.json').write_text(json.dumps(args, indent=2) + '\n')+ self.process = subprocess.Popen(args, stdout=self.stderr, stderr=self.stderr)+ self.serial = self.connect('serial.sock')+ self.qmp = self.connect('qmp.sock')+ self.qmp.settimeout(10)+ # Keep asynchronous shutdown events on the socket for poweroff(),+ # rather than prefetching them into a buffered response reader.+ self.qmp_file = self.qmp.makefile('rb', buffering=0)+ json.loads(self.qmp_file.readline())+ self.monitor('qmp_capabilities')+ if offline:+ self.monitor('set_link', name='hnnet', up=False)+ self.wait('HARNESS_ARM_CONSOLE> ', timeout=180)+ self.command('stty -echo')+ self.command('test "$(getconf PAGESIZE)" = 16384 && test "$(uname -m)" = aarch64')+ self.shell_ready = True++ def user(self, command, **kwargs):+ return self.command(USER + 'sh -c ' + shlex.quote(command), **kwargs)++ def wait_user(self, command, seconds=45):+ return self.user('for n in $(seq 1 ' + str(seconds * 2) + '); do if ' + command ++ '; then exit 0; fi; sleep .5; done; exit 1', timeout=seconds + 10)++ def frame(self, name, text, seconds=60, absent=()):+ from PIL import Image, ImageOps+ deadline = time.monotonic() + seconds+ while time.monotonic() < deadline:+ self.screenshot(name)+ # Match click_word's treatment of small controls. Preserve the real+ # framebuffer too; OCR must not miss a visibly rendered button just+ # because its native text is close to the border or only 12 px tall.+ ocr_frame = self.folder / (name + '-frame-ocr.png')+ with Image.open(self.folder / (name + '.png')) as frame:+ width, height = frame.size+ readable = ImageOps.invert(frame.convert('L')).resize((width * 2, height * 2))+ ImageOps.expand(readable, border=24, fill=255).save(ocr_frame)+ output = subprocess.check_output(['tesseract', str(ocr_frame), 'stdout', '--psm', '11'],+ text=True, stderr=subprocess.DEVNULL, timeout=15)+ (self.folder / (name + '.txt')).write_text(output)+ if frame_contains(output, text, absent):+ return+ time.sleep(1)+ raise TimeoutError('Expected visible screen was not rendered: ' + repr(text))++ def keyboard(self, name):+ before, _ = self.user('hn display-message -p "#{pane_id}"')+ old = re.search(r'%\d+', before)+ if not old:+ raise RuntimeError('No current pane before keyboard probe')+ self.keys('meta_l', 't')+ self.wait_user('test "$(hn display-message -p "#{pane_id}")" != ' + shlex.quote(old[0]) ++ ' && hn capture-pane -p | grep -Eq ' + shlex.quote(r'^\[me@harness [^]]*\]\$'))+ # Separate words stay legible to OCR in narrow restored panes; the+ # shell capture still requires the exact independently typed line.+ marker = 'arm ' + name.replace('-', ' ') + ' ready'+ self.type_probe('echo ' + marker)+ self.keys('ret')+ self.wait_user('hn capture-pane -p | grep -Fx ' + shlex.quote(marker))+ self.frame(name, marker)+ self.keys('ctrl', 'd')++ def poweroff(self, timeout=60):+ started = time.monotonic()+ report = {'status': 'waiting', 'events': []}+ streams = {self.serial: 'serial', self.qmp: 'qmp'}+ pending = b''+ try:+ # The test console may terminate before printing a command result.+ # Require the guest's actual shutdown event and clean QEMU exit.+ self.send('sync; systemctl poweroff --no-block\n')+ while True:+ remaining = timeout - (time.monotonic() - started)+ exited = self.process.poll() is not None+ if remaining <= 0 and not exited:+ raise TimeoutError('Guest poweroff did not finish; see shutdown.json and serial.log')+ # Read until EOF after exit too, retaining the final guest event.+ ready, _, _ = select.select(list(streams), [], [], 0 if exited else min(.2, max(0, remaining)))+ if not ready and exited:+ break+ for stream in ready:+ data = stream.recv(65536)+ if not data:+ del streams[stream]+ elif streams[stream] == 'serial':+ self.log.write(data)+ else:+ pending += data+ while b'\n' in pending:+ line, pending = pending.split(b'\n', 1)+ event = json.loads(line)+ report['events'].append(event)+ if self.process.returncode != 0:+ raise RuntimeError('QEMU exited unsuccessfully during guest poweroff')+ if not any(event.get('event') == 'SHUTDOWN' and+ event.get('data', {}).get('guest') is True and+ event['data'].get('reason') == 'guest-shutdown' for event in report['events']):+ raise RuntimeError('QEMU exit lacks a completed guest poweroff event')+ report['status'] = 'passed'+ return report+ except BaseException as error:+ report.update(status='failed', error=str(error))+ raise+ finally:+ report.update(seconds=round(time.monotonic() - started, 3), exit_code=self.process.poll())+ (self.folder / 'shutdown.json').write_text(json.dumps(report, indent=2) + '\n')++ def close(self):+ self.stop()+ self.log.close()+ self.stderr.close()+ self.control.cleanup()+++def exercise(vm, result):+ vm.start(offline=True)+ # Hosted ARM runners may lack KVM. On the first TCG boot the recorded+ # readiness command completed successfully just after the old 100s host+ # deadline. Keep the same condition and visual assertion, with a bounded+ # cold-start allowance; this emulated run is not a boot-speed benchmark.+ vm.wait_user('systemctl --user is-active --quiet hn-screen && hn capture-pane -p | grep -q "Connect to Wi-Fi"', 180)+ vm.frame('01-wifi', 'Connect to Wi-Fi')+ result['first_visible_wifi'] = {'accelerator': vm.accelerator,+ 'seconds_since_boot': round(time.monotonic() - vm.started, 3)}+ vm.keyboard('offline')+ result['checks'].append('Fresh offline boot shows Wi-Fi; Super+t opens a real shell and accepts graphical keyboard input')+ vm.monitor('set_link', name='hnnet', up=True)+ vm.wait_user('test -f ~/.local/state/harness-os/onboarded && pgrep -u 1000 -x opencode >/dev/null', 150)+ vm.wait_user('test "$(hn list-panes -F "#{pane_id}" | wc -l)" -eq 3')+ # The status bar names OpenCode before its input is ready. Require the+ # actual composer, then observe the prompt before submitting it once.+ vm.frame('02-agent', ['OpenCode', 'Ask anything'])+ output, _ = vm.command('pgrep -u 1000 -x opencode | head -1')+ pid = re.search(r'(?m)^\d+\r?$', output)[0].strip()+ output, _ = vm.command('readlink /proc/' + pid + '/cwd')+ match = re.search(r'/home/me/projects/[a-zA-Z0-9._-]+', output)+ if not match:+ raise RuntimeError('Agent did not start in its own projects subfolder')+ project = match[0]+ result['agent_pid'] = int(pid)+ result['project'] = project+ prompt = ('Create hello.py that prints exactly harness arm ready and exits. Also create index.html with title Harness ARM Demo, '+ 'visible text Harness ARM Demo, and exactly one button named Increment. The page displays Count: 0 initially and '+ 'Count: 1 after clicking the button once. Use plain HTML and JavaScript only, no dependencies. Save both files now.')+ vm.user('hn send-keys -l ' + shlex.quote(prompt))+ vm.wait_user('hn capture-pane -p | grep -F ' + shlex.quote('Create hello.py'), 15)+ vm.frame('02-prompt', 'Create hello.py', 15)+ vm.keys('ret')+ files = 'test -s ' + shlex.quote(project + '/hello.py') + ' && test -s ' + shlex.quote(project + '/index.html')+ vm.wait_user(files, 240)+ vm.wait_user('test "$(python3 ' + shlex.quote(project + '/hello.py') + ')" = "harness arm ready"', 30)+ for name in ['hello.py', 'index.html']:+ (vm.folder / name).write_bytes(vm.read_file(project + '/' + name))+ vm.screenshot('03-agent-project')+ result['checks'].append('Upstream-default OpenCode creates Python and HTML; independent Python execution checks the result')+ vm.user('hn-browser ' + shlex.quote('file://' + project + '/index.html'))+ # The agent's transcript contains the same page title and HTML. Wait for+ # the rendered page after Chromium takes focus, not that earlier terminal.+ vm.frame('04-browser', ['Harness ARM Demo', 'Count: 0', 'Increment'], 90, absent=['me@harness'])+ vm.click_word('05-increment', 'Increment')+ vm.frame('06-counter', 'Count: 1', absent=['me@harness'])+ output, _ = vm.command('python3 - <<\'PY\'\nfrom pathlib import Path\n'+ 'renderers=[]\nfor p in Path("/proc").glob("[0-9]*"):\n'+ ' try:\n cmd=(p/"cmdline").read_bytes()\n'+ ' if b"--type=renderer" in cmd and p.stat().st_uid==1000:\n'+ ' status=(p/"status").read_text(); assert "NoNewPrivs:\\t1" in status and "Seccomp:\\t2" in status; '+ 'assert b"--no-sandbox" not in cmd; renderers.append(p.name)\n'+ ' except FileNotFoundError: pass\nassert renderers\nprint(renderers)\nPY\n')+ (vm.folder / 'browser-sandbox.txt').write_text(output)+ vm.keys('meta_l', 'b')+ vm.frame('07-return', 'OpenCode')+ vm.command('kill -0 ' + pid)+ vm.keyboard('after-browser')+ vm.command('kill -0 ' + pid)+ result['checks'].append('Sandboxed native Chromium renders the agent page; mouse click increments it; Super+b returns to the same agent and keyboard works')+ vm.command('uname -r; getconf PAGESIZE; systemd-analyze; df -B1 /')+ result['projects'] = {name: digest(vm.folder / name) for name in ['hello.py', 'index.html']}+ result['first_shutdown'] = vm.poweroff()+++def exercise_reboot(machine, receipt, output):+ machine.start()+ machine.wait_user('systemctl --user is-active --quiet hn-screen && hn list-panes >/dev/null', 120)+ machine.frame('08-restored', 'harness', 90)+ machine.keyboard('reboot')+ for name, expected in receipt['projects'].items():+ data = machine.read_file(receipt['project'] + '/' + name)+ target = output / 'second-boot' / name+ target.write_bytes(data)+ if digest(target) != expected:+ raise ValueError('Project changed across cold boot: ' + name)+ machine.user('test "$(python3 ' + shlex.quote(receipt['project'] + '/hello.py') + ')" = "harness arm ready"')+ receipt['second_shutdown'] = machine.poweroff()+ receipt['checks'].append('Second cold boot reaches Harness, accepts graphical typing and preserves byte-identical working projects')+++def failure_evidence(machine):+ if not machine:+ return+ errors = []+ for collect in [lambda: machine.screenshot('failure'),+ lambda: machine.command('ps -eo pid,ppid,stat,pcpu,pmem,wchan:32,comm; '+ 'journalctl -b --no-pager -n 250; '+ 'cat /home/me/.local/state/harness-os/display.log; '+ 'tail -n 80 /home/me/.local/share/opencode/log/*.log', check=False, timeout=30)]:+ try:+ collect()+ except (OSError, RuntimeError, TimeoutError, ValueError) as error:+ errors.append(str(error))+ if errors:+ (machine.folder / 'diagnostic-errors.json').write_text(json.dumps(errors, indent=2) + '\n')+++def fixture_identity(folder, source):+ """A portable fixture is a fresh test disk, never a hardware installer."""+ manifest = folder / 'manifest.json'+ if manifest.is_symlink() or not manifest.is_file():+ raise ValueError('Missing regular fixture manifest.')+ info = json.loads(manifest.read_text())+ if info.get('schema') != 1 or info.get('status') != 'prepared' or info.get('source_commit') != source:+ raise ValueError('Use a prepared fixture from this exact clean source commit.')+ if set(info.get('artifacts', {})) != {'Image', 'guest.raw.zst'}:+ raise ValueError('The fixture must contain its kernel and compressed private disk.')+ for name, item in info['artifacts'].items():+ path = folder / name+ if (path.is_symlink() or not path.is_file() or path.stat().st_size != item['bytes'] or+ digest(path) != item['sha256']):+ raise ValueError('Fixture checksum mismatch: ' + name)+ disk = info.get('raw_disk', {})+ if disk.get('bytes') != 6 * 1024 ** 3 or not re.fullmatch(r'[a-f0-9]{64}', disk.get('sha256', '')):+ raise ValueError('Unexpected private disk identity.')+ with (folder / 'Image').open('rb') as handle:+ check_arm_image(handle.read(64))+ return info+++def prepare_fixture(disk, image, output, receipt, run):+ folder = output / 'fixture'+ folder.mkdir()+ shutil.copy2(image, folder / 'Image')+ run(['zstd', '-T2', '-3', disk, '-o', folder / 'guest.raw.zst'], timeout=180)+ info = {**receipt, 'schema': 1, 'status': 'prepared',+ 'raw_disk': {'bytes': disk.stat().st_size, 'sha256': digest(disk)},+ 'artifacts': {name: {'bytes': (folder / name).stat().st_size, 'sha256': digest(folder / name)}+ for name in ['Image', 'guest.raw.zst']}}+ (folder / 'manifest.json').write_text(json.dumps(info, indent=2) + '\n')+ fixture_identity(folder, receipt['source_commit'])+ receipt['status'] = 'prepared'+ receipt['fixture'] = info['artifacts']+ print('Fresh private fixture prepared; graphical acceptance has not run', flush=True)+++def run_fixture(folder, output, source, test_source):+ info = fixture_identity(folder, source)+ receipt = {**info, 'status': 'running', 'checks': [], 'started_at_unix': time.time(),+ 'fixture_manifest_sha256': digest(folder / 'manifest.json'), 'test_source_commit': test_source}+ machine = None+ with tempfile.TemporaryDirectory(prefix='harness-arm-acceptance-') as temporary:+ disk = Path(temporary) / 'guest.raw'+ try:+ subprocess.run(['zstd', '-d', '--sparse', str(folder / 'guest.raw.zst'), '-o', str(disk)],+ check=True, timeout=180)+ if disk.stat().st_size != info['raw_disk']['bytes'] or digest(disk) != info['raw_disk']['sha256']:+ raise ValueError('Decompressed disk identity mismatch.')+ machine = SessionVM(output / 'first-boot', disk, folder / 'Image')+ exercise(machine, receipt)+ machine.close()+ machine = SessionVM(output / 'second-boot', disk, folder / 'Image')+ exercise_reboot(machine, receipt, output)+ receipt['status'] = 'passed'+ print('Fresh Fedora/Asahi graphical session and reboot passed', flush=True)+ except BaseException as error:+ receipt.update(status='failed', error=str(error))+ failure_evidence(machine)+ raise+ finally:+ try:+ if machine:+ machine.close()+ except (OSError, RuntimeError) as error:+ receipt.update(status='failed', cleanup_errors=[str(error)])+ raise+ finally:+ receipt['finished_at_unix'] = time.time()+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ inputs = parser.add_mutually_exclusive_group(required=True)+ inputs.add_argument('--runtime', type=Path, help='Build a fresh fixture on native ARM Linux.')+ inputs.add_argument('--fixture', type=Path, help='Exercise an exact-source prepared fixture on ARM Linux or macOS.')+ parser.add_argument('--fixture-source', help='Explicit full source SHA of an older immutable fixture; recorded separately from the test source.')+ parser.add_argument('--prepare-only', action='store_true', help='Prepare a private fixture without claiming acceptance.')+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ if os.geteuid() == 0:+ parser.error('Use an ordinary user.')+ if args.fixture and args.prepare_only:+ parser.error('--prepare-only requires --runtime.')+ if args.fixture_source and (not args.fixture or not re.fullmatch(r'[a-f0-9]{40}', args.fixture_source)):+ parser.error('--fixture-source requires --fixture and its full source SHA.')+ if args.runtime and (platform.system(), platform.machine()) != ('Linux', 'aarch64'):+ parser.error('Build the fixture on a native ARM Linux runner.')+ if args.fixture and (platform.system(), platform.machine()) not in [('Linux', 'aarch64'), ('Darwin', 'arm64')]:+ parser.error('Exercise the fixture on ARM Linux or Apple Silicon macOS.')+ required = ['zstd']+ if args.runtime:+ required += ['docker', 'rpm', 'rpmkeys', 'gpg', 'bsdtar', 'mkfs.ext4', 'sudo']+ if not args.prepare_only:+ required += ['qemu-system-aarch64', 'tesseract']+ from PIL import Image # noqa: F401 — fail before preparing a disk if unavailable.+ for name in required:+ if not shutil.which(name):+ parser.error('Missing tool: ' + name)+ source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()+ if subprocess.check_output(['git', 'status', '--porcelain'], cwd=ROOT, text=True).strip():+ parser.error('Commit the exact source before building a traceable VM.')+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ if args.fixture:+ run_fixture(args.fixture.resolve(), output, args.fixture_source or source, source)+ return+ runtime = args.runtime.resolve()+ runtime_identity(runtime, source)+ work = Path(tempfile.mkdtemp(prefix='harness-arm-session-', dir=os.environ.get('RUNNER_TEMP')))+ container = work.name+ lock = json.loads(Path(__file__).with_name('arm-boot.lock.json').read_text())+ graphical = json.loads(Path(__file__).with_name('arm-session.lock.json').read_text())+ receipt = {'status': 'running', 'source_commit': source, 'scope': 'Private Fedora/Asahi graphical VM only',+ 'started_at_unix': time.time(), 'kernel_inputs': lock, 'session_inputs': graphical, 'checks': [],+ 'limitations': ['No Apple hardware, firmware provisioning or installer', 'No Fedora update/recovery integration',+ 'No OS/runtime release; signed repository package versions are recorded, not snapshot-pinned']}+ log = (output / 'host.log').open('w')+ machine = None++ def run(argv, timeout=120, capture=False, check=True):+ log.write('$ ' + repr([str(a) for a in argv]) + '\n')+ log.flush()+ result = subprocess.run([str(a) for a in argv], timeout=timeout, check=check, text=True,+ stdout=subprocess.PIPE if capture else log, stderr=subprocess.STDOUT if capture else log)+ if capture:+ log.write(result.stdout)+ log.flush()+ return result.stdout+ return result++ try:+ inputs = work / 'inputs'+ inputs.mkdir()+ print('Verify signed 16 KiB kernel and graphical modules', flush=True)+ with ThreadPoolExecutor(max_workers=3) as pool:+ paths = list(pool.map(lambda item: download(item, inputs), [*lock['kernel_packages'], graphical['graphics_modules'], lock['signing_key']]))+ key, packages = paths[-1], paths[:-1]+ gpg_home, rpmdb = work / 'gpg', work / 'rpmdb'+ gpg_home.mkdir(mode=0o700)+ rpmdb.mkdir()+ keys = run(['gpg', '--homedir', gpg_home, '--with-colons', '--show-keys', '--fingerprint', key], capture=True)+ if [line.split(':')[9] for line in keys.splitlines() if line.startswith('fpr:')] != [lock['signing_key']['fingerprint']]:+ raise ValueError('Unexpected kernel signing key')+ run(['rpm', '--dbpath', rpmdb, '--initdb'])+ run(['rpm', '--dbpath', rpmdb, '--import', key])+ kernel = work / 'kernel'+ kernel.mkdir()+ for package in packages:+ signature = run(['rpmkeys', '--dbpath', rpmdb, '--checksig', '--verbose', package], capture=True)+ if not re.search(r'signature, key (?:ID|fingerprint):? [0-9a-f]+: OK', signature, re.I) or 'NOKEY' in signature or 'NOT OK' in signature:+ raise ValueError('Missing verified kernel package signature')+ run(['bsdtar', '--no-same-owner', '-xpf', package, '-C', kernel])+ modules = kernel / 'lib/modules' / lock['kernel_release']+ compressed, image = work / 'Image.zst', work / 'Image'+ compressed.write_bytes(zboot_payload((modules / 'vmlinuz').read_bytes()))+ run(['zstd', '-d', compressed, '-o', image])+ check_arm_image(image.read_bytes()[:64])+ receipt['kernel_sha256'] = digest(image)+ shutil.move(kernel / 'lib/modules', inputs / 'modules')+ (inputs / 'kernel-release').write_text(lock['kernel_release'] + '\n')+ receipt['payload'] = stage(runtime, inputs / 'overlay', source)+ shutil.copy2(Path(__file__).with_name('arm_session_root.sh'), inputs / 'provision')+ receipt['provision_sha256'] = digest(inputs / 'provision')+ print('Build a fresh signed Fedora session without a desktop', flush=True)+ run(['docker', 'run', '--name', container, '--platform', 'linux/arm64', '--memory=4g', '--cpus=2', '--pids-limit=1024',+ '--mount', f'type=bind,source={inputs},target=/inputs,readonly', graphical['root_image'], 'bash', '/inputs/provision'], timeout=1200)+ for source_path, name in [('/harness-packages.tsv', 'packages.tsv'), ('/opt/harness-agent/package-lock.json', 'agent-lock.json')]:+ run(['docker', 'cp', container + ':' + source_path, output / name])+ archive, root, disk = work / 'root.tar', work / 'root', work / 'guest.raw'+ root.mkdir()+ run(['docker', 'export', '--output', archive, container], timeout=180)+ run(['sudo', 'bsdtar', '-xpf', archive, '-C', root], timeout=180)+ archive.unlink()+ # Correct only the exported private root, never the host /etc files.+ run(['sudo', 'rm', '-f', root / 'etc/resolv.conf', root / '.dockerenv'])+ run(['sudo', 'ln', '-s', '/run/systemd/resolve/stub-resolv.conf', root / 'etc/resolv.conf'])+ for path, content in [('etc/hostname', 'harness\n'), ('etc/hosts', '127.0.0.1 localhost\n127.0.1.1 harness\n::1 localhost\n'), ('etc/machine-id', '')]:+ replacement = work / ('replacement-' + Path(path).name)+ replacement.write_text(content)+ run(['sudo', 'install', '-m', '644', replacement, root / path])+ with disk.open('xb') as handle:+ handle.truncate(6 * 1024 ** 3)+ run(['sudo', 'mkfs.ext4', '-F', '-q', '-L', 'HARNESS_ARM_TEST', '-d', root, disk], timeout=180)+ receipt['disk'] = {'virtual_bytes': disk.stat().st_size, 'allocated_bytes': disk.stat().st_blocks * 512}+ if args.prepare_only:+ prepare_fixture(disk, image, output, receipt, run)+ return+ print('Boot into Wi-Fi, use an agent, open its page, and return to Harness', flush=True)+ machine = SessionVM(output / 'first-boot', disk, image)+ exercise(machine, receipt)+ machine.close()+ machine = SessionVM(output / 'second-boot', disk, image)+ exercise_reboot(machine, receipt, output)+ receipt['status'] = 'passed'+ print('Fresh Fedora/Asahi graphical session and reboot passed', flush=True)+ except BaseException as error:+ receipt.update(status='failed', error=str(error))+ failure_evidence(machine)+ raise+ finally:+ cleanup = []+ if machine:+ try:+ machine.close()+ except (OSError, RuntimeError) as error:+ cleanup.append(str(error))+ for argv in [['docker', 'rm', '-f', container], ['sudo', 'rm', '-rf', '--', work]]:+ try:+ if run(argv, timeout=90, check=False).returncode:+ cleanup.append('Cleanup failed: ' + repr([str(a) for a in argv]))+ except subprocess.SubprocessError as error:+ cleanup.append(str(error))+ if cleanup:+ receipt['cleanup_errors'] = cleanup+ receipt['status'] = 'failed'+ receipt['finished_at_unix'] = time.time()+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')+ log.close()+ if cleanup:+ raise RuntimeError('; '.join(cleanup))+++if __name__ == '__main__':+ main()diff --git a/os/tests/arm_session_root.sh b/os/tests/arm_session_root.shnew file mode 100644index 000000000..b671eb5e8--- /dev/null+++ b/os/tests/arm_session_root.sh@@ -0,0 +1,71 @@+#!/bin/bash+# Build only inside a disposable, unprivileged ARM Fedora container.+# This is a VM fixture, not an installer for a person's computer.+set -euo pipefail+test -f /.dockerenv+test "$(uname -m)" = aarch64+test -f /inputs/overlay/usr/share/harness-os/runtime.json+manager=$(command -v dnf5 || command -v microdnf)+"$manager" install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True --nodocs \+ systemd systemd-udev systemd-pam systemd-resolved dbus-broker dbus-tools \+ NetworkManager sudo python3 shadow-utils util-linux procps-ng kmod iproute \+ labwc xorg-x11-server-Xwayland foot chromium mesa-dri-drivers \+ pipewire pipewire-pulseaudio wireplumber swayidle swaylock brightnessctl \+ wl-clipboard xdg-utils xdg-desktop-portal-wlr dejavu-sans-mono-fonts \+ google-noto-color-emoji-fonts cascadia-mono-nf-fonts \+ nodejs22 nodejs22-bin nodejs22-npm nodejs22-npm-bin tmux git curl jq ripgrep less which unzip+"$manager" clean all+cp -a --no-preserve=ownership /inputs/overlay/. /+cp -a --no-preserve=ownership /inputs/modules /usr/lib/+depmod -a "$(cat /inputs/kernel-release)"+npm install --prefix /opt/harness-agent --no-audit --no-fund opencode-ai+ln -s /opt/harness-agent/node_modules/.bin/opencode /usr/bin/opencode+opencode --version+useradd --create-home --uid 1000 --groups wheel --shell /bin/bash me+# The empty password belongs only to this test disk and its local QEMU console.+# There is no SSH server, public listener, or host disk attached to the VM.+passwd -d me+printf 'harness\n' > /etc/hostname+printf '127.0.0.1 localhost\n127.0.1.1 harness\n::1 localhost\n' > /etc/hosts+mkdir -p /etc/systemd/system/[email protected]+cat > /etc/systemd/system/[email protected]/autologin.conf <<'EOF'+[Service]+ExecStart=+ExecStart=-/sbin/agetty --autologin me --noclear %I $TERM+EOF+mkdir -p /usr/local/lib/harness-test+cat > /usr/local/lib/harness-test/console <<'EOF'+#!/bin/bash+export PS1='HARNESS_ARM_CONSOLE> '+exec /bin/bash --noprofile --norc -i+EOF+chmod 755 /usr/local/lib/harness-test/console+cat > /etc/systemd/system/harness-test-console.service <<'EOF'+[Unit]+Description=Private QEMU test console+After=systemd-user-sessions.service+[Service]+ExecStart=/usr/local/lib/harness-test/console+StandardInput=tty+StandardOutput=tty+StandardError=tty+TTYPath=/dev/ttyAMA0+TTYReset=yes+TTYVHangup=yes+# Interactive bash ignores SIGTERM. End this private console like a getty,+# rather than delaying guest shutdown until systemd's service timeout.+KillSignal=SIGHUP+Restart=always+[Install]+WantedBy=multi-user.target+EOF+systemctl mask [email protected]+systemctl enable [email protected] harness-test-console.service NetworkManager.service systemd-resolved.service+systemctl set-default multi-user.target+mkdir -p /etc/modules-load.d+printf 'virtio_net\nvirtio_gpu\nvirtio_input\n' > /etc/modules-load.d/harness-test.conf+truncate -s 0 /etc/machine-id+rpm -qa --qf '%{NAME}\t%{VERSION}-%{RELEASE}\t%{ARCH}\n' | sort > /harness-packages.tsv+# Docker replaces these files with host bind mounts. The exported root's copies+# are repaired by the host builder before a fresh regular-file disk is made.diff --git a/os/tests/test_arm_session.py b/os/tests/test_arm_session.pynew file mode 100644index 000000000..0c9263d85--- /dev/null+++ b/os/tests/test_arm_session.py@@ -0,0 +1,207 @@+"""Keep the graphical ARM fixture separate from PC installation/update artifacts."""+import json+import io+from pathlib import Path+import socket+import subprocess+import sys+import tempfile+import unittest++from arm_boot import digest+from arm_session import SessionVM, fixture_identity, frame_contains, runtime_identity, stage+++class ARMFixture(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.runtime = self.root / 'runtime'+ self.runtime.mkdir()+ elf = bytearray(32)+ elf[:6] = b'\x7fELF\x02\x01'+ elf[18:20] = (183).to_bytes(2, 'little')+ for name, data in [('harness-tui', elf), ('cli.js', b'fixture'), ('notify.mjs', b'fixture')]:+ (self.runtime / name).write_bytes(data)+ self.info = {'source_commit': 'a' * 40, 'dirty': False, 'architecture': 'aarch64',+ 'target': 'aarch64-unknown-linux-musl',+ 'files': {p.name: {'bytes': p.stat().st_size, 'sha256': digest(p)} for p in self.runtime.iterdir()}}+ self.save()++ def save(self):+ (self.runtime / 'source.json').write_text(json.dumps(self.info))++ def test_rejects_wrong_source_target_and_dirty_payload(self):+ runtime_identity(self.runtime, 'a' * 40)+ for key, value in [('source_commit', 'b' * 40), ('dirty', True), ('architecture', 'x86_64'),+ ('target', 'x86_64-unknown-linux-musl')]:+ original = self.info[key]+ self.info[key] = value+ self.save()+ with self.subTest(key=key), self.assertRaises(ValueError):+ runtime_identity(self.runtime, 'a' * 40)+ self.info[key] = original++ def test_rejects_modified_runtime_and_mislabelled_elf(self):+ binary = self.runtime / 'harness-tui'+ data = bytearray(binary.read_bytes())+ data[18:20] = (62).to_bytes(2, 'little')+ binary.write_bytes(data)+ with self.assertRaisesRegex(ValueError, 'checksum'):+ runtime_identity(self.runtime, 'a' * 40)+ self.info['files']['harness-tui']['sha256'] = digest(binary)+ self.save()+ with self.assertRaisesRegex(ValueError, 'ARM64 ELF'):+ runtime_identity(self.runtime, 'a' * 40)++ def test_session_overlay_contains_no_pc_installer_or_update_services(self):+ destination = self.root / 'overlay'+ receipt = stage(self.runtime, destination, 'a' * 40)+ files = receipt['files']+ for path in ['usr/lib/harness-os/install.py', 'usr/lib/harness-os/runtime_update.py',+ 'usr/lib/systemd/user/harness-update.timer', 'etc/mkinitcpio.conf.d/20-harness-apple-keyboard.conf']:+ self.assertNotIn(path, files)+ self.assertEqual((destination / 'usr/lib/harness/hn').readlink(), Path('harness-tui'))+ self.assertEqual(receipt['runtime']['architecture'], 'aarch64')+ self.assertIn('chromium-browser', (destination / 'usr/bin/hn-browser').read_text())+ self.assertNotIn('--no-sandbox', (destination / 'usr/bin/hn-browser').read_text())+++class PortableFixture(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.folder = Path(self.temp.name)+ kernel = bytearray(64)+ kernel[24:32] = (4).to_bytes(8, 'little')+ kernel[56:60] = b'ARM\x64'+ (self.folder / 'Image').write_bytes(kernel)+ (self.folder / 'guest.raw.zst').write_bytes(b'checksum fixture; never booted')+ self.info = {'schema': 1, 'status': 'prepared', 'source_commit': 'a' * 40,+ 'raw_disk': {'bytes': 6 * 1024 ** 3, 'sha256': 'b' * 64},+ 'artifacts': {p.name: {'bytes': p.stat().st_size, 'sha256': digest(p)}+ for p in self.folder.iterdir()}}+ self.save()++ def save(self):+ (self.folder / 'manifest.json').write_text(json.dumps(self.info))++ def test_requires_prepared_exact_source(self):+ fixture_identity(self.folder, 'a' * 40)+ with self.assertRaisesRegex(ValueError, 'exact clean source'):+ fixture_identity(self.folder, 'c' * 40)+ self.info['status'] = 'passed'+ self.save()+ with self.assertRaisesRegex(ValueError, 'prepared fixture'):+ fixture_identity(self.folder, 'a' * 40)++ def test_rejects_corruption_and_symlinks_before_boot(self):+ disk = self.folder / 'guest.raw.zst'+ original = disk.read_bytes()+ disk.write_bytes(b'changed')+ with self.assertRaisesRegex(ValueError, 'checksum mismatch'):+ fixture_identity(self.folder, 'a' * 40)+ other = self.folder / 'other'+ other.write_bytes(original)+ disk.unlink()+ disk.symlink_to(other)+ with self.assertRaisesRegex(ValueError, 'checksum mismatch'):+ fixture_identity(self.folder, 'a' * 40)++ def test_rejects_unbounded_disk_and_other_artifact_names(self):+ self.info['raw_disk']['bytes'] = 1024 ** 4+ self.save()+ with self.assertRaisesRegex(ValueError, 'private disk identity'):+ fixture_identity(self.folder, 'a' * 40)+ self.info['artifacts']['../other'] = self.info['artifacts'].pop('Image')+ self.save()+ with self.assertRaisesRegex(ValueError, 'kernel and compressed private disk'):+ fixture_identity(self.folder, 'a' * 40)+++class VisibleFrames(unittest.TestCase):+ def test_agent_name_in_status_bar_is_not_ready_input(self):+ # Actual failed frame: the status bar appeared before the composer,+ # so the earlier name-only assertion sent the prompt into startup.+ starting = 'Terminal harness 10-5 6:42\n[me@harness ~]$\n0: opencode*\nharness 06:42'+ expected = ['OpenCode', 'Ask anything']+ self.assertFalse(frame_contains(starting, expected))+ self.assertTrue(frame_contains(starting + '\nOpenCode\nAsk anything...\nBuild OpenCode Zen', expected))++ def test_agent_transcript_is_not_a_loaded_browser_page(self):+ # The retained failure frame showed the generated HTML in OpenCode+ # while Chromium was still starting in the background.+ transcript = ('Terminal harness 10-5 5:53 [me@harness ~]$\n'+ 'Wrote index.html\n<title>Harness ARM Demo</title>\n'+ 'The page displays Count: 0 and an Increment button.\n'+ 'Build Big Pickle OpenCode Zen')+ expected = ['Harness ARM Demo', 'Count: 0', 'Increment']+ self.assertFalse(frame_contains(transcript, expected, absent=['me@harness']))+ self.assertFalse(frame_contains('Harness ARM Demo', expected, absent=['me@harness']))+ browser = 'Harness ARM Demo\n/home/me/projects/demo/index.html\nHarness ARM Demo\nCount: 0\nIncrement'+ self.assertTrue(frame_contains(browser, expected, absent=['me@harness']))+++class GuestPoweroff(unittest.TestCase):+ def machine(self, event, exit_code=0):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ machine = object.__new__(SessionVM)+ machine.folder = Path(temporary.name)+ machine.log = io.BytesIO()+ machine.serial, console = socket.socketpair()+ machine.qmp, monitor = socket.socketpair()+ self.addCleanup(machine.serial.close)+ self.addCleanup(machine.qmp.close)+ # A real child/socket pair exposes serial backpressure: merely waiting+ # for process exit without draining output cannot complete this probe.+ producer = '''import json,socket,sys,time+serial=socket.socket(fileno=int(sys.argv[1]))+qmp=socket.socket(fileno=int(sys.argv[2]))+request=b''+while not request.endswith(b'\\n'):+ request+=serial.recv(1024)+assert request==b'sync; systemctl poweroff --no-block\\n'+serial.sendall(b'x'*(2*1024*1024))+qmp.sendall((sys.argv[3]+'\\n').encode())+time.sleep(.02)+sys.exit(int(sys.argv[4]))+'''+ machine.process = subprocess.Popen(+ [sys.executable, '-c', producer, str(console.fileno()), str(monitor.fileno()),+ json.dumps(event), str(exit_code)], pass_fds=(console.fileno(), monitor.fileno()))+ console.close()+ monitor.close()++ def cleanup():+ if machine.process.poll() is None:+ machine.process.terminate()+ machine.process.wait(timeout=5)+ self.addCleanup(cleanup)+ return machine++ def test_drains_console_and_requires_guest_shutdown(self):+ event = {'event': 'SHUTDOWN', 'data': {'guest': True, 'reason': 'guest-shutdown'}}+ machine = self.machine(event)+ receipt = machine.poweroff(timeout=5)+ self.assertEqual(receipt['status'], 'passed')+ self.assertEqual(machine.log.getvalue(), b'x' * (2 * 1024 * 1024))+ self.assertEqual(receipt['events'], [event])+ self.assertEqual(receipt['exit_code'], 0)++ def test_host_quit_is_not_successful_guest_poweroff(self):+ machine = self.machine({'event': 'SHUTDOWN', 'data': {'guest': False, 'reason': 'host-qmp-quit'}})+ with self.assertRaisesRegex(RuntimeError, 'guest poweroff event'):+ machine.poweroff(timeout=5)+ receipt = json.loads((machine.folder / 'shutdown.json').read_text())+ self.assertEqual(receipt['status'], 'failed')++ def test_guest_event_does_not_hide_unsuccessful_exit(self):+ machine = self.machine({'event': 'SHUTDOWN', 'data': {'guest': True, 'reason': 'guest-shutdown'}}, exit_code=1)+ with self.assertRaisesRegex(RuntimeError, 'exited unsuccessfully'):+ machine.poweroff(timeout=5)+++if __name__ == '__main__':+ unittest.main()