Skip to content

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.

Validate Harness ARM work on a real 16 KiB kernel (#750)

Deea764743775d3
diff --git a/.github/workflows/os-arm-boot.yml b/.github/workflows/os-arm-boot.yml
new file mode 100644
index 000000000..967eb811e
--- /dev/null
+++ b/.github/workflows/os-arm-boot.yml
@@ -0,0 +1,85 @@
+name: Harness OS ARM kernel acceptance
+
+on:
+ workflow_dispatch:
+ push:
+ branches: ['os-polish/arm-boot']
+ paths:
+ - 'os/tests/arm_boot*'
+ - 'os/tests/arm-boot.lock.json'
+ - 'os/tests/runtime_native.py'
+ - '.github/workflows/os-arm-boot.yml'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: harness-arm-boot-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ boot:
+ 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: |
+ sudo apt-get update -qq
+ sudo apt-get install -y --no-install-recommends musl-tools qemu-system-arm \
+ e2fsprogs rpm libarchive-tools zstd gnupg libevent-dev libncurses-dev libutf8proc-dev bison
+ if [ -c /dev/kvm ]; then sudo chown "$USER" /dev/kvm; fi
+ make -C os check
+ - name: Use the OS tmux release for native comparison
+ run: |
+ curl --fail --location --retry 3 --max-time 120 \
+ https://github.com/tmux/tmux/releases/download/3.7c/tmux-3.7c.tar.gz \
+ --output "$RUNNER_TEMP/tmux.tar.gz"
+ echo '7c60cae9a0e25288e2e24750aafc9e8800fc7fd4555e447e1b29ee4201cfb3bf tmux.tar.gz' > "$RUNNER_TEMP/tmux.sha256"
+ (cd "$RUNNER_TEMP" && sha256sum --check tmux.sha256)
+ mkdir "$RUNNER_TEMP/tmux-source"
+ tar -xzf "$RUNNER_TEMP/tmux.tar.gz" -C "$RUNNER_TEMP/tmux-source" --strip-components=1
+ cd "$RUNNER_TEMP/tmux-source"
+ ./configure --prefix="$RUNNER_TEMP/tmux-reference"
+ make -j2
+ make install
+ "$RUNNER_TEMP/tmux-reference/bin/tmux" -V
+ echo "$RUNNER_TEMP/tmux-reference/bin" >> "$GITHUB_PATH"
+ - name: Build the exact native Harness runtime
+ run: bash os/tools/build-runtime.sh
+ - name: Prepare the upstream-default agent for the disposable VM
+ run: |
+ npm install --prefix "$RUNNER_TEMP/harness-native-agent" --no-audit --no-fund opencode-ai
+ mkdir -p os/test-results
+ cp "$RUNNER_TEMP/harness-native-agent/package-lock.json" os/test-results/agent-test-lock.json
+ - name: Boot the signed 16 KiB kernel and exercise actual work
+ run: |
+ python3 os/tests/arm_boot.py --runtime os/work/runtime \
+ --agent "$RUNNER_TEMP/harness-native-agent" --output os/test-results/arm-boot
+ - name: Retain boot and native runtime evidence
+ if: always()
+ uses: actions/upload-artifact@v6
+ with:
+ name: harness-arm-kernel-acceptance
+ path: |
+ os/work/runtime/source.json
+ os/test-results/arm-boot/
+ os/test-results/agent-test-lock.json
+ if-no-files-found: error
+ retention-days: 14
+ compression-level: 6
diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.md
index caf3ad039..2a93f5e8d 100644
--- a/os/DEVELOPMENT.md
+++ b/os/DEVELOPMENT.md
@@ -504,6 +504,30 @@ An aligned ARM executable still needs execution on a 16 KiB-page kernel before
claiming Apple Silicon userspace compatibility; see
[Asahi's page-size requirements](https://asahilinux.org/docs/sw/broken-software/).
+The **Harness OS ARM kernel acceptance** workflow boots that runtime under a
+16 KiB-page Asahi kernel in a disposable QEMU VM. `tests/arm-boot.lock.json`
+pins the Ubuntu ARM64 userspace image, kernel RPMs and signing key by digest.
+The runner verifies RPM signatures before extracting the raw boot image; no
+kernel packages are installed on the runner. The guest records its actual kernel
+and page size, then runs the real daemon/pane/agent acceptance above, including
+independent execution of generated code and preservation of work through restart.
+Serial output, guest receipts, userspace package versions and agent lockfiles are
+retained even when acceptance fails. The private disk and container are removed.
+
+Run on a disposable native ARM Linux host with Docker, QEMU, RPM verification,
+libarchive, zstd and ext4 tools; use the workflow for complete tool setup:
+
+```sh
+python3 os/tests/arm_boot.py --runtime os/work/runtime \
+ --agent /path/to/npm-opencode-prefix --output os/test-results/arm-boot
+```
+
+This isolates the page-size/kernel change while retaining the native runner's
+Ubuntu userspace. It is not a product image, distribution choice, graphical boot
+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 and
+update feed until each platform has its own packaging and installation path.
+
## Mac support targets
Intel Macs and Apple Silicon are both intended OS targets. They share the Harness
diff --git a/os/tests/arm-boot.lock.json b/os/tests/arm-boot.lock.json
new file mode 100644
index 000000000..1ad4993cd
--- /dev/null
+++ b/os/tests/arm-boot.lock.json
@@ -0,0 +1,26 @@
+{
+ "schema": 1,
+ "scope": "Disposable 16 KiB-kernel userspace acceptance; not an ARM product image",
+ "architecture": "aarch64",
+ "page_size": 16384,
+ "root_image": "docker.io/library/ubuntu@sha256:08571ca13e00ca07a2a84eab83a959b4242e22cceb16486a11bef1428c9e93a7",
+ "kernel_release": "7.1.13-402.asahi.fc44.aarch64+16k",
+ "kernel_packages": [
+ {
+ "url": "https://packages.redhat.com/api/pulp-content/public-copr/@asahi/kernel/fedora-44-aarch64/Packages/k/kernel-16k-core-7.1.13-402.asahi.fc44.aarch64.rpm",
+ "bytes": 24411445,
+ "sha256": "eed80db3ed1f6762023b98917f860ba2f33b622f0af36a2d75bbd17897c652f9"
+ },
+ {
+ "url": "https://packages.redhat.com/api/pulp-content/public-copr/@asahi/kernel/fedora-44-aarch64/Packages/k/kernel-16k-modules-core-7.1.13-402.asahi.fc44.aarch64.rpm",
+ "bytes": 42678069,
+ "sha256": "b56ff68c92b909124cbd1b69ba764e8014267142b7ce114459c9d3fd31a9672b"
+ }
+ ],
+ "signing_key": {
+ "url": "https://download.copr.fedorainfracloud.org/results/@asahi/kernel/pubkey.gpg",
+ "bytes": 998,
+ "sha256": "93372b0c24fdb10b6d6204ebedf8861b0dceffa7998b4d6c70f55bd69fe86668",
+ "fingerprint": "9E4DF9135D39DDFFC77B514EB2D8704E00C08EA0"
+ }
+}
diff --git a/os/tests/arm_boot.py b/os/tests/arm_boot.py
new file mode 100644
index 000000000..56bea0ab9
--- /dev/null
+++ b/os/tests/arm_boot.py
@@ -0,0 +1,258 @@
+#!/usr/bin/env python3
+"""Boot the exact ARM runtime under a verified 16 KiB kernel on a private test disk.
+
+This exports a disposable Ubuntu userspace, not a Harness release image. It does
+not partition any host disk, prepare Apple firmware, or claim hardware support.
+"""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import shutil
+import struct
+import subprocess
+import tempfile
+import time
+from urllib.request import urlopen
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def digest(path):
+ with path.open('rb') as handle:
+ return hashlib.file_digest(handle, 'sha256').hexdigest()
+
+
+def zboot_payload(data):
+ # Linux v7.1 drivers/firmware/efi/libstub/zboot-header.S: offset/size at 8/12,
+ # compression at 24, Linux PE magic at 56. The pinned package uses zstd.
+ if len(data) < 64 or data[:8] != b'MZ\0\0zimg' or data[56:60] != b'\xcd\x23\x82\x81':
+ raise ValueError('Not a Linux EFI zboot image')
+ offset, size = struct.unpack_from('<II', data, 8)
+ if offset < 64 or size == 0 or offset + size > len(data):
+ raise ValueError('Invalid compressed kernel bounds')
+ if data[24:32].split(b'\0', 1)[0] != b'zstd':
+ raise ValueError('The locked kernel must use zstd')
+ return data[offset:offset + size]
+
+
+def check_arm_image(data):
+ # Documentation/arch/arm64/booting.rst: Image flags bits 1..2 encode page size.
+ if len(data) < 64 or data[56:60] != b'ARM\x64':
+ raise ValueError('Not an ARM64 Linux Image')
+ flags = struct.unpack_from('<Q', data, 24)[0]
+ if flags & 1 or ((flags >> 1) & 3) != 2:
+ raise ValueError('Expected a little-endian 16 KiB ARM64 Image')
+
+
+def download(item, folder):
+ path = folder / item['url'].rsplit('/', 1)[-1]
+ with urlopen(item['url'], timeout=60) as response, path.open('xb') as output:
+ written = 0
+ while chunk := response.read(1024 * 1024):
+ written += len(chunk)
+ if written > item['bytes']:
+ raise ValueError('Oversized input: ' + path.name)
+ output.write(chunk)
+ if path.stat().st_size != item['bytes'] or digest(path) != item['sha256']:
+ raise ValueError('Input checksum mismatch: ' + path.name)
+ return path
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--runtime', type=Path, required=True)
+ parser.add_argument('--agent', type=Path, required=True, help='npm prefix containing opencode-ai')
+ parser.add_argument('--output', type=Path, required=True)
+ args = parser.parse_args()
+ if platform.system() != 'Linux' or platform.machine() != 'aarch64' or os.geteuid() == 0:
+ parser.error('Use an ordinary user on a native aarch64 Linux test runner.')
+ for name in ['docker', 'rpm', 'rpmkeys', 'gpg', 'bsdtar', 'zstd', 'mkfs.ext4',
+ 'debugfs', 'qemu-system-aarch64', 'node', 'tmux', 'sudo']:
+ if not shutil.which(name):
+ parser.error('Missing test tool: ' + name)
+ output = args.output.resolve()
+ output.mkdir(parents=True, exist_ok=False)
+ runtime, agent = args.runtime.resolve(), args.agent.resolve()
+ lock = json.loads(Path(__file__).with_name('arm-boot.lock.json').read_text())
+ source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
+ if subprocess.check_output(['git', 'status', '--porcelain', '--untracked-files=no'], cwd=ROOT, text=True).strip():
+ parser.error('Commit tracked source changes before running the boot acceptance.')
+ info = json.loads((runtime / 'source.json').read_text())
+ if info['source_commit'] != source or info['dirty'] or info['architecture'] != 'aarch64':
+ parser.error('Use the exact clean ARM runtime from this checkout.')
+ if set(info['files']) != {'harness-tui', 'cli.js', 'notify.mjs'}:
+ parser.error('The runtime must contain the complete native payload.')
+ for name, identity in info['files'].items():
+ if (runtime / name).stat().st_size != identity['bytes'] or digest(runtime / name) != identity['sha256']:
+ parser.error('Runtime identity mismatch: ' + name)
+ work = Path(tempfile.mkdtemp(prefix='harness-arm-boot-', dir=os.environ.get('RUNNER_TEMP')))
+ container = 'harness-arm-boot-' + work.name.rsplit('-', 1)[-1]
+ process = None
+ root = work / 'root'
+ root.mkdir()
+ log = (output / 'host.log').open('w')
+ receipt = {'status': 'running', 'scope': '16 KiB kernel and userspace in QEMU; no board install or drivers',
+ 'source_commit': source, 'runtime': info, 'locked_inputs': lock,
+ 'started_at_unix': time.time()}
+
+ 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,
+ stdout=subprocess.PIPE if capture else log,
+ stderr=subprocess.STDOUT if capture else log, text=True)
+ if capture:
+ log.write(result.stdout)
+ log.flush()
+ return result.stdout
+ return result
+
+ try:
+ print('Verifying signed kernel inputs', flush=True)
+ inputs = work / 'inputs'
+ inputs.mkdir()
+ with ThreadPoolExecutor(max_workers=3) as pool:
+ paths = list(pool.map(lambda item: download(item, inputs),
+ [*lock['kernel_packages'], lock['signing_key']]))
+ packages, key = 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)
+ fingerprints = [line.split(':')[9] for line in keys.splitlines() if line.startswith('fpr:')]
+ if fingerprints != [lock['signing_key']['fingerprint']]:
+ raise ValueError('Unexpected kernel signing key')
+ run(['rpm', '--dbpath', rpmdb, '--initdb'])
+ run(['rpm', '--dbpath', rpmdb, '--import', key])
+ for package in packages:
+ signatures = run(['rpmkeys', '--dbpath', rpmdb, '--checksig', '--verbose', package], capture=True)
+ if not re.search(r'signature, key ID [0-9a-f]+: OK', signatures, re.I) or 'NOKEY' in signatures or 'NOT OK' in signatures:
+ raise ValueError('Missing verified RPM signature')
+ kernel = work / 'kernel'
+ kernel.mkdir()
+ for package in packages:
+ run(['bsdtar', '--no-same-owner', '-xpf', package, '-C', kernel])
+ module_dir = kernel / 'lib/modules' / lock['kernel_release']
+ config = (module_dir / 'config').read_text()
+ for required in ['ARM64_16K_PAGES', 'VIRTIO_BLK', 'VIRTIO_PCI', 'EXT4_FS',
+ 'DEVTMPFS_MOUNT', 'SERIAL_AMBA_PL011', 'PCI_HOST_GENERIC']:
+ if f'CONFIG_{required}=y\n' not in config:
+ raise ValueError('Missing built-in boot requirement: ' + required)
+ compressed = work / 'Image.zst'
+ compressed.write_bytes(zboot_payload((module_dir / 'vmlinuz').read_bytes()))
+ image = work / 'Image'
+ run(['zstd', '-d', '--force', compressed, '-o', image])
+ check_arm_image(image.read_bytes()[:64])
+ shutil.copy2(module_dir / 'config', output / 'kernel.config')
+ receipt['raw_kernel'] = {'sha256': digest(image), 'bytes': image.stat().st_size}
+ print('Preparing the disposable userspace', flush=True)
+ shutil.move(kernel / 'lib/modules', inputs / 'modules')
+ (inputs / 'kernel-release').write_text(lock['kernel_release'] + '\n')
+ (inputs / 'source-commit').write_text(source + '\n')
+ shutil.copy2(shutil.which('node'), inputs / 'node')
+ shutil.copy2(shutil.which('tmux'), inputs / 'tmux')
+ payload = inputs / 'payload'
+ shutil.copytree(runtime, payload / 'runtime')
+ for relative in ['os/tests/runtime_native.py', 'os/tools/build-package.py',
+ 'os/root/usr/share/harness-os/tmux.conf']:
+ destination = payload / relative
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(ROOT / relative, destination)
+ shutil.copytree(agent, inputs / 'agent', symlinks=True)
+ shutil.copy2(Path(__file__).with_name('arm_boot_guest.sh'), inputs / 'guest-init')
+ shutil.copy2(Path(__file__).with_name('arm_boot_root.sh'), inputs / 'provision')
+ receipt['fixture_files'] = {name: digest(inputs / name) for name in
+ ['node', 'tmux', 'guest-init', 'provision', 'agent/package-lock.json']}
+ run(['docker', 'run', '--name', container, '--platform', 'linux/arm64',
+ '--mount', f'type=bind,source={inputs},target=/inputs,readonly',
+ lock['root_image'], 'bash', '/inputs/provision'], timeout=1200)
+ export = work / 'root.tar'
+ run(['docker', 'export', '--output', export, container], timeout=180)
+ run(['sudo', 'bsdtar', '-xpf', export, '-C', root], timeout=180)
+ export.unlink()
+ disk = work / 'guest.raw'
+ with disk.open('xb') as handle:
+ handle.truncate(8 * 1024 ** 3)
+ run(['sudo', 'mkfs.ext4', '-F', '-q', '-d', root, disk], timeout=180)
+ receipt['disk'] = {'virtual_bytes': disk.stat().st_size, 'allocated_bytes': disk.stat().st_blocks * 512}
+ accelerator = 'kvm' if os.access('/dev/kvm', os.R_OK | os.W_OK) else 'tcg'
+ # Keep the TCG instruction set stable across emulator versions.
+ cpu = 'host' if accelerator == 'kvm' else 'cortex-a76'
+ receipt['accelerator'] = accelerator
+ receipt['cpu'] = cpu
+ receipt['qemu_version'] = run(['qemu-system-aarch64', '--version'], capture=True).strip()
+ print(f'Booting the 16 KiB kernel with {accelerator}', flush=True)
+ serial = output / 'serial.log'
+ boot_started = time.monotonic()
+ with serial.open('wb') as handle:
+ process = subprocess.Popen(['qemu-system-aarch64', '-machine', 'virt', '-accel', accelerator,
+ '-cpu', cpu, '-smp', '2', '-m', '4096', '-nodefaults', '-display', 'none',
+ '-serial', 'stdio', '-monitor', 'none', '-no-reboot', '-kernel', str(image),
+ '-append', 'root=/dev/vda rw console=ttyAMA0 earlycon init=/sbin/harness-test-init net.ifnames=0 panic=1',
+ '-drive', f'file={disk},format=raw,if=none,id=root', '-device', 'virtio-blk-pci,drive=root',
+ '-netdev', 'user,id=net', '-device', 'virtio-net-pci,netdev=net,romfile='],
+ stdin=subprocess.DEVNULL, stdout=handle, stderr=subprocess.STDOUT)
+ while process.poll() is None:
+ elapsed = time.monotonic() - boot_started
+ if elapsed > 120 and 'HARNESS_ARM_KERNEL=' not in serial.read_text(errors='replace'):
+ raise TimeoutError('Guest did not reach the kernel/page-size assertion within 120 seconds; see serial.log')
+ if elapsed > 1200:
+ raise TimeoutError('Guest runtime acceptance exceeded 1200 seconds; see serial.log')
+ time.sleep(1)
+ receipt['vm_elapsed_seconds'] = time.monotonic() - boot_started
+ receipt['qemu_exit'] = process.returncode
+ run(['debugfs', '-R', f'rdump /results {output}', disk], timeout=90)
+ if process.returncode != 0:
+ raise ValueError('QEMU did not shut down successfully; see serial.log')
+ guest = output / 'results'
+ boot = json.loads((guest / 'boot.json').read_text())
+ native = json.loads((guest / 'native-runtime/receipt.json').read_text())
+ if boot['page_size'] != 16384 or native['page_size'] != 16384 or native['status'] != 'passed':
+ raise ValueError('The 16 KiB guest runtime acceptance did not pass')
+ if native['runtime'] != info or native['kernel'] != lock['kernel_release']:
+ raise ValueError('The guest did not run the expected runtime/kernel')
+ if not re.search(r'^HARNESS_ARM_BOOT_EXIT=0\r?$', serial.read_text(), re.M):
+ raise ValueError('The guest did not report successful completion')
+ receipt.update(status='passed', boot=boot, native_receipt_sha256=digest(guest / 'native-runtime/receipt.json'))
+ print('16 KiB kernel, real panes, default agent and surviving work passed', flush=True)
+ except BaseException as error:
+ receipt.update(status='failed', error=str(error))
+ raise
+ finally:
+ cleanup_errors = []
+ if process and process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout=15)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+ # Recover guest diagnostics after a failed or timed-out boot as well.
+ disk = work / 'guest.raw'
+ if disk.exists() and not (output / 'results').exists():
+ try:
+ run(['debugfs', '-R', f'rdump /results {output}', disk], timeout=90, check=False)
+ except (OSError, subprocess.SubprocessError) as error:
+ cleanup_errors.append('Guest evidence: ' + str(error))
+ try:
+ run(['docker', 'rm', '--force', container], check=False)
+ run(['sudo', 'rm', '-rf', '--', root], timeout=90)
+ shutil.rmtree(work)
+ except (OSError, subprocess.SubprocessError) as error:
+ cleanup_errors.append('Fixture cleanup: ' + str(error))
+ receipt['finished_at_unix'] = time.time()
+ if cleanup_errors:
+ receipt.update(status='failed', cleanup_errors=cleanup_errors)
+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')
+ log.close()
+ if cleanup_errors:
+ raise RuntimeError('; '.join(cleanup_errors))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/arm_boot_guest.sh b/os/tests/arm_boot_guest.sh
new file mode 100644
index 000000000..815d84f2d
--- /dev/null
+++ b/os/tests/arm_boot_guest.sh
@@ -0,0 +1,46 @@
+#!/usr/bin/env bash
+# PID 1 in a private QEMU test disk; never installed on a user's computer.
+export PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+exec </dev/console >/dev/console 2>&1
+set -u
+finish() {
+ status=$?
+ trap - EXIT
+ set +e
+ printf '\nHARNESS_ARM_BOOT_EXIT=%s\n' "$status"
+ sync
+ /bin/busybox poweroff -f
+ while true; do sleep 10; done
+}
+trap finish EXIT
+set -e
+mkdir -p /proc /sys /run /dev/pts /dev/shm
+mount -t proc proc /proc
+mount -t sysfs sysfs /sys
+mount -t tmpfs -o mode=0755 tmpfs /run
+mount -t devpts devpts /dev/pts
+mount -t tmpfs -o mode=1777 tmpfs /dev/shm
+printf harness > /proc/sys/kernel/hostname
+test "$(uname -m)" = aarch64
+test "$(uname -r)" = "$(cat /etc/harness-test-kernel)"
+test "$(getconf PAGESIZE)" = 16384
+printf 'HARNESS_ARM_KERNEL=%s PAGESIZE=%s\n' "$(uname -r)" "$(getconf PAGESIZE)"
+modprobe virtio_net
+ip link set lo up
+ip link set eth0 up
+ip address add 10.0.2.15/24 dev eth0
+ip route add default via 10.0.2.2
+printf 'nameserver 10.0.2.3\n' > /etc/resolv.conf
+python3 - <<'PY' > /results/boot.json
+import json, os, platform
+print(json.dumps({'architecture': platform.machine(), 'kernel': platform.release(),
+ 'page_size': os.sysconf('SC_PAGE_SIZE'),
+ 'uptime_seconds': float(open('/proc/uptime').read().split()[0])}, indent=2))
+PY
+setpriv --reuid=1000 --regid=1000 --clear-groups \
+ env HOME=/home/me TERM=xterm-256color LANG=C.UTF-8 \
+ python3 /opt/harness-native/os/tests/runtime_native.py \
+ --runtime /opt/harness-native/runtime --architecture aarch64 \
+ --source-commit "$(cat /etc/harness-test-source)" \
+ --opencode /opt/harness-agent/node_modules/.bin/opencode \
+ --output /results/native-runtime
diff --git a/os/tests/arm_boot_root.sh b/os/tests/arm_boot_root.sh
new file mode 100644
index 000000000..fe7455e7a
--- /dev/null
+++ b/os/tests/arm_boot_root.sh
@@ -0,0 +1,31 @@
+#!/usr/bin/env bash
+# Build only the disposable test guest, inside its named container.
+set -euo pipefail
+export DEBIAN_FRONTEND=noninteractive
+apt-get update -qq
+apt-get install -y --no-install-recommends ca-certificates git python3 tmux libutf8proc3 \
+ procps kmod iproute2 util-linux passwd busybox-static
+install -m 755 /inputs/node /usr/local/bin/node
+install -m 755 /inputs/tmux /usr/local/bin/tmux
+node --version
+tmux -V
+cp -a /inputs/modules /lib/
+chown -R root:root /lib/modules
+depmod -a "$(cat /inputs/kernel-release)"
+cp -a /inputs/payload /opt/harness-native
+cp -a /inputs/agent /opt/harness-agent
+install -m 755 /inputs/guest-init /sbin/harness-test-init
+cp /inputs/kernel-release /etc/harness-test-kernel
+cp /inputs/source-commit /etc/harness-test-source
+existing=$(getent passwd 1000 | cut -d: -f1 || true)
+if [[ -n "$existing" ]]; then
+ usermod --login me --home /home/me --move-home --shell /bin/bash "$existing"
+else
+ useradd --create-home --uid 1000 --shell /bin/bash me
+fi
+mkdir -p /results /dev/pts /dev/shm /run
+chown 1000:1000 /results
+dpkg-query -W -f='${Package}\t${Version}\t${Architecture}\n' > /results/userspace-packages.tsv
+chmod 644 /results/userspace-packages.tsv
+apt-get clean
+rm -rf /var/lib/apt/lists/*
diff --git a/os/tests/runtime_native.py b/os/tests/runtime_native.py
index df1c22b8a..de3a07d85 100644
--- a/os/tests/runtime_native.py
+++ b/os/tests/runtime_native.py
@@ -9,11 +9,13 @@ import os
from pathlib import Path
import platform
import pty
+import re
import select
import shlex
import shutil
import signal
import socket
+import sqlite3
import struct
import subprocess
import tempfile
@@ -43,6 +45,72 @@ def checksum(path):
return hashlib.file_digest(handle, 'sha256').hexdigest()
+def agent_transcript(home):
+ """Read only conversation rows from the fixture's fresh, isolated agent home."""
+ database = home / '.local/share/opencode/opencode.db'
+ if not database.is_file():
+ return {'status': 'unavailable', 'reason': 'No agent conversation database'}
+ with sqlite3.connect(database.as_uri() + '?mode=ro', uri=True, timeout=2) as db:
+ db.row_factory = sqlite3.Row
+ # Do not archive the database, auth/config files, or unrelated tables.
+ return {table: [dict(row) for row in db.execute(sql)] for table, sql in [
+ ('messages', 'SELECT id, session_id, time_created, data FROM message ORDER BY time_created, id'),
+ ('parts', 'SELECT id, message_id, session_id, time_created, data FROM part ORDER BY time_created, id'),
+ ]}
+
+
+def finish_fixture_processes(home):
+ """Drain only this fixture's private-HOME processes before removing their files.
+
+ Closing a tmux server does not wait for its children to finish writing. Pin
+ each matching process with a Linux pidfd so PID reuse cannot target another
+ process, and never include an unrelated runner's command line in evidence.
+ """
+ expected = b'HOME=' + os.fsencode(home)
+ signalled = []
+ for action, seconds in [(None, 2), (signal.SIGTERM, 3), (signal.SIGKILL, 3)]:
+ deadline = time.monotonic() + seconds
+ while True:
+ pending = {}
+ try:
+ for process in Path('/proc').iterdir():
+ if not process.name.isdigit() or int(process.name) == os.getpid():
+ continue
+ fd = None
+ try:
+ if process.stat().st_uid != os.getuid():
+ continue
+ fd = os.pidfd_open(int(process.name))
+ if expected not in (process / 'environ').read_bytes().split(b'\0'):
+ continue
+ if select.select([fd], [], [], 0)[0]:
+ continue
+ pending[fd] = int(process.name)
+ fd = None
+ except (ProcessLookupError, FileNotFoundError, PermissionError):
+ continue
+ finally:
+ if fd is not None:
+ os.close(fd)
+ if not pending:
+ return signalled
+ if action is not None:
+ for fd, pid in pending.items():
+ try:
+ signal.pidfd_send_signal(fd, action)
+ signalled.append({'pid': pid, 'signal': action.name})
+ except ProcessLookupError:
+ pass
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ select.select(list(pending), [], [], min(remaining, .2))
+ finally:
+ for fd in pending:
+ os.close(fd)
+ raise RuntimeError('Fixture processes did not exit before cleanup')
+
+
class Screen:
def __init__(self, argv, env, cwd):
self.fd, slave = pty.openpty()
@@ -94,6 +162,7 @@ def main():
parser.add_argument('--opencode', type=Path, required=True)
parser.add_argument('--architecture', choices=['x86_64', 'aarch64'], required=True)
parser.add_argument('--output', type=Path, required=True)
+ parser.add_argument('--source-commit', help='Expected clean producer commit when testing an exported VM payload')
args = parser.parse_args()
if platform.system() != 'Linux' or platform.machine() != args.architecture or os.geteuid() == 0:
parser.error('Run as an ordinary user on the matching native Linux runner.')
@@ -101,7 +170,9 @@ def main():
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=False)
info = json.loads((runtime / 'source.json').read_text())
- source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
+ source = args.source_commit or subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
+ if not re.fullmatch(r'[0-9a-f]{40}', source):
+ parser.error('A complete source commit is required.')
assert info['source_commit'] == source and info['dirty'] is False
assert info['architecture'] == args.architecture
assert info['target'] == args.architecture + '-unknown-linux-musl'
@@ -109,7 +180,7 @@ def main():
for name, identity in info['files'].items():
assert (runtime / name).stat().st_size == identity['bytes']
assert checksum(runtime / name) == identity['sha256']
- assert subprocess.check_output(['node', '-p', 'process.arch'], text=True).strip() == {
+ assert subprocess.check_output(['node', '-p', 'process.arch'], text=True, timeout=30).strip() == {
'x86_64': 'x64', 'aarch64': 'arm64'}[args.architecture]
with (runtime / 'harness-tui').open('rb') as handle:
header = handle.read(64)
@@ -139,14 +210,15 @@ def main():
receipt = {'status': 'running', 'scope': 'native userspace; no boot, drivers or platform installation',
'architecture': args.architecture, 'kernel': platform.release(), 'runtime': info,
'page_size': os.sysconf('SC_PAGE_SIZE'), 'hn_load_alignments': load_alignments,
- 'tmux': subprocess.check_output(['tmux', '-V'], text=True).strip(),
+ 'tmux': subprocess.check_output(['tmux', '-V'], text=True, timeout=15).strip(),
'checks': ['Exact source, native ELF/Node architecture, complete hashes and PC packaging boundary verified'],
'started_at_unix': time.time()}
report = output / 'receipt.json'
report.write_text(json.dumps(receipt, indent=2) + '\n')
daemon = screen = None
logs = []
- with tempfile.TemporaryDirectory(prefix='harness-native-', dir='/tmp') as temporary:
+ temporary_directory = tempfile.TemporaryDirectory(prefix='harness-native-', dir='/tmp')
+ with temporary_directory as temporary:
base = Path(temporary)
home, binaries = base / 'home', base / 'bin'
project = home / 'projects/native-agent'
@@ -212,10 +284,36 @@ def main():
def type_into_screen(pane, line):
hn('select-pane', '-t', pane)
- time.sleep(.2)
+ wait(lambda: hn('display-message', '-p', '-t', pane, '#{pane_active}') == '1',
+ 'Selected input pane ' + pane)
assert screen.process.poll() is None, 'Native terminal closed'
screen.write(line + '\r')
+ def record_state(label):
+ state = {'at_unix': time.time()}
+ for key, argv in [
+ ('hn', [*command, 'list-panes', '-a', '-F',
+ '#{pane_id}|#{pane_active}|#{pane_current_path}|#{pane_current_command}']),
+ ('tmux', ['tmux', '-S', str(base / f'tmux-{os.getuid()}' / 'default'),
+ 'list-panes', '-a', '-F',
+ '#{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}|#{pane_dead}']),
+ ('processes', ['ps', '-eo', 'pid,ppid,pgid,lstart,comm']),
+ ]:
+ try:
+ result = subprocess.run(argv, env=env, cwd=project, text=True,
+ capture_output=True, timeout=15)
+ state[key] = {'exit': result.returncode, 'stdout': result.stdout, 'stderr': result.stderr}
+ except (OSError, subprocess.SubprocessError) as error:
+ state[key] = {'error': str(error)}
+ (output / (label + '.json')).write_text(json.dumps(state, indent=2) + '\n')
+
+ def wait_for_shell():
+ # Escape sequences alone are not proof that the reattached screen
+ # has received its terminal replay. Wait for our real shell prompt.
+ wait(lambda: b'HN_NATIVE_READY>' in screen.data, 'Restored shell prompt', 45)
+ wait(lambda: set(hn('list-panes', '-t', 'runtime', '-F', '#{pane_id}').splitlines())
+ == {shell, right, agent}, 'All three original pane identities', 30)
+
try:
receipt['opencode_version'] = subprocess.check_output([str(binaries / 'opencode'), '--version'],
env=env, cwd=project, text=True, timeout=30).strip()
@@ -237,22 +335,44 @@ def main():
wait(lambda: hn('display-message', '-p', '-t', pane, '#{pane_current_path}') == str(project),
'Project working directory in ' + pane)
type_into_screen(shell, 'printf "%s" "$$" > ' + shlex.quote(str(project / 'shell.pid')) +
- '; printf before > ' + shlex.quote(str(project / 'keyboard.txt')))
+ '; printf before > ' + shlex.quote(str(project / 'keyboard.txt')) +
+ "; PS1='HN_NATIVE_READY> '")
wait(lambda: (project / 'keyboard.txt').read_text() == 'before', 'PTY keyboard input')
# A daemon-backed pane is not a local PTY owner and need not expose
# pane_pid. Ask the actual shell, independently of UI metadata.
pid = int((project / 'shell.pid').read_text())
start_time = Path(f'/proc/{pid}/stat').read_text().split()[21]
receipt['checks'].append('Three real hn shell panes open; the attached terminal accepts native PTY keyboard input')
- prompt = ('Create sum.py here using only the Python standard library. It must accept zero or more '
+ # Diagnose idle-terminal restoration before spending time on a model
+ # request. A later restart separately checks a running agent.
+ record_state('idle-before-restart')
+ stop_daemon()
+ daemon = start_daemon()
+ wait(ready, 'Restarted idle daemon readiness', 90)
+ assert Path(f'/proc/{pid}/stat').read_text().split()[21] == start_time
+ screen.close()
+ (output / 'idle-before-reconnect.ansi').write_bytes(screen.data)
+ screen = None
+ screen = Screen([*command, 'attach-session', '-t', 'runtime'], env, project)
+ wait_for_shell()
+ type_into_screen(shell, 'printf restored > keyboard.txt')
+ wait(lambda: (project / 'keyboard.txt').read_text() == 'restored', 'Idle shell input after restart')
+ receipt['checks'].append('Idle shell processes and all three panes survive daemon/screen restart and accept new keyboard input')
+ record_state('idle-after-restart')
+ prompt = (f'Use your file tools to create {project / "sum.py"} using only the Python standard library. '
+ 'Write the actual file to that absolute path. It must accept zero or more '
'signed integer command-line arguments, print their sum as one integer, and exit successfully. '
'No arguments must print 0. Test it. Do the work now without questions or subagents.')
+ receipt['agent_prompt'] = prompt
# Keep the agent open as it is on the OS. A completed `opencode run`
# process is archived by Harness; that is not a running pane to retain.
agent_command = shlex.join(['opencode', '--prompt', prompt])
type_into_screen(agent, 'printf "%s" "$$" > agent.pid; exec ' + agent_command)
def project_passes():
+ identity = project / 'agent.pid'
+ if identity.is_file() and not Path('/proc/' + identity.read_text().strip()).exists():
+ raise RuntimeError('The agent exited before completing its project')
if not (project / 'sum.py').is_file():
return False
before = checksum(project / 'sum.py')
@@ -280,6 +400,7 @@ def main():
assert set(before_panes) == expected_panes, ('Before restart', before_panes, expected_panes)
(output / 'agent-before-restart.txt').write_text(hn('capture-pane', '-p', '-t', agent) + '\n')
project_digest = checksum(project / 'sum.py')
+ record_state('agent-before-restart')
stop_daemon()
daemon = start_daemon()
wait(ready, 'Restarted native daemon readiness', 90)
@@ -290,7 +411,7 @@ def main():
(output / 'before-reconnect.ansi').write_bytes(screen.data)
screen = None
screen = Screen([*command, 'attach-session', '-t', 'runtime'], env, project)
- wait(lambda: screen.data, 'Reattached native screen')
+ wait_for_shell()
type_into_screen(shell, 'printf after > keyboard.txt')
wait(lambda: (project / 'keyboard.txt').read_text() == 'after', 'Keyboard input after daemon/screen restart')
assert Path(f'/proc/{pid}/stat').read_text().split()[21] == start_time
@@ -307,6 +428,29 @@ def main():
raise
finally:
cleanup_errors = []
+ try:
+ record_state('final-state')
+ except OSError as error:
+ cleanup_errors.append('State capture: ' + str(error))
+ if 'agent' in locals():
+ try:
+ (output / 'agent-final.txt').write_text(hn('capture-pane', '-p', '-t', agent) + '\n')
+ except (OSError, subprocess.SubprocessError) as error:
+ (output / 'agent-capture-error.txt').write_text(str(error) + '\n')
+ # This isolated home has no user account or credentials. Retain the
+ # agent's own diagnostic logs, never auth/provider configuration.
+ agent_logs = home / '.local/share/opencode/log'
+ try:
+ if agent_logs.is_dir():
+ shutil.copytree(agent_logs, output / 'opencode-logs')
+ try:
+ transcript = agent_transcript(home)
+ except (OSError, sqlite3.Error) as error:
+ transcript = {'status': 'unavailable', 'reason': str(error)}
+ (output / 'opencode-transcript.json').write_text(json.dumps(transcript, indent=2) + '\n')
+ receipt['discovered_project_files'] = [str(path.relative_to(base)) for path in base.rglob('sum.py')]
+ except OSError as error:
+ cleanup_errors.append('Agent log capture: ' + str(error))
if screen:
(output / 'terminal.ansi').write_bytes(screen.data)
try:
@@ -323,6 +467,11 @@ def main():
for name in ['sum.py', 'agent.pid', 'shell.pid']:
if (project / name).is_file():
shutil.copy2(project / name, output / name)
+ try:
+ receipt['cleanup_signals'] = finish_fixture_processes(home)
+ temporary_directory.cleanup()
+ except (OSError, RuntimeError) as error:
+ cleanup_errors.append('Private workspace cleanup: ' + str(error))
receipt['finished_at_unix'] = time.time()
if cleanup_errors:
receipt.update(status='failed', cleanup_errors=cleanup_errors)
diff --git a/os/tests/test_arm_boot.py b/os/tests/test_arm_boot.py
new file mode 100644
index 000000000..ea8ba9a1f
--- /dev/null
+++ b/os/tests/test_arm_boot.py
@@ -0,0 +1,55 @@
+"""Reject incompatible or truncated kernels before starting a test VM."""
+import struct
+import unittest
+
+from arm_boot import check_arm_image, zboot_payload
+
+
+class KernelImages(unittest.TestCase):
+ def zboot(self):
+ data = bytearray(80)
+ data[:8] = b'MZ\0\0zimg'
+ struct.pack_into('<II', data, 8, 64, 8)
+ data[24:28] = b'zstd'
+ data[56:60] = b'\xcd\x23\x82\x81'
+ data[64:72] = b'payload!'
+ data[72:80] = b'trailer!'
+ return data
+
+ def test_extracts_only_declared_payload(self):
+ self.assertEqual(zboot_payload(self.zboot()), b'payload!')
+
+ def test_rejects_wrong_header_compression_and_truncated_payload(self):
+ for position, replacement in [(0, b'ZZ'), (24, b'gzip'), (56, b'nope')]:
+ data = self.zboot()
+ data[position:position + len(replacement)] = replacement
+ with self.subTest(position=position), self.assertRaises(ValueError):
+ zboot_payload(data)
+ for data in [self.zboot()[:32], self.zboot()[:70]]:
+ with self.assertRaises(ValueError):
+ zboot_payload(data)
+
+ def test_rejects_payload_outside_image(self):
+ for offset, size in [(0, 8), (64, 0), (80, 1), (0xffffffff, 0xffffffff)]:
+ data = self.zboot()
+ struct.pack_into('<II', data, 8, offset, size)
+ with self.subTest(offset=offset, size=size), self.assertRaises(ValueError):
+ zboot_payload(data)
+
+ def test_accepts_only_little_endian_16k_arm_image(self):
+ data = bytearray(64)
+ data[56:60] = b'ARM\x64'
+ struct.pack_into('<Q', data, 24, 0xc)
+ check_arm_image(data)
+ for flags in [0, 2, 6, 0xd]:
+ struct.pack_into('<Q', data, 24, flags)
+ with self.subTest(flags=flags), self.assertRaises(ValueError):
+ check_arm_image(data)
+ with self.assertRaises(ValueError):
+ check_arm_image(data[:60])
+ with self.assertRaises(ValueError):
+ check_arm_image(bytes(64))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_runtime_native.py b/os/tests/test_runtime_native.py
new file mode 100644
index 000000000..a880ae9e4
--- /dev/null
+++ b/os/tests/test_runtime_native.py
@@ -0,0 +1,80 @@
+import importlib.util
+import os
+from pathlib import Path
+import signal
+import sqlite3
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+
+
+spec = importlib.util.spec_from_file_location('runtime_native', Path(__file__).with_name('runtime_native.py'))
+runtime = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(runtime)
+
+
+class AgentEvidenceTests(unittest.TestCase):
+ def test_retains_private_conversation_without_auth_or_unrelated_tables(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ home = Path(temporary)
+ folder = home / '.local/share/opencode'
+ folder.mkdir(parents=True)
+ (folder / 'auth.json').write_text('private-auth-must-not-be-retained')
+ with sqlite3.connect(folder / 'opencode.db') as db:
+ db.executescript('CREATE TABLE message (id, session_id, time_created, data);'
+ 'CREATE TABLE part (id, message_id, session_id, time_created, data);'
+ 'CREATE TABLE secret (data);'
+ "INSERT INTO secret VALUES ('private-secret');")
+ db.execute('INSERT INTO message VALUES (?, ?, ?, ?)', ('m1', 's1', 1, '{"role":"user"}'))
+ db.execute('INSERT INTO part VALUES (?, ?, ?, ?, ?)', ('p1', 'm1', 's1', 1, '{"text":"Create sum.py"}'))
+ evidence = runtime.agent_transcript(home)
+ self.assertEqual(set(evidence), {'messages', 'parts'})
+ self.assertEqual(evidence['parts'][0]['data'], '{"text":"Create sum.py"}')
+ self.assertNotIn('private-', str(evidence))
+ self.assertEqual(runtime.agent_transcript(home / 'absent')['status'], 'unavailable')
+
+
[email protected](sys.platform == 'linux' and hasattr(os, 'pidfd_open'), 'Linux process ownership check')
+class FixtureCleanupTests(unittest.TestCase):
+ def test_waits_for_own_worker_and_preserves_similarly_named_home(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ home = Path(temporary) / 'home'
+ home.mkdir()
+ other_home = Path(temporary) / 'home-other'
+ other_home.mkdir()
+ writer = "import os,time; from pathlib import Path; p=Path(os.environ['HOME'])/'worker'; p.write_text('ready'); time.sleep(60)"
+ owned = subprocess.Popen([sys.executable, '-c', writer], env={**os.environ, 'HOME': str(home)})
+ other = subprocess.Popen([sys.executable, '-c', writer], env={**os.environ, 'HOME': str(other_home)})
+ try:
+ runtime.wait(lambda: (home / 'worker').exists() and (other_home / 'worker').exists(), 'Workers', 5)
+ sent = runtime.finish_fixture_processes(home)
+ self.assertEqual(owned.wait(timeout=2), -signal.SIGTERM)
+ self.assertIsNone(other.poll())
+ self.assertEqual({item['pid'] for item in sent}, {owned.pid})
+ finally:
+ for process in [owned, other]:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=2)
+
+ def test_bounds_a_worker_that_ignores_termination(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ home = Path(temporary)
+ worker = ("import os,signal,time; from pathlib import Path; "
+ "signal.signal(signal.SIGTERM, signal.SIG_IGN); "
+ "(Path(os.environ['HOME'])/'ready').touch(); time.sleep(60)")
+ process = subprocess.Popen([sys.executable, '-c', worker], env={**os.environ, 'HOME': str(home)})
+ try:
+ runtime.wait(lambda: (home / 'ready').exists(), 'Worker', 5)
+ started = time.monotonic()
+ sent = runtime.finish_fixture_processes(home)
+ self.assertEqual(process.wait(timeout=2), -signal.SIGKILL)
+ self.assertLess(time.monotonic() - started, 10)
+ self.assertIn('SIGKILL', {item['signal'] for item in sent})
+ self.assertEqual({item['pid'] for item in sent}, {process.pid})
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=2)