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
Prepare selected Broadcom Wi-Fi for offline Harness installation (#691)
Deea9b91caddc35
diff --git a/.github/workflows/os-hardware.yml b/.github/workflows/os-hardware.ymlnew file mode 100644index 000000000..a48bd999a--- /dev/null+++ b/.github/workflows/os-hardware.yml@@ -0,0 +1,63 @@+name: Harness OS hardware preparation++on:+ workflow_dispatch:+ inputs:+ image_run_id:+ description: 'Exact Harness OS image artifact to assess'+ type: string+ default: '37142219550'+ required: true+ push:+ branches: ['os-polish/hardware-*']+ paths: ['os/tests/broadcom_*.py', '.github/workflows/os-hardware.yml']++permissions:+ contents: read+ actions: read++concurrency:+ group: harness-hardware-${{ github.ref }}+ cancel-in-progress: false++jobs:+ broadcom:+ runs-on: ubuntu-24.04+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@v7+ - uses: actions/download-artifact@v6+ with:+ name: programmer-os-x86_64+ path: os/dist+ run-id: ${{ inputs.image_run_id || '37142219550' }}+ github-token: ${{ github.token }}+ - name: Check the experiment and install VM tools+ run: |+ python3 -m py_compile os/tests/broadcom_guest.py os/tests/broadcom_vm.py+ go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os-hardware.yml+ sudo apt-get update -qq+ sudo apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr+ sudo chmod a+rw /dev/kvm+ - name: Build, reinstall offline, and load on the constrained image+ run: python3 os/tests/broadcom_vm.py --iso os/dist/*.iso+ - name: Archive package filenames unchanged+ if: always()+ run: |+ # Arch epochs put ':' in package names; upload-artifact rejects those+ # names directly. Keep original names and signatures inside one tar.+ if [ -d os/test-results/broadcom/bundle ]; then+ tar -cf os/test-results/broadcom/driver-bundle.tar -C os/test-results/broadcom/bundle .+ fi+ - name: Retain exact package, module, license and experiment evidence+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: harness-broadcom-preparation+ path: |+ os/test-results/broadcom/+ !os/test-results/broadcom/bundle/**+ !os/test-results/broadcom/**/*.qcow2+ !os/test-results/broadcom/**/OVMF_VARS.fd+ retention-days: 14+ compression-level: 0diff --git a/.github/workflows/os.yml b/.github/workflows/os.ymlindex 66db74866..4e817a139 100644--- a/.github/workflows/os.yml+++ b/.github/workflows/os.yml@@ -47,11 +47,11 @@ on:default: falsetype: booleanchecks:- description: 'Image journey, focused lock/suspend checks, or simulated Wi-Fi/audio essentials; use image_run_id to reuse an image'+ description: 'Image journey, lock/suspend, Wi-Fi/audio essentials, or offline hardware installation; image_run_id reuses an image'required: falsedefault: imagetype: choice- options: [image, session, essentials]+ options: [image, session, essentials, hardware]push:branches: ['os/**']paths: ['os/**', 'tui/**', 'cli/**', '.github/workflows/os.yml']@@ -61,7 +61,7 @@ permissions:actions: readconcurrency:- group: programmer-os-${{ github.ref }}-${{ inputs.memory_mib || '2048' }}-${{ inputs.live_transport || 'cdrom' }}-${{ inputs.development_update && 'update' || inputs.checks == 'session' && 'session' || inputs.checks == 'essentials' && 'essentials' || inputs.dsh && 'dsh' || inputs.workloads && 'workloads' || 'image' }}+ group: programmer-os-${{ github.ref }}-${{ inputs.memory_mib || '2048' }}-${{ inputs.live_transport || 'cdrom' }}-${{ inputs.development_update && 'update' || inputs.checks == 'session' && 'session' || inputs.checks == 'essentials' && 'essentials' || inputs.checks == 'hardware' && 'hardware' || inputs.dsh && 'dsh' || inputs.workloads && 'workloads' || 'image' }}cancel-in-progress: falsejobs:@@ -138,11 +138,13 @@ jobs:os/work/profile/profiledef.shos/work/profile/pacman.confos/work/archiso/x86_64/airootfs/var/log/pacman.log+ os/work/hardware-build/root/var/lib/dkms/**/make.log+ os/work/profile/airootfs/usr/share/harness-os/hardware/broadcom/manifest.jsonretention-days: 7machine:needs: image- if: ${{ always() && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'essentials' && (needs.image.result == 'success' || inputs.image_run_id != '') && !cancelled() }}+ if: ${{ always() && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'essentials' && inputs.checks != 'hardware' && (needs.image.result == 'success' || inputs.image_run_id != '') && !cancelled() }}runs-on: ubuntu-24.04timeout-minutes: 65strategy:@@ -212,6 +214,40 @@ jobs:os/test-results/**/dsh/**retention-days: 14+ hardware:+ needs: image+ if: ${{ always() && !inputs.publish_run_id && !inputs.development_update && (needs.image.result == 'success' || inputs.checks == 'hardware' && inputs.image_run_id != '') && !cancelled() }}+ runs-on: ubuntu-24.04+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@v7+ - uses: actions/download-artifact@v6+ with:+ name: programmer-os-x86_64+ path: os/dist+ run-id: ${{ inputs.image_run_id || github.run_id }}+ github-token: ${{ github.token }}+ - name: Check the fixture and install VM tools+ run: |+ python3 -m py_compile os/tests/hardware_install_guest.py os/tests/hardware_install_vm.py+ go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os.yml+ sudo apt-get update -qq+ sudo apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr+ sudo chmod a+rw /dev/kvm+ - name: Install the selected driver offline and reboot with 1 GiB+ run: python3 os/tests/hardware_install_vm.py --iso os/dist/*.iso+ - name: Retain hardware installation and rebuild evidence+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: harness-os-hardware+ path: |+ os/test-results/hardware-install/+ !os/test-results/hardware-install/*.qcow2+ !os/test-results/hardware-install/OVMF_VARS.fd+ retention-days: 14+ compression-level: 0+essentials:needs: imageif: ${{ always() && inputs.checks == 'essentials' && !inputs.publish_run_id && !inputs.development_update && (needs.image.result == 'success' || inputs.image_run_id != '') && !cancelled() }}diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.mdindex 11fbcd053..19d1810e1 100644--- a/os/DEVELOPMENT.md+++ b/os/DEVELOPMENT.md@@ -5,8 +5,8 @@ boot changes. Reflashing is a release/install test, not the intended way to tryevery interface fix. Keep the development tools on the build/test host; theinstalled OS keeps the same minimal interface.-This plan was recorded on October 3, 2026. Preview 4 and its optional small-package-update are published. Native update/rollback acceptance passed; remote-launcher+This plan was recorded on October 3, 2026. Preview 5 and its small bootstrap bundle+and update channel are published. Native update/rollback acceptance passed; remote-launcherargument tests passed but remote display/SSH interaction is still unverified.## Next release priorities@@ -238,7 +238,41 @@ the small updater; install its separately validated development bundle to add itIntel Macs and Apple Silicon are both intended OS targets. They share the Harnessinterface and behavior, but need separate platform work. None is claimed as a-validated Harness OS hardware target by preview 4.+validated Harness OS hardware target by preview 5.++The next image prepares selected older Broadcom radios by PCI ID, not Mac model.+BCM4331 (`14e4:4331`) and BCM4360 (`14e4:43a0`) may load the optional wl driver;+an already working native interface is preserved. BCM43602 and other native+brcmfmac/brcmsmac devices are outside that selection. The vendor package's broad+blacklist is overridden so it cannot disable those other drivers.++The live driver is about 2 MB. A separate signed package cache is kept on the+USB for offline installation; its compiler, DKMS and matching LTS headers are+installed only when the radio needs them. The cache is removed from every+installed system. The standard package hooks then rebuild wl on kernel updates.+The driver bundle is built in a disposable root using the same complete Arch+snapshot as the image; none of its build packages enter the normal image base.+This selection happens during a fresh installation. Updating an older installed+preview adds the device policy and report, but does not silently download driver+packages. On a connected older installation that needs wl, an agent can first+complete `sudo hn-os update`, then install `broadcom-wl-dkms linux-lts-headers`+with pacman from that same snapshot and reboot. A working native interface needs+neither package.++[Native preparation run 37145711377](https://github.com/autonomous-ai/openharness/actions/runs/37145711377)+used the exact preview 5 kernel, `6.18.54-1-lts`. Its signed extra closure was+128.76 MiB. Online package installation/build took 32.831 seconds, then removing+exactly those packages and reinstalling with networking off took 13.440 seconds.+The prebuilt module loaded on a fresh 1 GiB USB VM without GCC or DKMS, and hn+accepted keyboard input. This proves module compatibility and offline package+availability, not association with a physical access point. The integrated+candidate image and device-selection policy have their own validation records.+The Arch wl package is an unmaintained out-of-tree driver; retain its original+license and prefer a working native driver where available.++`harness hardware` produces a small local JSON report for agents and hardware+testing. It includes device IDs and current bindings, not serial numbers, SSIDs+or network addresses. No additional daemon or settings application is needed.| Target | Approach | Current Harness OS status || --- | --- | --- |@@ -254,6 +288,8 @@ reached the USB welcome and successfully ran hn, Node and Chromium versioncommands, but OpenCode exited with SIGILL (132). This is an instruction-setfinding, not physical Mac or full browser validation. Older CPUs need a separatelyvalidated agent path; do not describe them as ready for the default trial.+The OS Try action detects this limitation before Wi-Fi setup and explains it,+instead of launching a binary that immediately fails with an illegal instruction.[Bun's executable targets](https://bun.com/docs/bundler/executables) document theSSE4.2 baseline used by its compiled runtime.diff --git a/os/INSTALL.md b/os/INSTALL.mdindex 06f3e49a3..59f5656e1 100644--- a/os/INSTALL.md+++ b/os/INSTALL.md@@ -1,6 +1,6 @@# Install Harness on a ThinkPad-These instructions are for **0.1.0-preview.5**, using a Mac to prepare the USB.+These instructions are for **0.1.0-preview.6**, using a Mac to prepare the USB.The USB starts a live session. Installation begins only when you choose **Install**in the installer; it erases the entire selected disk.@@ -21,20 +21,20 @@ compute still need testing on the actual hardware.## 2. Download and verify on the Mac-From the [preview 5 release](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.5),+From the [preview 6 release](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.6),download both files into the same folder:-- `harness-0.1.0-preview.5-x86_64.iso`-- `harness-0.1.0-preview.5-x86_64.iso.sha256`+- `harness-0.1.0-preview.6-x86_64.iso`+- `harness-0.1.0-preview.6-x86_64.iso.sha256`If they are in Downloads, open Terminal and run:```shcd ~/Downloads-shasum -a 256 -c harness-0.1.0-preview.5-x86_64.iso.sha256+shasum -a 256 -c harness-0.1.0-preview.6-x86_64.iso.sha256```-The result must say `harness-0.1.0-preview.5-x86_64.iso: OK`.+The result must say `harness-0.1.0-preview.6-x86_64.iso: OK`.If it does not, download the files again before flashing.## 3. Flash the USB@@ -68,6 +68,25 @@ The welcome screen offers **Enter — Install Harness** and **T — Try withoutinstalling**. No account or password is needed to use the live session. Work inthe USB session is temporary and is not copied during installation.+### Trying an older Intel Mac++Intel Macs with a 64-bit EFI and no T2 chip are an experimental target. The USB+includes optional support for selected Broadcom radios, but no physical Mac+model has passed our complete hardware checks yet. This image is not the+Apple Silicon or T2 installation path. Core 2 CPUs cannot run bundled OpenCode;+Try explains that limitation before attempting to start it.++Shut down, insert the USB, then hold **Option (⌥)** while turning on the Mac.+Choose the external **EFI Boot** entry. Apple's+[startup-key guide](https://support.apple.com/en-us/102603) describes that menu.+Start with **T — Try without installing** and check built-in keyboard, trackpad,+Wi-Fi, brightness and sound before choosing the internal disk. Installation uses+the same form below and erases the whole selected disk, including macOS.++For a hardware report, open a terminal and run `harness hardware`. Keep that+report with the Mac's model and the behavior you observed. It contains device+IDs and driver names, without serial numbers or Wi-Fi passwords.+## 5. InstallPress **Enter** on the welcome screen. You do not need to open a terminal or typediff --git a/os/build.sh b/os/build.shindex d419aee13..8daa4b78b 100644--- a/os/build.sh+++ b/os/build.sh@@ -46,6 +46,9 @@ EOF# installation should not immediately be offered this identical build again.python3 tools/build-package.py --runtime "$RUNTIME_DIR" --output "$BUILD_DIR/repo" --developmentrepo-add "$BUILD_DIR/repo/harness-build.db.tar.gz" "$BUILD_DIR/repo/"*.pkg.tar.gz+python3 tools/build-hardware.py --config "$PROFILE/pacman.conf" \+ --work "$BUILD_DIR/hardware-build" \+ --output "$PROFILE/airootfs/usr/share/harness-os/hardware/broadcom"cp -a live/. "$PROFILE/airootfs/"mkdir -p "$PROFILE/airootfs/root" "$PROFILE/airootfs/etc/pacman.d/hooks"cp tools/customize-live.sh "$PROFILE/airootfs/root/setup-live.sh"diff --git a/os/hardware.py b/os/hardware.pynew file mode 100644index 000000000..7b959b31d--- /dev/null+++ b/os/hardware.py@@ -0,0 +1,215 @@+#!/usr/bin/env python3+"""Small, on-demand hardware diagnosis and selected Broadcom Wi-Fi preparation."""+import argparse+import fcntl+import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import subprocess+import tempfile+++# These older Mac radio families need firmware/driver support beyond the stock+# brcmfmac path. Never treat every Broadcom device as a wl device. In particular,+# BCM43602 (43ba/43bb/43bc) must keep its native driver.+# https://wireless.docs.kernel.org/en/latest/en/users/drivers/b43.html+BROADCOM_IDS = {'14e4:4331': 'BCM4331', '14e4:43a0': 'BCM4360'}+BUNDLE = Path('/usr/share/harness-os/hardware/broadcom')+PCI_NAME = re.compile(r'[0-9a-f]{4,8}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]')+++def read(path):+ try:+ return path.read_text().strip()+ except (OSError, UnicodeError):+ return ''+++def run(*args, capture=False, timeout=180):+ result = subprocess.run(list(map(str, args)), check=True, text=True, timeout=timeout,+ stdout=subprocess.PIPE if capture else None)+ return result.stdout.strip() if capture else None+++def digest(path):+ with path.open('rb') as handle:+ return hashlib.file_digest(handle, 'sha256').hexdigest()+++def pci_devices(sysfs=Path('/sys')):+ devices = []+ for path in sorted((sysfs / 'bus/pci/devices').glob('*')):+ if not PCI_NAME.fullmatch(path.name):+ continue+ vendor, device, kind = (read(path / name).removeprefix('0x') for name in ['vendor', 'device', 'class'])+ if not re.fullmatch(r'[0-9a-f]{4}', vendor) or not re.fullmatch(r'[0-9a-f]{4}', device):+ continue+ interfaces = []+ for interface in (sysfs / 'class/net').glob('*'):+ if (interface / 'device').is_symlink() and (interface / 'device').resolve().is_relative_to(path.resolve()):+ interfaces.append({'name': interface.name, 'wireless': (interface / 'wireless').is_dir() or (interface / 'phy80211').exists()})+ driver = (path / 'driver').resolve().name if (path / 'driver').is_symlink() else None+ devices.append({'address': path.name, 'id': vendor + ':' + device,+ 'class': kind, 'driver': driver, 'interfaces': interfaces})+ return devices+++def needs_broadcom(device):+ return device['id'] in BROADCOM_IDS and device['class'] == '028000' and (+ device['driver'] == 'wl' or not any(i['wireless'] for i in device['interfaces']))+++def report(sysfs=Path('/sys'), proc=Path('/proc')):+ fields = {}+ for line in read(proc / 'cpuinfo').splitlines():+ if ':' in line:+ key, value = line.split(':', 1)+ fields.setdefault(key.strip(), value.strip())+ flags = fields.get('flags')+ return {'architecture': os.uname().machine, 'kernel': os.uname().release,+ 'computer': {'vendor': read(sysfs / 'class/dmi/id/sys_vendor') or None,+ 'model': read(sysfs / 'class/dmi/id/product_name') or None},+ 'efi_bits': read(sysfs / 'firmware/efi/fw_platform_size') or None,+ 'opencode_cpu': {'required_x86_feature': 'sse4_2',+ 'available': 'sse4_2' in flags.split() if flags is not None else None},+ 'pci': pci_devices(sysfs),+ 'backlights': [p.name for p in sorted((sysfs / 'class/backlight').glob('*'))],+ 'broadcom_bundle_available': (BUNDLE / 'manifest.json').is_file()}+++def bundle_manifest(folder, all_files=False):+ manifest = json.loads((folder / 'manifest.json').read_text())+ if manifest.get('schema') != 1 or manifest.get('driver') != 'broadcom-wl' or manifest.get('architecture') != 'x86_64':+ raise ValueError('Unsupported Wi-Fi bundle.')+ module = manifest.get('module', '')+ if module not in {'wl.ko', 'wl.ko.zst', 'wl.ko.xz'} or module not in manifest.get('files', {}):+ raise ValueError('Wi-Fi module is missing from its manifest.')+ for name, expected in manifest['files'].items():+ relative = Path(name)+ if relative.is_absolute() or '..' in relative.parts or len(relative.parts) > 2:+ raise ValueError('Invalid Wi-Fi bundle path.')+ path = folder / name+ if path.is_symlink() or not path.resolve().is_relative_to(folder.resolve()):+ raise ValueError('Wi-Fi bundle files must stay inside their directory.')+ if all_files or name == module:+ if not path.is_file() or path.stat().st_size != expected['bytes'] or digest(path) != expected['sha256']:+ raise ValueError('Wi-Fi bundle checksum mismatch: ' + name)+ return manifest+++def activate(address, sysfs=Path('/sys'), bundle=BUNDLE):+ if not PCI_NAME.fullmatch(address):+ raise ValueError('Invalid PCI address.')+ devices = pci_devices(sysfs)+ device = next((d for d in devices if d['address'] == address), None)+ if not device or not needs_broadcom(device) or device['driver'] == 'wl':+ return {'status': 'unchanged', 'address': address}+ if device['driver'] not in {None, 'bcma-pci-bridge', 'ssb'}:+ return {'status': 'unchanged', 'address': address, 'reason': 'Keep an existing driver.'}+ # Verify availability before changing a binding. The live image carries only+ # a prebuilt module here; installed machines use the ordinary DKMS package.+ if (bundle / 'manifest.json').is_file():+ manifest = bundle_manifest(bundle)+ if manifest['kernel'] != os.uname().release:+ raise ValueError('The Wi-Fi bundle is for a different kernel.')+ loader = ['insmod', str(bundle / manifest['module'])]+ else:+ run('modinfo', 'wl', capture=True, timeout=5)+ loader = ['modprobe', 'wl']+ path = sysfs / 'bus/pci/devices' / address+ previous = read(path / 'driver_override')+ previous = '' if previous == '(null)' else previous+ try:+ (path / 'driver_override').write_text('wl\n')+ if device['driver']:+ (path / 'driver/unbind').write_text(address + '\n')+ run('modprobe', 'cfg80211', timeout=8)+ if not (sysfs / 'module/wl').is_dir():+ run(*loader, timeout=15)+ if not (path / 'driver').is_symlink():+ (sysfs / 'bus/pci/drivers_probe').write_text(address + '\n')+ if not (path / 'driver').is_symlink() or (path / 'driver').resolve().name != 'wl':+ raise RuntimeError('Wi-Fi driver did not bind to ' + address)+ return {'status': 'activated', 'address': address, 'driver': 'wl'}+ except BaseException:+ (path / 'driver_override').write_text(previous + '\n')+ if not (path / 'driver').is_symlink():+ (sysfs / 'bus/pci/drivers_probe').write_text(address + '\n')+ raise+++def configure_install(target, devices=None):+ target = target.resolve()+ # Only the offline installer's mounted, still-marked image may use this path.+ # It must never install a compiler into the running live overlay by mistake.+ if target == Path('/') or not target.is_mount() or not (target / 'etc/harness-live').is_file():+ raise ValueError('Wi-Fi preparation requires the mounted installation image.')+ selected = [d for d in (pci_devices() if devices is None else devices) if needs_broadcom(d)]+ folder = target / BUNDLE.relative_to('/')+ result = {'drivers': [], 'devices': [d['id'] for d in selected]}+ if selected:+ manifest = bundle_manifest(folder, all_files=True)+ lock = json.loads((target / 'usr/share/harness-os/lock.json').read_text())+ if manifest['arch_snapshot'] != lock['arch_snapshot']:+ raise ValueError('Wi-Fi bundle and installed package snapshot differ.')+ output = run('arch-chroot', target, 'pacman', '-Q', *manifest['base_packages'], capture=True)+ actual = dict(line.split(' ', 1) for line in output.splitlines())+ if actual != manifest['base_packages']:+ raise ValueError('Wi-Fi dependencies differ from the validated base.')+ names = sorted(manifest['packages'])+ if not names or any(not re.fullmatch(r'[a-zA-Z0-9_+.:\-]+\.pkg\.tar\.zst', name) for name in names):+ raise ValueError('Invalid offline Wi-Fi package list.')+ for name in names:+ if 'packages/' + name not in manifest['files'] or 'packages/' + name + '.sig' not in manifest['files']:+ raise ValueError('Offline Wi-Fi packages require signatures.')+ # No repositories: this operation either succeeds from signed local+ # packages or fails. It cannot quietly turn into an online installation.+ with tempfile.TemporaryDirectory(prefix='harness-driver-', dir=target / 'var/tmp') as temporary:+ config = Path(temporary) / 'pacman.conf'+ config.write_text('[options]\nArchitecture = auto\nCheckSpace\nSigLevel = Required\nLocalFileSigLevel = Required\n')+ config.chmod(0o600)+ run('arch-chroot', target, 'pacman', '--config', '/' + str(config.relative_to(target)),+ '-U', '--needed', '--noconfirm', *[str(BUNDLE / 'packages' / name) for name in names], timeout=600)+ run('arch-chroot', target, 'modinfo', '-k', manifest['kernel'], 'wl', capture=True)+ result.update(drivers=['broadcom-wl-dkms'], kernel=manifest['kernel'], packages=manifest['packages'])+ # The USB keeps the offline cache; the installed computer does not. Unrelated+ # machines receive neither wl nor its compiler/kernel-header dependencies.+ shutil.rmtree(folder, ignore_errors=False)+ state = target / 'var/lib/harness-os/hardware.json'+ state.parent.mkdir(parents=True, exist_ok=True)+ state.write_text(json.dumps(result, indent=2) + '\n')+ return result+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest='command')+ sub.add_parser('report')+ activation = sub.add_parser('activate')+ activation.add_argument('address')+ installation = sub.add_parser('configure-install')+ installation.add_argument('target', type=Path)+ args = parser.parse_args()+ if args.command in {'activate', 'configure-install'} and os.geteuid() != 0:+ parser.error('This operation requires root.')+ if args.command == 'activate':+ # Multiple matching PCI add events must not race the module load.+ descriptor = os.open('/run/lock/harness-broadcom.lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)+ with os.fdopen(descriptor, 'r+') as lock:+ stat = os.fstat(lock.fileno())+ if stat.st_uid != 0 or stat.st_mode & 0o022:+ raise ValueError('Wi-Fi activation lock is not root-owned and private.')+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)+ result = activate(args.address)+ elif args.command == 'configure-install':+ result = configure_install(args.target)+ else:+ result = report()+ print(json.dumps(result, indent=2))+++if __name__ == '__main__':+ main()diff --git a/os/installer.py b/os/installer.pyindex cc81aff22..24f7be8c1 100644--- a/os/installer.py+++ b/os/installer.py@@ -230,7 +230,7 @@ def install(config, source, target, progress=None):# The live image is immutable. No live passwords, SSH keys or sessions are copied.for path in ['etc/sudoers.d/10-live', 'etc/mkinitcpio.conf.d/archiso.conf','etc/systemd/system/[email protected]/live.conf',- 'etc/pacman.d/hooks/99-harness-live.hook', 'root/setup-live.sh', 'etc/harness-live']:+ 'etc/pacman.d/hooks/99-harness-live.hook', 'root/setup-live.sh']:(target / path).unlink(missing_ok=True)for path in ['etc/systemd/system/[email protected]', 'root/.ssh']:shutil.rmtree(target / path, ignore_errors=True)@@ -295,6 +295,10 @@ def install(config, source, target, progress=None):chroot(target, 'systemctl', 'disable', 'sshd.service')report('Preparing startup and recovery…')chroot(target, '/usr/lib/harness-os/init-keyring')+ # Keep the live marker through this initial optional package transaction,+ # so recovery hooks do not checkpoint an unfinished installation.+ run('/usr/bin/python3', '/usr/lib/harness-os/hardware.py', 'configure-install', target)+ (target / 'etc/harness-live').unlink()chroot(target, 'mkinitcpio', '-P')chroot(target, 'grub-install', '--target=i386-pc', '--recheck', disk)chroot(target, 'grub-install', '--target=x86_64-efi', '--efi-directory=/boot', '--boot-directory=/boot', '--removable', '--no-nvram')diff --git a/os/lock.json b/os/lock.jsonindex c6c8f6457..d6e958fc8 100644--- a/os/lock.json+++ b/os/lock.json@@ -1,8 +1,9 @@{- "version": "0.1.0-preview.5",+ "version": "0.1.0-preview.6","arch_snapshot": "2026/10/01","architecture": "x86_64","upgrades_from": [+ {"version": "0.1.0-preview.5", "arch_snapshot": "2026/10/01"},{"version": "0.1.0-preview.4", "arch_snapshot": "2026/10/01"}]}diff --git a/os/root/etc/modprobe.d/broadcom-wl-dkms.conf b/os/root/etc/modprobe.d/broadcom-wl-dkms.confnew file mode 100644index 000000000..2b70802b0--- /dev/null+++ b/os/root/etc/modprobe.d/broadcom-wl-dkms.conf@@ -0,0 +1,2 @@+# Override the vendor package's global blacklist. Harness selects wl by PCI+# device; brcmfmac, brcmsmac, b43 and other native drivers must remain available.diff --git a/os/root/usr/bin/harness b/os/root/usr/bin/harnessindex 139bf0d8c..542b91dba 100644--- a/os/root/usr/bin/harness+++ b/os/root/usr/bin/harness@@ -1,4 +1,8 @@#!/bin/sh+if [ "${1:-}" = hardware ]; then+ shift+ exec /usr/bin/python3 /usr/lib/harness-os/hardware.py report "$@"+fiif [ "${1:-}" = install ]; thenshiftexec /usr/bin/python3 /usr/lib/harness-os/install.py "$@"diff --git a/os/root/usr/lib/modprobe.d/harness-wl.conf b/os/root/usr/lib/modprobe.d/harness-wl.confnew file mode 100644index 000000000..b5ea537fe--- /dev/null+++ b/os/root/usr/lib/modprobe.d/harness-wl.conf@@ -0,0 +1,2 @@+# wl advertises a broad PCI alias. Only the selected-hardware service may load it.+blacklist wldiff --git a/os/root/usr/lib/systemd/system/[email protected] b/os/root/usr/lib/systemd/system/[email protected]new file mode 100644index 000000000..8546217f6--- /dev/null+++ b/os/root/usr/lib/systemd/system/[email protected]@@ -0,0 +1,9 @@+[Unit]+Description=Prepare the selected Broadcom Wi-Fi device+After=local-fs.target systemd-udevd.service+ConditionPathExists=/sys/bus/pci/devices/%I++[Service]+Type=oneshot+ExecStart=/usr/bin/python3 /usr/lib/harness-os/hardware.py activate %I+TimeoutStartSec=45diff --git a/os/root/usr/lib/udev/rules.d/81-harness-broadcom.rules b/os/root/usr/lib/udev/rules.d/81-harness-broadcom.rulesnew file mode 100644index 000000000..1a5be3d4b--- /dev/null+++ b/os/root/usr/lib/udev/rules.d/81-harness-broadcom.rules@@ -0,0 +1,2 @@+ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x14e4", ATTR{device}=="0x4331", TAG+="systemd", ENV{SYSTEMD_WANTS}+="harness-broadcom@%k.service"+ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x14e4", ATTR{device}=="0x43a0", TAG+="systemd", ENV{SYSTEMD_WANTS}+="harness-broadcom@%k.service"diff --git a/os/root/usr/share/harness-os/AGENTS.md b/os/root/usr/share/harness-os/AGENTS.mdindex 68e0b8913..676d55582 100644--- a/os/root/usr/share/harness-os/AGENTS.md+++ b/os/root/usr/share/harness-os/AGENTS.md@@ -46,6 +46,14 @@ is required.## Network and hardware+- `harness hardware` reports the model, CPU baseline, PCI devices, bound drivers+ and backlights. It does not collect serial numbers, Wi-Fi names, MAC addresses+ or passwords. Use actual device IDs when diagnosing hardware.+- The USB carries a prebuilt wl module and signed offline packages for selected+ BCM4331/BCM4360 radios. The installer adds DKMS and matching LTS headers only+ where needed, so future kernel upgrades can rebuild the driver. Other Broadcom+ families keep their native drivers. Do not apply a blanket Broadcom blacklist.+ Driver build/load checks are not evidence of physical radio or suspend support.- Ethernet uses NetworkManager automatically. For Wi-Fi, use`hn-os wifi`, which opens NetworkManager’s keyboard interface.Keep passwords out of shell arguments and transcripts.diff --git a/os/tests/broadcom_guest.py b/os/tests/broadcom_guest.pynew file mode 100644index 000000000..e7004562f--- /dev/null+++ b/os/tests/broadcom_guest.py@@ -0,0 +1,121 @@+#!/usr/bin/env python3+"""Probe a signed, snapshot-matched Broadcom driver in a disposable live guest."""+import base64+import hashlib+import json+from pathlib import Path+import shutil+import subprocess+import sys+import tarfile+import time+from urllib.request import Request, urlopen+++def run(*args):+ return subprocess.check_output(args, text=True, timeout=420).strip()+++def packages():+ return dict(line.split(' ', 1) for line in run('pacman', '-Q').splitlines())+++def identity(path):+ with path.open('rb') as handle:+ digest = hashlib.file_digest(handle, 'sha256').hexdigest()+ return {'bytes': path.stat().st_size, 'sha256': digest}+++def main():+ assert Path('/etc/harness-live').is_file(), 'Disposable live guest only'+ url = sys.argv[1]+ assert url.startswith('http://10.0.2.2:'), 'Private QEMU host only'+ started = time.time()+ root = Path('/root/broadcom-probe')+ root.mkdir()+ kernel = run('uname', '-r')+ baseline = packages()+ run('systemctl', 'start', 'harness-keyring.service')+ run('nm-online', '-q', '--timeout=60')+ # The image already carries databases for its complete dated repository.+ # Do not refresh one repository or upgrade this base during the experiment.+ build_started = time.monotonic()+ run('pacman', '-S', '--needed', '--noconfirm', 'broadcom-wl-dkms', 'linux-lts-headers')+ build_seconds = time.monotonic() - build_started+ after = packages()+ assert all(after.get(name) == version for name, version in baseline.items())+ added = {name: version for name, version in after.items() if name not in baseline}+ assert {'broadcom-wl-dkms', 'linux-lts-headers', 'dkms'}.issubset(added)+ module = Path(run('modinfo', '-n', 'wl'))+ vermagic = run('modinfo', '-F', 'vermagic', str(module))+ assert vermagic.split()[0] == kernel, (vermagic, kernel)+ run('modprobe', 'wl')+ assert Path('/sys/module/wl').is_dir()+ run('modprobe', '-r', 'wl')+ shutil.copyfile(module, root / module.name)+ shutil.copyfile('/usr/share/licenses/broadcom-wl-dkms/LICENSE', root / 'LICENSE.broadcom-wl')++ # Retain the signed package closure needed on this exact base. Independently+ # verify detached signatures before considering the offline bundle usable.+ descriptions = {}+ for database in Path('/var/lib/pacman/sync').glob('*.db'):+ with tarfile.open(database) as archive:+ for member in archive:+ if not member.name.endswith('/desc'):+ continue+ blocks = archive.extractfile(member).read().decode().split('\n\n')+ fields = {lines[0]: lines[1:] for block in blocks if (lines := block.strip().splitlines())}+ name = fields.get('%NAME%', [''])[0]+ if name in added:+ descriptions[name] = fields+ archives = []+ for name, version in sorted(added.items()):+ fields = descriptions[name]+ assert fields['%VERSION%'] == [version]+ filename = fields['%FILENAME%'][0]+ source = Path('/var/cache/pacman/pkg') / filename+ assert identity(source)['sha256'] == fields['%SHA256SUM%'][0]+ target = root / filename+ shutil.copyfile(source, target)+ signature = target.with_name(target.name + '.sig')+ signature.write_bytes(base64.b64decode(fields['%PGPSIG%'][0], validate=True))+ run('pacman-key', '--verify', str(signature), str(target))+ archives.append(target)++ # Remove exactly the newly added packages, then repeat with networking off.+ # This checks the closure rather than counting a cached successful build.+ run('pacman', '-R', '--noconfirm', *sorted(added))+ assert packages() == baseline+ run('nmcli', 'networking', 'off')+ config = root / 'pacman-signed.conf'+ config.write_text(Path('/etc/pacman.conf').read_text().replace(+ 'LocalFileSigLevel = Optional', 'LocalFileSigLevel = Required'))+ assert 'LocalFileSigLevel = Required' in config.read_text()+ offline_started = time.monotonic()+ run('pacman', '--config', str(config), '-U', '--noconfirm', *map(str, archives))+ offline_seconds = time.monotonic() - offline_started+ assert packages() == after+ run('modprobe', 'wl')+ assert Path('/sys/module/wl').is_dir()+ run('modprobe', '-r', 'wl')+ config.unlink()+ receipt = {'status': 'passed', 'scope': 'kernel module and offline package closure; no physical radio',+ 'started_at': started, 'finished_at': time.time(), 'kernel': kernel,+ 'vermagic': vermagic, 'module': module.name,+ 'arch_snapshot': json.loads(Path('/usr/share/harness-os/lock.json').read_text())['arch_snapshot'],+ 'package_versions': added, 'online_install_and_build_seconds': round(build_seconds, 3),+ 'offline_install_and_build_seconds': round(offline_seconds, 3),+ 'blacklist_packaged_by_upstream': Path('/usr/lib/modprobe.d/broadcom-wl-dkms.conf').read_text(),+ 'files': {p.name: identity(p) for p in sorted(root.iterdir())}}+ (root / 'driver-receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')+ run('nmcli', 'networking', 'on')+ run('nm-online', '-q', '--timeout=60')+ for path in sorted(root.iterdir()):+ request = Request(url + '/' + path.name, data=path.read_bytes(), method='PUT')+ with urlopen(request, timeout=90) as response:+ assert response.status == 201+ print('HN_BROADCOM_PROBE=' + json.dumps(receipt))+++if __name__ == '__main__':+ main()diff --git a/os/tests/broadcom_vm.py b/os/tests/broadcom_vm.pynew file mode 100644index 000000000..5d26a3190--- /dev/null+++ b/os/tests/broadcom_vm.py@@ -0,0 +1,153 @@+#!/usr/bin/env python3+"""Build/load wl and verify its offline closure; this does not test a Mac radio."""+import argparse+import hashlib+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import re+import shlex+import subprocess+import threading+import time+from vm import VM, check_graphical_keyboard+++def digest(path):+ with path.open('rb') as handle:+ return hashlib.file_digest(handle, 'sha256').hexdigest()+++class UserView:+ """Run shared graphical acceptance as the live session owner, not root."""+ def __init__(self, vm):+ self.vm = vm++ def __getattr__(self, name):+ return getattr(self.vm, name)++ def command(self, command, **kwargs):+ return self.vm.command('runuser -u me -- env XDG_RUNTIME_DIR=/run/user/1000 '+ 'DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus sh -c ' ++ shlex.quote(command), **kwargs)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--iso', type=Path, required=True)+ parser.add_argument('--output', type=Path, default=Path('os/test-results/broadcom'))+ args = parser.parse_args()+ if not os.access('/dev/kvm', os.R_OK | os.W_OK):+ parser.error('Native x86 KVM is required')+ iso = args.iso.resolve()+ manifest = json.loads(iso.with_name('manifest.json').read_text())+ assert digest(iso) == manifest['iso']['sha256']+ folder = args.output.resolve()+ folder.mkdir(parents=True, exist_ok=False)+ artifacts = folder / 'bundle'+ artifacts.mkdir()+ (artifacts / 'broadcom_guest.py').write_bytes(Path(__file__).with_name('broadcom_guest.py').read_bytes())++ class Transfer(SimpleHTTPRequestHandler):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, directory=str(artifacts), **kwargs)++ def do_PUT(self):+ name = self.path.removeprefix('/')+ allowed = re.fullmatch(r'[a-zA-Z0-9_+.:\-]+\.pkg\.tar\.zst(?:\.sig)?', name)+ allowed = allowed or name in {'wl.ko', 'wl.ko.zst', 'wl.ko.xz', 'LICENSE.broadcom-wl', 'driver-receipt.json'}+ try:+ size = int(self.headers.get('Content-Length', '0'))+ except ValueError:+ size = 0+ if not allowed or not 0 < size <= 256 * 1024 * 1024 or self.headers.get('Transfer-Encoding'):+ self.send_error(400)+ return+ target = artifacts / name+ if target.exists():+ self.send_error(409)+ return+ self.connection.settimeout(90)+ remaining = size+ with target.open('xb') as handle:+ while remaining:+ data = self.rfile.read(min(1024 * 1024, remaining))+ if not data:+ raise EOFError('Incomplete guest artifact')+ handle.write(data)+ remaining -= len(data)+ self.send_response(201)+ self.send_header('Content-Length', '0')+ self.end_headers()++ server = ThreadingHTTPServer(('127.0.0.1', 0), Transfer)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ url = f'http://10.0.2.2:{server.server_port}'+ source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()+ receipt = {'status': 'running', 'started_at': time.time(), 'source_commit': source,+ 'image': manifest, 'scope': 'exact-kernel Broadcom module, offline closure, constrained live load',+ 'limitations': ['No physical Intel Mac or Broadcom radio is available; association and suspend are unverified.']}+ vm = None+ try:+ build = folder / 'build'+ build.mkdir()+ vm = VM(build, iso, 'bios', 4096)+ vm.start(live=True)+ vm.wait(r'root@[^\r\n]*[#] ', timeout=180)+ vm.shell_ready = True+ vm.command('stty -echo')+ vm.command('nm-online -q --timeout=60 && curl --fail --silent --show-error ' ++ shlex.quote(url + '/broadcom_guest.py') + ' -o /tmp/broadcom_guest.py')+ output, _ = vm.command('python3 /tmp/broadcom_guest.py ' + shlex.quote(url), timeout=1000)+ (build / 'build.log').write_text(output)+ result = json.loads((artifacts / 'driver-receipt.json').read_text())+ assert result['status'] == 'passed'+ for name, expected in result['files'].items():+ path = artifacts / name+ assert path.parent == artifacts+ assert path.stat().st_size == expected['bytes'] and digest(path) == expected['sha256']+ receipt['driver'] = result+ vm.stop()++ # A real USB needs the module before it has a network or build toolchain.+ # Test that path on the unmodified base with just 1 GiB RAM.+ constrained = folder / 'constrained'+ constrained.mkdir()+ vm = VM(constrained, iso, 'bios', 1024, 'usb')+ vm.start(live=True)+ vm.wait(r'root@[^\r\n]*[#] ', timeout=180)+ vm.shell_ready = True+ vm.command('stty -echo; nm-online -q --timeout=60')+ name = result['module']+ vm.command('curl --fail --silent --show-error ' + shlex.quote(url + '/' + name) + ' -o /tmp/' + shlex.quote(name))+ vm.command('test "$(sha256sum /tmp/' + name + ' | cut -d " " -f1)" = ' + shlex.quote(result['files'][name]['sha256']))+ vm.command('nmcli networking off && modprobe cfg80211 && insmod /tmp/' + shlex.quote(name))+ vm.command('test -d /sys/module/wl && ! pacman -Q dkms && ! pacman -Q gcc')+ user = UserView(vm)+ user.command('/usr/lib/harness-os/wait-runtime', timeout=160)+ receipt['constrained_keyboard'] = check_graphical_keyboard(user, 'driver-loaded')+ vm.command('rmmod wl')+ receipt['status'] = 'passed'+ except BaseException as error:+ receipt.update(status='failed', error=str(error))+ if vm:+ try:+ vm.screenshot('failure')+ output, _ = vm.command('tail -100 /var/log/pacman.log; dkms status; dmesg | tail -100', timeout=30, check=False)+ (folder / 'failure-diagnostics.log').write_text(output)+ except Exception:+ pass+ raise+ finally:+ receipt['finished_at'] = time.time()+ (folder / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')+ if vm:+ vm.stop()+ server.shutdown()+ server.server_close()+++if __name__ == '__main__':+ main()diff --git a/os/tests/hardware_install_guest.py b/os/tests/hardware_install_guest.pynew file mode 100644index 000000000..46b776e12--- /dev/null+++ b/os/tests/hardware_install_guest.py@@ -0,0 +1,91 @@+#!/usr/bin/env python3+"""Exercise the real offline installer with an explicit radio-selection fixture.++QEMU has no Broadcom radio. Only device discovery is substituted; the image's+installer, bundle verification, pacman, signature checks and DKMS run normally.+"""+import importlib.util+import json+from pathlib import Path+import subprocess+import time+++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+++def main():+ hardware = load('hardware', '/usr/lib/harness-os/hardware.py')+ installer = load('installer', '/usr/lib/harness-os/install.py')+ assert subprocess.check_output(['nmcli', 'networking'], text=True).strip() == 'disabled'+ bundle = hardware.bundle_manifest(hardware.BUNDLE, all_files=True)+ baseline = subprocess.check_output(['pacman', '-Q'], text=True)+ for name in ['broadcom-wl-dkms', 'dkms', 'gcc', 'linux-lts-headers']:+ assert not any(line.startswith(name + ' ') for line in baseline.splitlines())+ hardware.run('modprobe', 'cfg80211')+ hardware.run('insmod', hardware.BUNDLE / bundle['module'])+ assert Path('/sys/module/wl').is_dir()+ hardware.run('rmmod', 'wl')++ config = dict(disk='/dev/vda', expected_serial='HN_OS_TEST', confirm_erase='/dev/vda',+ username='me', hostname='harness', password='test-password-123',+ encrypt=True, serial_console=True)+ installer.selected_disk(config)+ devices = [dict(address='0000:03:00.0', id='14e4:43a0',+ **{'class': '028000'}, driver=None, interfaces=[])]+ original_run = installer.run+ evidence = {}++ def hardware_selection(*args, **kwargs):+ if args[:3] != ('/usr/bin/python3', '/usr/lib/harness-os/hardware.py', 'configure-install'):+ return original_run(*args, **kwargs)+ target = Path(args[3])+ module = target / hardware.BUNDLE.relative_to('/') / bundle['module']+ original_module = module.read_bytes()+ before = hardware.run('arch-chroot', target, 'pacman', '-Q', capture=True)+ # Corruption must fail before a package transaction or binding change.+ module.write_bytes(b'corrupt-module')+ try:+ hardware.configure_install(target, devices)+ except ValueError as error:+ assert 'checksum' in str(error), error+ else:+ raise AssertionError('The installer accepted a damaged Wi-Fi bundle')+ finally:+ module.write_bytes(original_module)+ assert hardware.run('arch-chroot', target, 'pacman', '-Q', capture=True) == before+ started = time.monotonic()+ result = hardware.configure_install(target, devices)+ after = hardware.run('arch-chroot', target, 'pacman', '-Q', capture=True)+ old = dict(line.split(' ', 1) for line in before.splitlines())+ new = dict(line.split(' ', 1) for line in after.splitlines())+ assert all(new.get(name) == version for name, version in old.items()), 'An existing base package changed'+ added = {name: version for name, version in new.items() if name not in old}+ assert added == {value['name']: value['version'] for value in bundle['packages'].values()}, added+ assert not (target / hardware.BUNDLE.relative_to('/')).exists()+ assert result['drivers'] == ['broadcom-wl-dkms']+ assert hardware.run('arch-chroot', target, 'modinfo', '-k', bundle['kernel'], '-F', 'vermagic', 'wl', capture=True).split()[0] == bundle['kernel']+ overrides = hardware.run('arch-chroot', target, 'modprobe', '--showconfig', capture=True)+ for name in ['b43', 'brcmfmac', 'brcmsmac', 'bcma', 'ssb']:+ assert 'blacklist ' + name not in overrides.splitlines(), 'A native driver was globally blocked'+ assert 'blacklist wl' in overrides.splitlines()+ evidence.update(optional_packages=added, offline_prepare_seconds=round(time.monotonic() - started, 3),+ corrupted_bundle_rejected=True, cache_removed=True, base_packages_unchanged=True,+ native_drivers_preserved=True, hardware_state=result)+ return None++ installer.run = hardware_selection+ started = time.monotonic()+ installer.install(config, installer.live_payload(), Path('/mnt/harness-os'))+ assert evidence, 'The actual installer did not invoke hardware preparation'+ evidence.update(status='passed', kernel=bundle['kernel'], installation_seconds=round(time.monotonic() - started, 3),+ scope='Offline encrypted installation with synthetic PCI selection; no physical radio')+ print('HN_HARDWARE_RESULT=' + json.dumps(evidence), flush=True)+++if __name__ == '__main__':+ main()diff --git a/os/tests/hardware_install_vm.py b/os/tests/hardware_install_vm.pynew file mode 100644index 000000000..df7353ec7--- /dev/null+++ b/os/tests/hardware_install_vm.py@@ -0,0 +1,99 @@+#!/usr/bin/env python3+"""Validate optional hardware packages on the actual ISO and installed system."""+import argparse+import base64+import hashlib+import json+import os+from pathlib import Path+import re+import shlex+import subprocess+import time+from vm import VM, check_graphical_keyboard+++def digest(path):+ with path.open('rb') as handle:+ return hashlib.file_digest(handle, 'sha256').hexdigest()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--iso', required=True, type=Path)+ parser.add_argument('--output', type=Path, default=Path('os/test-results/hardware-install'))+ args = parser.parse_args()+ if not os.access('/dev/kvm', os.R_OK | os.W_OK):+ parser.error('Native x86 KVM is required')+ iso = args.iso.resolve()+ manifest = json.loads(iso.with_name('manifest.json').read_text())+ assert digest(iso) == manifest['iso']['sha256']+ assert 'broadcom-offline' in manifest['capabilities']+ folder = args.output.resolve()+ folder.mkdir(parents=True, exist_ok=False)+ config = dict(username='me', password='test-password-123', encrypt=True)+ receipt = dict(status='running', started_at=time.time(), iso_sha256=manifest['iso']['sha256'],+ image_source_commit=manifest['source_commit'],+ test_source_commit=subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(),+ memory_mib=1024, firmware='uefi', live_transport='usb',+ limitations=['Synthetic PCI selection; physical Wi-Fi association and Mac sleep/wake remain unverified.'])+ vm = VM(folder, iso, 'uefi', 1024, 'usb')+ try:+ vm.start(live=True)+ vm.wait(r'root@[^\r\n]*[#] ', timeout=180)+ vm.shell_ready = True+ vm.command('stty -echo; nmcli networking off')+ script = Path(__file__).with_name('hardware_install_guest.py')+ encoded = base64.b64encode(script.read_bytes()).decode()+ vm.command('umask 077; : > /run/hardware-test.b64')+ # Serial canonical mode caps each line; no network is needed to stage it.+ for offset in range(0, len(encoded), 2400):+ vm.command('printf %s ' + shlex.quote(encoded[offset:offset + 2400]) + ' >> /run/hardware-test.b64')+ vm.command('base64 -d /run/hardware-test.b64 > /run/hardware-test.py')+ receipt['guest_fixture_sha256'] = digest(script)+ output, _ = vm.command('python3 /run/hardware-test.py', timeout=1200)+ (folder / 'installation.log').write_text(output)+ match = re.search(r'HN_HARDWARE_RESULT=(\{[^\r\n]+\})', output)+ assert match, 'Offline hardware acceptance receipt is missing'+ receipt['installation'] = json.loads(match.group(1))+ assert receipt['installation']['status'] == 'passed'+ vm.screenshot('01-live-install-complete')+ vm.command('sync')+ vm.stop()+ vm.start(live=False)+ vm.login_installed(config)+ receipt['keyboard'] = check_graphical_keyboard(vm, 'optional-wifi-installed')+ vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S true')+ vm.command('sudo nmcli networking off')+ vm.command('test ! -e /usr/share/harness-os/hardware/broadcom && test ! -e /etc/harness-live')+ output, _ = vm.command('pacman -Q broadcom-wl-dkms dkms gcc linux-lts-headers; dkms status; harness hardware')+ (folder / 'installed-hardware.txt').write_text(output)+ source = "$(find /usr/src -maxdepth 1 -type d -name 'broadcom-wl-*' -printf '%f\\n')"+ command = 'version=' + source + '; version=${version#broadcom-wl-}; test -n "$version" && '+ command += 'sudo dkms build --force -m broadcom-wl -v "$version" -k "$(uname -r)" && '+ command += 'sudo dkms install --force -m broadcom-wl -v "$version" -k "$(uname -r)" && '+ command += 'sudo modprobe wl && test -d /sys/module/wl && sudo modprobe -r wl'+ started = time.monotonic()+ output, _ = vm.command(command, timeout=600)+ (folder / 'installed-rebuild.log').write_text(output)+ receipt['installed_offline_rebuild_seconds'] = round(time.monotonic() - started, 3)+ receipt['post_rebuild_keyboard'] = check_graphical_keyboard(vm, 'driver-rebuilt')+ vm.screenshot('02-installed-driver-rebuilt')+ receipt['status'] = 'passed'+ except BaseException as error:+ receipt.update(status='failed', error=str(error))+ try:+ vm.screenshot('failure')+ output, _ = vm.command('tail -100 /var/log/pacman.log; dkms status; systemctl --failed --no-pager', timeout=30, check=False)+ (folder / 'failure-diagnostics.log').write_text(output)+ except Exception:+ pass+ raise+ finally:+ receipt['finished_at'] = time.time()+ (folder / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')+ vm.stop()+++if __name__ == '__main__':+ main()diff --git a/os/tests/test_first_use.py b/os/tests/test_first_use.pyindex c94298895..4638cf5e2 100644--- a/os/tests/test_first_use.py+++ b/os/tests/test_first_use.py@@ -13,6 +13,19 @@ loader.exec_module(hn_os)class FirstUse(unittest.TestCase):+ def test_old_cpu_gets_an_explanation_before_network_setup_or_agent_launch(self):+ for cpu, ready in [('flags : sse sse2 ssse3\n', False), ('flags : sse4_2\n', True),+ ('Features : fp asimd\n', True)]:+ with self.subTest(cpu=cpu), patch.object(hn_os.Path, 'read_text', return_value=cpu):+ self.assertEqual(hn_os.opencode_cpu_ready(), ready)+ with patch.object(hn_os, 'opencode_cpu_ready', return_value=False), \+ patch.object(hn_os.sys.stdin, 'isatty', return_value=True), patch('builtins.input') as wait, \+ patch.object(hn_os, 'connected') as connected, patch.object(hn_os.os, 'execv') as execute:+ hn_os.try_harness()+ connected.assert_not_called()+ execute.assert_not_called()+ wait.assert_called_once()+def test_connected_machine_starts_bundled_agent_without_model_or_config_override(self):with tempfile.TemporaryDirectory() as temp, patch.object(hn_os.Path, 'home', return_value=Path(temp)), \patch.object(hn_os, 'connected', return_value=True), patch.object(hn_os, 'wifi') as wifi, \diff --git a/os/tests/test_hardware.py b/os/tests/test_hardware.pynew file mode 100644index 000000000..1366229d9--- /dev/null+++ b/os/tests/test_hardware.py@@ -0,0 +1,161 @@+import importlib.util+import json+from pathlib import Path+import subprocess+import tempfile+import unittest+from unittest.mock import patch+++spec = importlib.util.spec_from_file_location('hardware', Path(__file__).resolve().parents[1] / 'hardware.py')+hardware = importlib.util.module_from_spec(spec)+spec.loader.exec_module(hardware)+++class HardwarePolicy(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.sysfs = self.root / 'sys'++ def device(self, address='0000:03:00.0', device='43a0', driver=None, wireless=False, kind='028000'):+ path = self.sysfs / 'bus/pci/devices' / address+ path.mkdir(parents=True)+ for name, value in [('vendor', '14e4'), ('device', device), ('class', kind)]:+ (path / name).write_text('0x' + value)+ (path / 'driver_override').write_text('(null)\n')+ if driver:+ bound = self.sysfs / 'bus/pci/drivers' / driver+ bound.mkdir(parents=True, exist_ok=True)+ (bound / 'unbind').touch()+ (path / 'driver').symlink_to(bound)+ if wireless:+ interface = self.sysfs / 'class/net' / ('wlan' + str(len(list((self.sysfs / 'class/net').glob('*')))))+ interface.mkdir(parents=True)+ child = path / 'bcma0:1'+ child.mkdir()+ (interface / 'device').symlink_to(child)+ (interface / 'wireless').mkdir()+ return path++ def bundle(self, folder=None):+ folder = folder or self.root / 'bundle'+ folder.mkdir(parents=True)+ module = folder / 'wl.ko'+ module.write_bytes(b'kernel-module-fixture')+ manifest = {'schema': 1, 'driver': 'broadcom-wl', 'architecture': 'x86_64',+ 'kernel': hardware.os.uname().release, 'module': 'wl.ko',+ 'arch_snapshot': '2026/10/01', 'base_packages': {'linux-lts': '6.18.54-1'},+ 'files': {'wl.ko': {'bytes': module.stat().st_size, 'sha256': hardware.digest(module)}}}+ (folder / 'manifest.json').write_text(json.dumps(manifest))+ return folder++ def test_native_fullmac_and_working_b43_are_preserved(self):+ self.device(device='43ba', driver='brcmfmac', wireless=True)+ self.device(address='0000:04:00.0', device='4331', driver='bcma-pci-bridge', wireless=True)+ with patch.object(hardware, 'run') as run:+ for device in hardware.pci_devices(self.sysfs):+ self.assertFalse(hardware.needs_broadcom(device))+ self.assertEqual(hardware.activate(device['address'], self.sysfs)['status'], 'unchanged')+ run.assert_not_called()++ def test_only_selected_radio_ids_request_the_driver(self):+ self.device()+ self.device(address='0000:04:00.0', device='4331', driver='wl', wireless=True)+ self.device(address='0000:05:00.0', device='43bb')+ self.device(address='0000:06:00.0', device='43a0', kind='020000')+ self.assertEqual([d['address'] for d in hardware.pci_devices(self.sysfs) if hardware.needs_broadcom(d)],+ ['0000:03:00.0', '0000:04:00.0'])++ def test_damaged_module_is_rejected_before_unbinding(self):+ device = self.device(driver='bcma-pci-bridge')+ bundle = self.bundle()+ (bundle / 'wl.ko').write_bytes(b'damaged')+ with patch.object(hardware, 'run') as run, self.assertRaisesRegex(ValueError, 'checksum'):+ hardware.activate(device.name, self.sysfs, bundle)+ run.assert_not_called()+ self.assertEqual((device / 'driver_override').read_text(), '(null)\n')+ self.assertEqual((device / 'driver/unbind').read_text(), '')++ def test_failed_load_restores_driver_selection(self):+ device = self.device(driver='bcma-pci-bridge')+ bundle = self.bundle()+ probe = self.sysfs / 'bus/pci/drivers_probe'+ probe.touch()++ def operation(*args, **kwargs):+ if args == ('modprobe', 'cfg80211'):+ # Simulate the preceding sysfs unbind's kernel side effect.+ (device / 'driver').unlink()+ else:+ raise subprocess.CalledProcessError(1, args)++ with patch.object(hardware, 'run', side_effect=operation), self.assertRaises(subprocess.CalledProcessError):+ hardware.activate(device.name, self.sysfs, bundle)+ self.assertEqual((device / 'driver_override').read_text(), '\n')+ self.assertEqual(probe.read_text(), device.name + '\n')++ def test_manifest_cannot_point_outside_bundle(self):+ bundle = self.bundle()+ (bundle / 'wl.ko').unlink()+ outside = self.root / 'external'+ outside.write_bytes(b'kernel-module-fixture')+ (bundle / 'wl.ko').symlink_to(outside)+ with self.assertRaisesRegex(ValueError, 'inside'):+ hardware.bundle_manifest(bundle)++ def test_running_root_and_unmounted_directory_cannot_receive_offline_packages(self):+ for target in [Path('/'), self.root]:+ with self.subTest(target=target), patch.object(hardware, 'run') as run, self.assertRaises(ValueError):+ hardware.configure_install(target, [])+ run.assert_not_called()++ def test_unrelated_install_prunes_only_its_hardware_cache(self):+ target = self.root / 'target'+ (target / 'etc').mkdir(parents=True)+ (target / 'etc/harness-live').touch()+ folder = self.bundle(target / hardware.BUNDLE.relative_to('/'))+ keep = folder.parent / 'keep.txt'+ keep.write_text('another hardware profile')+ with patch.object(hardware.Path, 'is_mount', return_value=True), patch.object(hardware, 'run') as run:+ result = hardware.configure_install(target, [])+ self.assertEqual(result['drivers'], [])+ run.assert_not_called()+ self.assertFalse(folder.exists())+ self.assertTrue(keep.is_file())+ self.assertTrue((target / 'etc/harness-live').exists())++ def test_dependency_mismatch_stops_before_package_transaction(self):+ self.device()+ target = self.root / 'target'+ (target / 'etc').mkdir(parents=True)+ (target / 'etc/harness-live').touch()+ self.bundle(target / hardware.BUNDLE.relative_to('/'))+ (target / 'usr/share/harness-os/lock.json').write_text('{"arch_snapshot":"2026/10/01"}')+ with patch.object(hardware.Path, 'is_mount', return_value=True), \+ patch.object(hardware, 'run', return_value='linux-lts different') as run, \+ self.assertRaisesRegex(ValueError, 'dependencies'):+ hardware.configure_install(target, hardware.pci_devices(self.sysfs))+ self.assertEqual(run.call_count, 1)+ self.assertIn('-Q', run.call_args.args)++ def test_report_does_not_collect_serials_network_addresses_or_ssids(self):+ self.device()+ dmi = self.sysfs / 'class/dmi/id'+ dmi.mkdir(parents=True)+ (dmi / 'product_name').write_text('MacBookAir6,2')+ (dmi / 'product_serial').write_text('PRIVATE-SERIAL')+ proc = self.root / 'proc'+ proc.mkdir()+ (proc / 'cpuinfo').write_text('flags : ssse3 sse4_2 avx\nSerial : PRIVATE-CPU\n')+ report = hardware.report(self.sysfs, proc)+ self.assertTrue(report['opencode_cpu']['available'])+ self.assertEqual(report['computer']['model'], 'MacBookAir6,2')+ self.assertNotIn('PRIVATE', json.dumps(report))+ (proc / 'cpuinfo').write_text('flags : ssse3\n')+ self.assertFalse(hardware.report(self.sysfs, proc)['opencode_cpu']['available'])+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/test_publication.py b/os/tests/test_publication.pyindex 803e30d0e..f2a26555a 100644--- a/os/tests/test_publication.py+++ b/os/tests/test_publication.py@@ -11,6 +11,30 @@ spec.loader.exec_module(publish)class PublicationGuards(unittest.TestCase):+ def test_optional_hardware_requires_matching_native_install_and_rebuild(self):+ manifest = {'source_commit': 'source-one', 'iso': {'sha256': 'image-one'},+ 'hardware': {'broadcom': {'kernel': 'exact-kernel',+ 'packages': {'driver.pkg.tar.zst': {'name': 'driver', 'version': '1'}}}}}+ receipt = dict(status='passed', iso_sha256='image-one', image_source_commit='source-one', test_source_commit='source-one',+ installed_offline_rebuild_seconds=12,+ keyboard={'confirmed_seconds_since_boot': 20},+ post_rebuild_keyboard={'confirmed_seconds_since_boot': 40},+ installation=dict(status='passed', kernel='exact-kernel',+ optional_packages={'driver': '1'}, corrupted_bundle_rejected=True,+ cache_removed=True, base_packages_unchanged=True, native_drivers_preserved=True))+ publish.validate_hardware(manifest, receipt)+ for change in [dict(status='failed'), dict(iso_sha256='other'), dict(image_source_commit='other'), dict(test_source_commit='other'),+ dict(keyboard={}), dict(post_rebuild_keyboard={}), dict(installed_offline_rebuild_seconds=0)]:+ with self.subTest(change=change), self.assertRaises(ValueError):+ publish.validate_hardware(manifest, dict(receipt, **change))+ for change in [dict(status='failed'), dict(kernel='other'), dict(optional_packages={'driver': '2'}),+ dict(corrupted_bundle_rejected=False), dict(cache_removed=False),+ dict(base_packages_unchanged=False), dict(native_drivers_preserved=False)]:+ bad = copy.deepcopy(receipt)+ bad['installation'].update(change)+ with self.subTest(change=change), self.assertRaises(ValueError):+ publish.validate_hardware(manifest, bad)+def test_installation_guide_cannot_name_an_older_release_or_image(self):manifest = {'version': '0.1.0-preview.4', 'iso': {'name': 'harness-0.1.0-preview.4-x86_64.iso'}}guide = 'These instructions are for **0.1.0-preview.4**. Download harness-0.1.0-preview.4-x86_64.iso.'@@ -71,6 +95,13 @@ class PublicationGuards(unittest.TestCase):'On-demand gcc/make installation and local preview passed'])for fw, encrypted in [('bios', False), ('uefi', True)]]publish.validate_receipts(manifest, receipts)+ hardware_manifest = dict(manifest, capabilities=['broadcom-offline'])+ with self.assertRaisesRegex(ValueError, 'optional-driver exclusion'):+ publish.validate_receipts(hardware_manifest, receipts)+ hardware_receipts = copy.deepcopy(receipts)+ for row in hardware_receipts:+ row['checks'].append('Unrelated hardware receives no optional Wi-Fi packages and retains no USB driver cache')+ publish.validate_receipts(hardware_manifest, hardware_receipts)for change in [dict(status='failed'), dict(scope='live session only'), dict(iso_sha256='another-image'),dict(image_source_commit='another-source'), dict(checks=['Live hn ready;']), dict(encrypted=False)]:bad = copy.deepcopy(receipts)diff --git a/os/tests/update_vm.py b/os/tests/update_vm.pyindex d18f14c60..65717a06f 100644--- a/os/tests/update_vm.py+++ b/os/tests/update_vm.py@@ -57,7 +57,7 @@ def main():vm.stop()vm.start(live=False)vm.login_installed(config)- receipt['checks'].append('Published preview 4 installs offline and boots from its encrypted internal disk')+ receipt['checks'].append('Published ' + image['version'] + ' installs offline and boots from its encrypted internal disk')vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S -v')# Reuse the exact bundle after encrypted reboot; /tmp is intentionally# volatile on the installed system.diff --git a/os/tests/vm.py b/os/tests/vm.pyindex baad5bbcf..16442ef93 100644--- a/os/tests/vm.py+++ b/os/tests/vm.py@@ -688,6 +688,13 @@ assert str(i.live_payload()) == '/run/archiso/copytoram/airootfs.sfs'' && test "$HOME" = ' + shlex.quote('/home/' + config['username']) +' && test "$(uname -n)" = ' + shlex.quote(config['hostname']))vm.command('test ! -e /etc/sudoers.d/10-live && test ! -e /etc/harness-live && ! sudo -n true')+ if 'broadcom-offline' in manifest.get('capabilities', []):+ vm.command('test ! -e /usr/share/harness-os/hardware/broadcom && '+ 'for name in gcc dkms broadcom-wl-dkms linux-lts-headers; '+ 'do if pacman -Q "$name"; then exit 1; fi; done')+ vm.command('python3 -c ' + shlex.quote('import json; assert json.load(open('+ '"/var/lib/harness-os/hardware.json")) == {"drivers": [], "devices": []}'))+ result['checks'].append('Unrelated hardware receives no optional Wi-Fi packages and retains no USB driver cache')vm.command('! pgrep -x chromium')vm.command('test "$(npm prefix -g)" = "$HOME/.local"')vm.command('findmnt -n -o FSTYPE / | grep -qx btrfs')diff --git a/os/tools/build-hardware.py b/os/tools/build-hardware.pynew file mode 100644index 000000000..abf7ef932--- /dev/null+++ b/os/tools/build-hardware.py@@ -0,0 +1,134 @@+#!/usr/bin/env python3+"""Prepare a small live Wi-Fi module and signed offline packages in an isolated root."""+import argparse+import base64+import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import subprocess+import tarfile+++def run(*args, capture=False):+ result = subprocess.run(list(map(str, args)), check=True, text=True,+ stdout=subprocess.PIPE if capture else None, timeout=600)+ return result.stdout.strip() if capture else None+++def identity(path):+ with path.open('rb') as handle:+ digest = hashlib.file_digest(handle, 'sha256').hexdigest()+ return {'bytes': path.stat().st_size, 'sha256': digest}+++def descriptions(database):+ result = {}+ for path in (database / 'sync').glob('*.db'):+ with tarfile.open(path) as archive:+ for member in archive:+ if not member.name.endswith('/desc'):+ continue+ blocks = archive.extractfile(member).read().decode().split('\n\n')+ fields = {lines[0]: lines[1:] for block in blocks if (lines := block.strip().splitlines())}+ if '%NAME%' in fields:+ result[fields['%NAME%'][0]] = fields+ return result+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--config', type=Path, required=True)+ parser.add_argument('--work', type=Path, required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ if os.geteuid() != 0 or os.uname().sysname != 'Linux' or os.uname().machine != 'x86_64':+ parser.error('Run in the isolated x86-64 Linux image builder as root.')+ source = Path(__file__).resolve().parents[1]+ lock = json.loads((source / 'lock.json').read_text())+ work, output = args.work.resolve(), args.output.resolve()+ work.mkdir(parents=True, exist_ok=False)+ output.mkdir(parents=True, exist_ok=False)+ cache, database, root = (work / name for name in ['cache', 'database', 'root'])+ cache.mkdir()+ database.mkdir()+ root.mkdir()+ (database / 'local').mkdir()+ config = work / 'pacman.conf'+ config.write_text(args.config.read_text().replace('[options]', '[options]\nCacheDir = ' + str(cache)))+ pacman = ['pacman', '--config', config, '--dbpath', database, '--cachedir', cache]+ run(*pacman, '-Sy', '--noconfirm')+ requested = [line.strip() for line in (source / 'packages.x86_64').read_text().splitlines()+ if line.strip() and not line.startswith('#')]++ def resolve(names):+ output = run(*pacman, '-Sp', '--noconfirm', '--print-format', 'HN_PACKAGE\t%n\t%v', *names, capture=True)+ result = dict(line.split('\t')[1:] for line in output.splitlines() if line.startswith('HN_PACKAGE\t'))+ if not set(names).issubset(result):+ raise ValueError('Package resolution omitted an explicit target.')+ return result++ # Resolve against an empty local database, never the build host's installed+ # packages. This is the exact extra closure beyond the complete image input.+ base = resolve(requested)+ hardware = resolve(['linux-lts', 'linux-lts-headers', 'broadcom-wl-dkms'])+ extra = {name: version for name, version in hardware.items() if name not in base}+ shared = {name: version for name, version in hardware.items() if name in base}+ if any(base[name] != version for name, version in shared.items()):+ raise ValueError('Driver and image dependencies do not use the same snapshot.')+ if not {'linux-lts-headers', 'broadcom-wl-dkms', 'dkms'}.issubset(extra):+ raise ValueError('Driver build dependencies unexpectedly entered the minimal image.')+ run(*pacman, '-Sw', '--noconfirm', *hardware)+ # pacstrap/chroot keep driver compilation and package hooks outside both the+ # host system and the image being assembled. The regular base stays small.+ run('pacstrap', '-C', config, '-c', root, 'base', 'linux-lts', 'linux-lts-headers', 'broadcom-wl-dkms')+ kernels = [p.parent.name for p in (root / 'usr/lib/modules').glob('*/pkgbase')+ if p.read_text().strip() == 'linux-lts']+ if len(kernels) != 1:+ raise ValueError('Expected exactly one LTS kernel in the driver build root.')+ kernel = kernels[0]+ run('arch-chroot', root, 'dkms', 'autoinstall', '-k', kernel)+ location = run('arch-chroot', root, 'modinfo', '-k', kernel, '-n', 'wl', capture=True)+ module = root / location.lstrip('/')+ vermagic = run('arch-chroot', root, 'modinfo', '-k', kernel, '-F', 'vermagic', 'wl', capture=True)+ if vermagic.split()[0] != kernel:+ raise ValueError('Built Wi-Fi module targets a different kernel.')+ shutil.copyfile(module, output / module.name)+ shutil.copyfile(root / 'usr/share/licenses/broadcom-wl-dkms/LICENSE', output / 'LICENSE.broadcom-wl')+ package_dir = output / 'packages'+ package_dir.mkdir()+ metadata = descriptions(database)+ packages = {}+ for name, version in sorted(extra.items()):+ fields = metadata[name]+ if fields['%VERSION%'] != [version]:+ raise ValueError('Package version changed while preparing hardware: ' + name)+ filename = fields['%FILENAME%'][0]+ if not re.fullmatch(r'[a-zA-Z0-9_+.:\-]+\.pkg\.tar\.zst', filename):+ raise ValueError('Invalid repository package filename.')+ package = cache / filename+ if identity(package)['sha256'] != fields['%SHA256SUM%'][0]:+ raise ValueError('Package checksum mismatch: ' + filename)+ target = package_dir / filename+ shutil.copyfile(package, target)+ signature = target.with_name(target.name + '.sig')+ signature.write_bytes(base64.b64decode(fields['%PGPSIG%'][0], validate=True))+ run('pacman-key', '--verify', signature, target)+ packages[filename] = {'name': name, 'version': version}+ manifest = {'schema': 1, 'driver': 'broadcom-wl', 'architecture': 'x86_64',+ 'arch_snapshot': lock['arch_snapshot'], 'kernel': kernel,+ 'module': module.name, 'vermagic': vermagic, 'base_packages': shared,+ 'packages': packages,+ 'files': {str(p.relative_to(output)): identity(p) for p in sorted(output.rglob('*')) if p.is_file()}}+ (output / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')+ print(json.dumps({'driver': manifest['driver'], 'kernel': kernel,+ 'live_module_bytes': manifest['files'][module.name]['bytes'],+ 'offline_package_bytes': sum(p.stat().st_size for p in package_dir.glob('*.pkg.tar.zst'))}, indent=2))+ shutil.rmtree(root)+ shutil.rmtree(cache)+++if __name__ == '__main__':+ main()diff --git a/os/tools/build-package.py b/os/tools/build-package.pyindex b82559c7a..390df63c3 100644--- a/os/tools/build-package.py+++ b/os/tools/build-package.py@@ -45,6 +45,7 @@ def stage(source, runtime, destination, commit):'os/runtime_update.py': 'usr/lib/harness-os/runtime_update.py','os/live_update.py': 'usr/lib/harness-os/live_update.py','os/release_update.py': 'usr/lib/harness-os/release_update.py',+ 'os/hardware.py': 'usr/lib/harness-os/hardware.py','os/tools/hn-os': 'usr/bin/hn-os','os/lock.json': 'usr/share/harness-os/lock.json',}diff --git a/os/tools/hn-os b/os/tools/hn-osindex 794c761d9..6d9340382 100644--- a/os/tools/hn-os+++ b/os/tools/hn-os@@ -32,7 +32,25 @@ def wifi():return subprocess.call(['sudo', 'nmtui-connect'])+def opencode_cpu_ready():+ try:+ lines = Path('/proc/cpuinfo').read_text().splitlines()+ except OSError:+ return True+ for line in lines:+ key, separator, value = line.partition(':')+ if separator and key.strip() == 'flags':+ return 'sse4_2' in value.split()+ return True # The x86 instruction check does not apply to an ARM CPU.++def try_harness():+ if not opencode_cpu_ready():+ print('The bundled OpenCode needs a newer CPU (SSE4.2).')+ print('Open a terminal to work locally or connect to a remote agent.')+ if sys.stdin.isatty():+ input('Press Enter to return to Harness.')+ returnif not connected():if wifi() != 0 or not connected():print('OpenCode needs an internet connection. Connect to Wi-Fi or plug in Ethernet, then try again.')@@ -57,6 +75,8 @@ def main():if command == 'try':try_harness()return+ if command == 'hardware':+ os.execv('/usr/bin/python3', ['python3', '/usr/lib/harness-os/hardware.py', 'report', *args])if command in ['checkpoint', 'update', 'recover']:os.execv('/usr/bin/python3', ['python3', '/usr/lib/harness-os/system.py', command, *args])if command == 'status':@@ -79,7 +99,7 @@ def main():'processes_rss_kib_and_lifetime_cpu': capture('ps', '-eo', 'comm,rss,pcpu', '--sort=-rss')}print(json.dumps(data, indent=2))return- raise SystemExit('Usage: hn-os [status | try | wifi | install | browser [URL] | measure | checkpoint | update [--snapshot YYYY/MM/DD] | recover ROOT_DEVICE [CHECKPOINT]]')+ raise SystemExit('Usage: hn-os [status | hardware | try | wifi | install | browser [URL] | measure | checkpoint | update [--snapshot YYYY/MM/DD] | recover ROOT_DEVICE [CHECKPOINT]]')if __name__ == '__main__':diff --git a/os/tools/inspect_image.py b/os/tools/inspect_image.pyindex 5959359a8..a5d05d919 100644--- a/os/tools/inspect_image.py+++ b/os/tools/inspect_image.py@@ -35,6 +35,7 @@ def inspect(iso):'usr/lib/harness-os/runtime_update.py': source / 'runtime_update.py','usr/lib/harness-os/live_update.py': source / 'live_update.py','usr/lib/harness-os/release_update.py': source / 'release_update.py',+ 'usr/lib/harness-os/hardware.py': source / 'hardware.py','usr/bin/hn-os': source / 'tools/hn-os','usr/share/harness-os/lock.json': source / 'lock.json'})for path, expected in files.items():@@ -69,7 +70,20 @@ def inspect(iso):expected_version = re.escape(version.replace('-preview.', 'pre')) + r'\.r\d+\.g' + manifest['source_commit'][:10] + '-1'assert re.fullmatch(expected_version, package_version), 'OS package version differs from the image source'assert package_version == manifest['package_version'], 'OS package version differs from the manifest'- assert set(manifest['capabilities']) == {'runtime-updates', 'system-updates'}, 'Update capabilities are missing from the manifest'+ assert set(manifest['capabilities']) == {'runtime-updates', 'system-updates', 'broadcom-offline'}, 'Image capabilities differ from the manifest'+ hardware_root = 'usr/share/harness-os/hardware/broadcom/'+ hardware = json.loads(read(hardware_root + 'manifest.json'))+ assert hardware == manifest['hardware']['broadcom'], 'Hardware manifest differs from the payload'+ assert hardware['kernel'] == Path(kernel['path']).parent.name, 'Wi-Fi module targets a different kernel'+ assert hardware['arch_snapshot'] == manifest['arch_snapshot']+ assert all(inventory.get(name) == version for name, version in hardware['base_packages'].items())+ assert not names & {'gcc', 'make', 'dkms', 'broadcom-wl-dkms', 'linux-lts-headers'}, 'Optional Wi-Fi build tools entered the default image'+ for name, expected in hardware['files'].items():+ assert not Path(name).is_absolute() and '..' not in Path(name).parts+ path = hardware_root + name+ data = read(path)+ assert len(data) == expected['bytes'] and hashlib.sha256(data).hexdigest() == expected['sha256'], f'Hardware bundle mismatch: {name}'+ assert owners.get(path) == '0/0', f'Hardware file is not root-owned: {name}'wanted = {row.strip() for row in (source / 'packages.x86_64').read_text().splitlines() if row.strip() and not row.startswith('#')}assert wanted.issubset(names), f'Missing packages: {wanted - names}'config = read('etc/pacman.conf').decode()diff --git a/os/tools/manifest.py b/os/tools/manifest.pyindex 8b2bfe328..0dbc19901 100644--- a/os/tools/manifest.py+++ b/os/tools/manifest.py@@ -25,6 +25,9 @@ if all((root / path).is_file() for path in [capabilities.append('runtime-updates')if (root / 'usr/lib/harness-os/release_update.py').is_file():capabilities.append('system-updates')+hardware = root / 'usr/share/harness-os/hardware/broadcom/manifest.json'+if hardware.is_file():+ capabilities.append('broadcom-offline')manifest = {'version': lock['version'], 'architecture': 'x86_64','source_commit': os.environ.get('HARNESS_OS_SOURCE_SHA') or subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(),@@ -33,5 +36,6 @@ manifest = {'capabilities': capabilities,'package_version': dict(row.split(maxsplit=1) for row in packages.splitlines())['harness-os'],'harness_inputs': json.loads((root / 'usr/share/harness-os/runtime.json').read_text()), 'validation': 'pending',+ 'hardware': {'broadcom': json.loads(hardware.read_text())} if hardware.is_file() else {},}(out / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')diff --git a/os/tools/publish.py b/os/tools/publish.pyindex d0dce6e1f..fe547381d 100644--- a/os/tools/publish.py+++ b/os/tools/publish.py@@ -43,6 +43,27 @@ def validate_install_guide(manifest, guide):raise ValueError('The installation guide must match the release version and ISO filename.')+def validate_hardware(manifest, receipt):+ if (receipt.get('status') != 'passed' or receipt.get('iso_sha256') != manifest['iso']['sha256'] or+ receipt.get('image_source_commit') != manifest['source_commit'] or+ receipt.get('test_source_commit') != manifest['source_commit']):+ raise ValueError('Hardware installation evidence covers a different image or did not pass.')+ installed = receipt.get('installation', {})+ if installed.get('status') != 'passed' or installed.get('kernel') != manifest['hardware']['broadcom']['kernel']:+ raise ValueError('The offline hardware installation did not pass for this kernel.')+ for check in ['corrupted_bundle_rejected', 'cache_removed', 'base_packages_unchanged', 'native_drivers_preserved']:+ if installed.get(check) is not True:+ raise ValueError('Missing hardware installation check: ' + check)+ expected = {value['name']: value['version'] for value in manifest['hardware']['broadcom']['packages'].values()}+ if installed.get('optional_packages') != expected:+ raise ValueError('Installed optional packages differ from the image manifest.')+ for check in ['keyboard', 'post_rebuild_keyboard']:+ if not isinstance(receipt.get(check), dict) or receipt[check].get('confirmed_seconds_since_boot', 0) <= 0:+ raise ValueError('The installed hardware profile has not passed keyboard acceptance.')+ if receipt.get('installed_offline_rebuild_seconds', 0) <= 0:+ raise ValueError('Installed driver dependencies have not passed an offline rebuild.')++def validate_receipts(manifest, receipts):rows = {(r['firmware'], r['encrypted']): r for r in receipts}if set(rows) != {('bios', False), ('uefi', True)} or len(receipts) != 2:@@ -55,6 +76,9 @@ def validate_receipts(manifest, receipts):checks = receipt.get('checks', [])if any(not any(check.startswith(prefix) for check in checks) for prefix in REQUIRED_CHECKS):raise ValueError('A required live, installation or recovery check is absent.')+ if 'broadcom-offline' in manifest.get('capabilities', []) and not any(+ check.startswith('Unrelated hardware receives no optional Wi-Fi packages') for check in checks):+ raise ValueError('The generic installation has not passed optional-driver exclusion.')if not any(check.startswith('Harness unlock screen renders, masks input, accepts a retry') for check in rows[('uefi', True)]['checks']):raise ValueError('The encrypted graphical unlock and retry checks have not passed.')if not any(check.startswith('Claude Code, Codex and pi install on demand; bundled OpenCode') for check in rows[('bios', False)]['checks']):@@ -116,6 +140,13 @@ def main():raise ValueError('The machine workflow did not finish successfully.')if image['head_sha'] != manifest['source_commit'] or not any(j['name'] == 'image' and j['conclusion'] == 'success' for j in jobs['jobs']):raise ValueError('The image does not match a successful build job.')+ hardware = None+ if 'broadcom-offline' in manifest.get('capabilities', []):+ if not any(j['name'] == 'hardware' and j['conclusion'] == 'success' for j in jobs['jobs']):+ raise ValueError('The image build has no successful hardware installation job.')+ gh('run', 'download', args.image, '--repo', args.repo, '--name', 'harness-os-hardware', '--dir', root / 'hardware')+ hardware = read(root / 'hardware/receipt.json')+ validate_hardware(manifest, hardware)examples = {}if list((root / 'machines').rglob('workloads/reports')):examples['workloads'] = {'run': run['html_url'], 'browser_checks': validate_examples(root / 'machines', 'workloads')}@@ -132,6 +163,8 @@ def main():'Timing and memory measurements describe these VMs, not physical laptop power-on time.']validation = {'status': 'passed', 'image_run': image['html_url'], 'machine_run': run['html_url'],'machines': receipts, 'examples': examples, 'limitations': limitations}+ if hardware is not None:+ validation['hardware'] = hardware(folder / 'validation.json').write_text(json.dumps(validation, indent=2) + '\n')manifest['validation'] = {'status': 'passed', 'receipt': 'validation.json', 'machine_run': run['html_url'], 'limitations': limitations}(folder / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')@@ -139,7 +172,7 @@ def main():validate_install_guide(manifest, guide)(folder / 'INSTALL.md').write_text(guide)with zipfile.ZipFile(folder / 'machine-evidence.zip', 'w', compression=zipfile.ZIP_DEFLATED) as archive:- for directory in ['machines', 'dsh-machines']:+ for directory in ['machines', 'dsh-machines', 'hardware']:for path in sorted((root / directory).rglob('*')):include = path.suffix in {'.png', '.json', '.txt', '.jsonl'} or path.name.endswith('-boot-journal.log')if path.is_file() and include and 'Projects' not in path.relative_to(root / directory).parts:@@ -178,6 +211,8 @@ To try it: follow the included `INSTALL.md` for Mac → USB → ThinkPad instrucBIOS/plain and UEFI/encrypted VM boot, clipboard, browser switching, offline installation and package-checkpoint recovery passed. The BIOS VM uses a Nehalem CPU profile without AVX2, starts bundled OpenCode, installs the other agent executables, installs a compiler on demand, builds C, and serves a local Node preview. See `validation.json` and `machine-evidence.zip` for the exact checks and measurements.+{'The USB carries an optional Broadcom Wi-Fi module and signed offline dependencies for selected BCM4331/BCM4360 radios. Fresh installations retain those packages only when needed; other computers receive no additional compiler or driver packages. The exact module and offline installation/rebuild path passed native VM checks with synthetic PCI selection. Physical Mac radio association and sleep/wake remain unverified.' if hardware is not None else ''}+{'Real free OpenCode agents built a Python CLI, a conference website, a keyboard game and a Fastify/SQLite application. Their unit tests and independent browser/API checks passed. The retained projects are in `harness-examples.zip`, separate from the minimal ISO.' if 'workloads' in examples else ''}{reuse_note}