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
Package the Harness session for Fedora ARM (#793)
Deea7bab9125c4e
diff --git a/.github/workflows/os-arm-session.yml b/.github/workflows/os-arm-session.ymlindex c04a8fb4c..c62cc1424 100644--- a/.github/workflows/os-arm-session.yml+++ b/.github/workflows/os-arm-session.yml@@ -13,6 +13,9 @@ on:- 'os/tests/arm_session*'- 'os/tests/test_arm_session.py'- 'os/tests/arm-session.lock.json'+ - 'os/tools/fedora_payload.py'+ - 'os/tools/build-fedora-package.py'+ - 'os/packaging/fedora/**'- '.github/workflows/os-arm-session.yml'permissions:@@ -53,13 +56,20 @@ jobs:make -C os check- name: Build the exact native Harness runtimerun: bash os/tools/build-runtime.sh+ - name: Build the Fedora session RPM with declared native inputs+ run: |+ image=$(python3 -c 'import json; print(json.load(open("os/tests/arm-session.lock.json"))["root_image"])')+ docker run --rm --platform linux/arm64 --memory=4g --cpus=2 --pids-limit=1024 \+ --mount "type=bind,source=$PWD,target=/source" --workdir /source "$image" \+ bash -c 'manager=$(command -v dnf5 || command -v microdnf); "$manager" install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True python3 git rpm-build && python3 os/tools/build-fedora-package.py --runtime os/work/runtime --runtime-source "$(git -c safe.directory=/source rev-parse HEAD)" --output os/work/fedora-package'+ sudo chown -R "$USER:$(id -gn)" os/work/fedora-package- name: Prepare the fresh fixture or exercise the full graphical sessionenv:PREPARE_ONLY: ${{ github.event_name == 'push' || inputs.prepare_only }}run: |args=()if [[ "$PREPARE_ONLY" == true ]]; then args+=(--prepare-only); fi- python3 os/tests/arm_session.py --runtime os/work/runtime \+ python3 os/tests/arm_session.py --package os/work/fedora-package \--output os/test-results/arm-session "${args[@]}"- name: Retain graphical session evidence onlyif: always()@@ -68,6 +78,7 @@ jobs:name: harness-arm-graphical-sessionpath: |os/work/runtime/source.json+ os/work/fedora-package/os/test-results/arm-session/receipt.jsonos/test-results/arm-session/host.logos/test-results/arm-session/packages.tsvdiff --git a/.github/workflows/os-fedora-package.yml b/.github/workflows/os-fedora-package.ymlnew file mode 100644index 000000000..184354e03--- /dev/null+++ b/.github/workflows/os-fedora-package.yml@@ -0,0 +1,103 @@+name: Harness OS private Fedora package++on:+ workflow_dispatch:+ inputs:+ runtime_run_id:+ description: 'Verified private ARM runtime fixture run'+ type: string+ required: true+ runtime_source:+ description: 'Exact producer commit recorded in that runtime artifact'+ type: string+ required: true++permissions:+ contents: read+ actions: read++concurrency:+ group: harness-fedora-package-${{ github.ref }}+ cancel-in-progress: false++jobs:+ package:+ runs-on: ubuntu-24.04-arm+ timeout-minutes: 30+ env:+ RUNTIME_RUN: ${{ inputs.runtime_run_id }}+ RUNTIME_SOURCE: ${{ inputs.runtime_source }}+ steps:+ - uses: actions/checkout@v7+ with:+ fetch-depth: 0+ - name: Check the selected producer and private package inputs+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ [[ "$RUNTIME_RUN" =~ ^[0-9]+$ ]]+ [[ "$RUNTIME_SOURCE" =~ ^[a-f0-9]{40}$ ]]+ gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUNTIME_RUN" > "$RUNNER_TEMP/producer.json"+ python3 - "$RUNNER_TEMP/producer.json" <<'PY'+ import json, os, sys+ run = json.load(open(sys.argv[1]))+ assert run['head_sha'] == os.environ['RUNTIME_SOURCE']+ assert run['path'] == '.github/workflows/os-runtime-updates.yml'+ assert run['status'] == 'completed' and run['conclusion'] == 'success'+ assert run['repository']['full_name'] == os.environ['GITHUB_REPOSITORY']+ PY+ make -C os check+ - uses: actions/download-artifact@v6+ with:+ name: harness-runtime-update-fixture-aarch64+ run-id: ${{ env.RUNTIME_RUN }}+ github-token: ${{ github.token }}+ path: os/work/fedora-runtime-input+ - name: Build two identical packages and a real RPM upgrade+ run: |+ image=$(python3 -c 'import json; print(json.load(open("os/tests/arm-session.lock.json"))["root_image"])')+ mkdir -p os/work/fedora-package-output+ docker pull --platform linux/arm64 "$image"+ docker image inspect "$image" > os/work/fedora-package-output/container-image.json+ docker run --rm --platform linux/arm64 \+ --mount "type=bind,source=$PWD,target=/source,readonly" \+ --mount "type=bind,source=$PWD/os/work/fedora-package-output,target=/output" \+ -e RUNTIME_SOURCE "$image" /bin/bash -euo pipefail -c '+ manager=$(command -v dnf5 || command -v microdnf)+ "$manager" install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True --nodocs python3 git rpm-build tar gzip+ python3 /source/os/tools/build-fedora-package.py --runtime /source/os/work/fedora-runtime-input/runtime --runtime-source "$RUNTIME_SOURCE" --output /output/first --release 1+ python3 /source/os/tools/build-fedora-package.py --runtime /source/os/work/fedora-runtime-input/runtime --runtime-source "$RUNTIME_SOURCE" --output /output/repeat --release 1+ python3 /source/os/tools/build-fedora-package.py --runtime /source/os/work/fedora-runtime-input/runtime --runtime-source "$RUNTIME_SOURCE" --output /output/upgrade --release 2+ '+ - name: Install, upgrade and remove in a fresh Fedora root+ run: |+ image=$(python3 -c 'import json; print(json.load(open("os/tests/arm-session.lock.json"))["root_image"])')+ mkdir -p os/test-results/fedora-package+ docker run --rm --platform linux/arm64 \+ --mount "type=bind,source=$PWD,target=/source,readonly" \+ --mount "type=bind,source=$PWD/os/test-results/fedora-package,target=/evidence" \+ -e RUNTIME_SOURCE -e PACKAGE_SOURCE="$GITHUB_SHA" -e ROOT_IMAGE="$image" \+ "$image" /bin/bash -euo pipefail -c '+ manager=$(command -v dnf5 || command -v microdnf)+ "$manager" install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True --nodocs python3 shadow-utils glibc-common+ python3 /source/os/tests/fedora_package_lifecycle.py \+ --first /source/os/work/fedora-package-output/first \+ --repeat /source/os/work/fedora-package-output/repeat \+ --upgrade /source/os/work/fedora-package-output/upgrade \+ --source "$PACKAGE_SOURCE" --runtime-source "$RUNTIME_SOURCE" \+ --runtime /source/os/work/fedora-runtime-input/runtime \+ --root-image "$ROOT_IMAGE" --output /evidence/lifecycle+ '+ - name: Retain exact package and lifecycle evidence+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: harness-fedora-package+ path: |+ os/work/fedora-package-output/container-image.json+ os/work/fedora-package-output/first/+ os/work/fedora-package-output/upgrade/+ os/test-results/fedora-package/+ if-no-files-found: error+ retention-days: 7+ compression-level: 0diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.mdindex 7c477cce7..9da6f0463 100644--- a/os/DEVELOPMENT.md+++ b/os/DEVELOPMENT.md@@ -546,7 +546,7 @@ repositories remain mutable; this is not a claim of an immutable package snapshoThe tracked fixture accounts for Fedora's browser executable and labwc actionname. It selects shared session files explicitly and excludes the PC installer,-update timer, pacman configuration and x86 driver hooks. Its empty-password account+pacman configuration and x86 driver hooks. Its empty-password accountand root console exist only on the private regular-file disk and local QEMU socket;no host block device, SSH service or public listener is exposed. These test settingsmust never enter a hardware image.@@ -561,7 +561,7 @@ the writable private disk/container are removed. A passing run establishes thisonly, not hardware installation, GPU acceleration, suspend or Fedora recovery.```sh-python3 os/tests/arm_session.py --runtime os/work/runtime \+python3 os/tests/arm_session.py --package os/work/fedora-package \--output os/test-results/arm-session```@@ -570,6 +570,76 @@ The two recorded hosted ARM runs lacked KVM; the second TCG run reached Wi-Fi anaccepted real keyboard input, but failed with a blank OpenCode pane. That failureis retained and is not graphical acceptance.+Fresh fixtures install the native `harness-os-session` RPM instead of copying an+unowned overlay. The RPM is a component of the future Fedora/Asahi Harness image:+it owns the shared session, verified ARM runtime, Fedora guidance and per-user+update units. It contains no installer, base-system updater, kernel, firmware,+boot files, `/etc` configuration, account provisioning or service scriptlets.+Package installation does not start or restart a session. Chromium is optional;+the private fixture still provisions OpenCode separately and records its npm lock.+That agent input is not yet a pinned, package-owned image component.++Build in the pinned Fedora aarch64 container from `arm-session.lock.json`, with+`python3`, `git`, `rpm-build`, `tar` and `gzip` installed from signed Fedora repositories:++```sh+python3 os/tools/build-fedora-package.py --runtime /path/to/runtime \+ --runtime-source FULL_RUNTIME_PRODUCER_SHA --output /path/to/fresh-package+python3 os/tests/arm_session.py --package /path/to/fresh-package \+ --output os/test-results/arm-session --prepare-only+```++The package source and explicitly selected runtime producer remain separate in+the manifest. Both must be clean, with native ARM ELF and runtime hashes checked.+An older immutable runtime can therefore validate packaging without rebuilding+unrelated TUI/CLI sources. Payload timestamps, RPM build time and buildhost are+fixed; compare actual RPM bytes with the same recorded Fedora RPM toolchain.+These private artifacts are unsigned and unpublished; their manifest checksums+are checked before fixture installation. This is not a product update channel.++The **Harness OS private Fedora package** workflow takes a successful private+runtime run and its full producer SHA. It builds release 1 twice and release 2+once, compares repeated RPM bytes, and installs, upgrades and removes the package+in a fresh native Fedora container. First it provisions the RPM's declared signed+Fedora dependencies with their normal presets, retaining package inventories and+the full `/etc` configuration delta. It then creates an existing account, project,+personal configuration and explicit user-unit mask before the Harness transactions.+Those transactions check the original runtime artifact, exact installed versions,+owned files and strict account/project/configuration preservation. This proves+preservation on an existing Fedora base; installing missing platform dependencies+can change Fedora defaults. Only the private local Harness RPMs bypass signature+checks; repository dependencies still require Fedora signatures.++Use its `first/` and `upgrade/` artifacts with the immutable graphical fixture+to check the packaged session across an actual VM reboot and user runtime update:++```sh+python3 os/tests/fedora_package_vm.py \+ --fixture /path/to/harness-arm-session-fixture \+ --fixture-source FULL_IMAGE_PRODUCER_SHA \+ --packages /path/to/harness-fedora-package \+ --package-source FULL_PACKAGE_PRODUCER_SHA \+ --updates /path/to/fast-update-fixture \+ --updates-source FULL_RUNTIME_PRODUCER_SHA \+ --output os/test-results/fedora-package-vm+```++Package and update artifacts must declare the same original runtime identity.+This check preserves a running agent and daemon through both RPM transactions,+then tests the packaged session's keyboard, platform commands and per-user update+activation/rollback after reboot. The private user's update timer is masked across+the reboot and starts only after the verified local feed is ready; no public update is consumed.+The RPM itself contains the normal timer. Neither this check nor the container+lifecycle test establishes Apple hardware installation or Fedora base recovery.++The Fedora profile reports runtime provenance through `hn-os status`. The+`harness install/upgrade/rollback` and `hn-os install/checkpoint/update/recover`+commands reject this profile before invoking PC helpers. `harness updates` and+Super+u retain verified per-user updates, while the system channel is explicitly+unavailable. Fedora/Asahi retains base-system and platform update/recovery+responsibility. The test-only login, networking policy, empty-password account,+root console and autologin remain in `arm_session_root.sh`, outside the RPM.+The workflow defaults to `prepare_only=true`, which uploads an unbooted, compressedprivate test disk and kernel with their hashes and exact source identity. Itsreceipt says **prepared**, never **passed**. Download `harness-arm-session-fixture`diff --git a/os/live_update.py b/os/live_update.pyindex 0d4e3cd29..5a757189e 100644--- a/os/live_update.py+++ b/os/live_update.py@@ -100,8 +100,19 @@ def locked():system_lock.close()+def system_channel():+ # Fedora supplies its own base-system lifecycle. A stale user cache must not+ # offer the PC updater, and an absent PC helper is not a failed runtime check.+ if read(BASE_ID, {}).get('system_profile', 'arch') != 'arch':+ return {'supported': False, 'available': False}+ return read(STATE / 'system.json', {})++def check_system(force=False):- cached = read(STATE / 'system.json', {})+ cached = system_channel()+ if cached.get('supported') is False:+ write(STATE / 'system.json', dict(cached, checked_at=time.time()))+ return cachedif not force and time.time() - cached.get('checked_at', 0) < 86400:return cachedtry:@@ -569,7 +580,7 @@ def update_all():"""One user decision; root still verifies its own official release assets."""if RESTART_REQUIRED.exists():raise ValueError('Restart when ready to finish the update.')- if read(STATE / 'system.json', {}).get('available'):+ if system_channel().get('available'):# Do not reconnect an old session using a new OS package. Its included# runtime takes effect on reboot; finish any independent public release# against that new base afterward, under this same explicit approval.@@ -610,10 +621,10 @@ def screen(window, message='', refresh=False):window.erase()height, width = window.getmaxyx()ready = prepared()- available = (ready is not None and ready != selected()) or read(STATE / 'system.json', {}).get('available')+ available = (ready is not None and ready != selected()) or system_channel().get('available')checked = read(STATE / 'check.json', {})system_state = read(RESTART_REQUIRED, {}).get('status')- errors = checked.get('errors') or read(STATE / 'system.json', {}).get('error') or read(STATE / 'approved.json', {}).get('status') == 'failed'+ errors = checked.get('errors') or system_channel().get('error') or read(STATE / 'approved.json', {}).get('status') == 'failed'if system_state == 'failed':title, choices = 'The update needs recovery.', [('Restore', 'restore-system'), ('Back', None)]elif system_state == 'ready':@@ -714,7 +725,7 @@ def main(argv=None):message = ''# A prepared release can be applied immediately. Otherwise check now# instead of exposing another command or making the user wait for a timer.- refresh = not (prepared() or read(STATE / 'system.json', {}).get('available'))+ refresh = not (prepared() or system_channel().get('available'))while True:action = curses.wrapper(screen, message, refresh)if action is None:@@ -744,7 +755,7 @@ def main(argv=None):print(json.dumps({'runtime': str(selected()), 'versions': versions(selected()),'ready': str(prepared()) if prepared() else None,'restart_required': RESTART_REQUIRED.exists(),- 'system': read(STATE / 'system.json'), 'check': read(STATE / 'check.json')}, indent=2))+ 'system': system_channel(), 'check': read(STATE / 'check.json')}, indent=2))if __name__ == '__main__':diff --git a/os/packaging/fedora/AGENTS.md b/os/packaging/fedora/AGENTS.mdnew file mode 100644index 000000000..5c1d5708d--- /dev/null+++ b/os/packaging/fedora/AGENTS.md@@ -0,0 +1,40 @@+# Harness++The user works in hn agent panes and ordinary terminals. Keep the system small.+Open `hn-browser URL` only when a browser helps. Add tools for the task at hand;+start extra services only when needed. Preserve the user's projects, instructions+and running agents. Read `guide.md` and the shipped TUI reference before advising.++## System operations++- This session runs on Fedora. Read `/etc/os-release` and+ `/usr/share/harness-os/runtime.json` for its system and package provenance.+- `harness updates` and Super+u update the per-user hn/CLI runtime. Verified+ downloads are prepared in the background; activation is explicit and preserves+ agent and terminal processes. The packaged runtime remains the fallback.+- This integration package does not implement Fedora base-system updates,+ installation, snapshots or recovery. Use Fedora/Asahi's maintained system+ tools and documentation. Do not use the PC USB installer or Arch commands.+- Fedora owns its RPM database, kernel, boot chain, firmware, device trees and+ platform services. Do not replace these with components from the PC image.+ Preserve Asahi's audio configuration, including asahi-audio and speakersafetyd.+- Do not replace `/usr/lib/harness` by hand. Package upgrades take effect on a+ later session; they must not kill the running agents or enable a second updater.+- `harness-session` starts the session explicitly from a logged-in local console.+ Installing the package does not create users, change passwords or enable+ autologin. The full image's provisioning is a separate responsibility.++## Network, tools and diagnosis++- Fedora's NetworkManager owns networking. `hn-os wifi` opens the root-owned+ network form through sudo; passwords stay in its masked input.+- PipeWire owns audio. Clipboard tools are `wl-copy` and `wl-paste`.+- Chromium is optional and remains sandboxed. Install ordinary task dependencies+ through Fedora's package manager; keep existing security policy enabled.+- Agents use their normal provider authentication and credential storage. The+ image supplies its default agent separately from this session RPM.+- `hn-os status`, `hn-os measure`, and `systemctl --user status hn-screen+ harness-daemon` report session state. Use `journalctl --user -u hn-screen+ -u harness-daemon` for logs. Reconnect a failed screen before restarting agents.+- A VM result does not establish Apple hardware, suspend, audio, firmware,+ installation or recovery support. Report the actual test environment.diff --git a/os/packaging/fedora/guide.md b/os/packaging/fedora/guide.mdnew file mode 100644index 000000000..5f6c7fc89--- /dev/null+++ b/os/packaging/fedora/guide.md@@ -0,0 +1,38 @@+# Helping someone use Harness++The user works in hn, with an agent or terminal in each pane. A browser is+available when graphical work helps. This Fedora session package is a component+of the future Apple Silicon Harness OS image; it is not an installer or a claim+of hardware support.++Read `/usr/share/harness-os/runtime.json` for the runtime and package source+commits, `/etc/os-release` for Fedora identity, and `AGENTS.md` beside this guide+before changing the system. The complete shipped TUI reference is `guide/tui.md`;+`guide/source.json` identifies its source. `hn list-keys` and `hn list-commands`+describe the actual running version. Preserve the user's existing instructions.++Help the user accomplish their task directly. Create projects under `~/projects`.+Agents use their normal model selection and authentication; do not promise free+model access or change providers without a task reason. The full image supplies+the default agent independently of the session RPM.++Use New Harness for another agent and New terminal for an immediate shell.+Ctrl+b, then Shift+n opens New Harness; Ctrl+b, then Shift+t opens a terminal.+Ctrl+b is a prefix: release it before the next key. Verify customized keys with+`hn list-keys`. Closing a pane and stopping an agent are different actions.++The OS keys are in `labwc/rc.xml`: Super+n opens New Harness, Super+t a terminal,+Super+m the connection flow, Super+w Wi-Fi, Super+b the browser, Super+Enter hn,+and Super+l the lock screen. Super is Command on a Mac keyboard running Linux.+Brightness and audio keys operate supported hardware. These are Linux session+bindings, not macOS shortcuts.++Super+u and `harness updates` activate verified per-user hn/CLI updates while+keeping the agents and terminals alive. Fedora base-system updates and recovery+are outside this package. Do not suggest the PC whole-disk USB flow, Arch package+commands or PC recovery helpers on Fedora. Follow Fedora/Asahi guidance for the+base system; do not describe a private VM as physically tested hardware support.++Use `hn-browser URL` when a browser helps. Chromium is optional and sandboxed.+Use `hn-os wifi` for networking and keep passwords in its masked form. Package+installation does not change accounts, start a session or replace system policy.diff --git a/os/packaging/fedora/harness-os-session.spec b/os/packaging/fedora/harness-os-session.specnew file mode 100644index 000000000..56bfb40ce--- /dev/null+++ b/os/packaging/fedora/harness-os-session.spec@@ -0,0 +1,42 @@+# Prebuilt, verified runtime bytes must retain their recorded identity.+%global debug_package %{nil}+%global __os_install_post %{nil}+%global _build_id_links none++Name: harness-os-session+Version: %{harness_version}+Release: %{harness_release}+Summary: Harness OS terminal and agent session for Fedora+License: MIT+URL: https://github.com/autonomous-ai/openharness+ExclusiveArch: aarch64+Source0: payload.tar.gz+Source1: files.list++Requires: python3, nodejs22, nodejs22-bin, tmux, foot, labwc+Requires: systemd, dbus-tools, NetworkManager, sudo, util-linux, procps-ng, kmod, iproute+Requires: pipewire, pipewire-pulseaudio, wireplumber, swayidle, swaylock, brightnessctl+Requires: wl-clipboard, xdg-utils, xdg-desktop-portal-wlr, dejavu-sans-mono-fonts+Requires: google-noto-color-emoji-fonts, cascadia-mono-nf-fonts++%description+The minimal Harness OS session and verified native ARM runtime. This is a+component for a future Fedora/Asahi Harness image. It does not provision accounts,+start services, install a boot chain, or implement Fedora system recovery.+Chromium and the image's default agent are supplied separately when needed.++%prep+%setup -q -c -T+tar -xzf %{SOURCE0}++%build++%install+mkdir -p %{buildroot}+cp -a usr %{buildroot}/++%files -f %{SOURCE1}+%defattr(-,root,root,-)++# Intentionally no scriptlets, presets or configuration under /etc. Installing,+# upgrading or removing this component must not take over an existing session.diff --git a/os/root/usr/bin/harness b/os/root/usr/bin/harnessindex 0826e56b0..9311faac2 100644--- a/os/root/usr/bin/harness+++ b/os/root/usr/bin/harness@@ -1,4 +1,9 @@#!/bin/sh+case "${1:-}" in+ install|upgrade|rollback)+ /usr/bin/hn-os _require-pc-system || exit "$?"+ ;;+esacif [ "${1:-}" = hardware ]; thenshiftexec /usr/bin/python3 /usr/lib/harness-os/hardware.py report "$@"diff --git a/os/tests/arm_session.py b/os/tests/arm_session.pyindex 0c7e49b1f..451d32d7f 100644--- a/os/tests/arm_session.py+++ b/os/tests/arm_session.py@@ -15,14 +15,16 @@ import selectimport shleximport shutilimport subprocess+import sysimport tempfileimport time-import xml.etree.ElementTree as ETfrom arm_boot import check_arm_image, digest, download, zboot_payloadfrom vm import VMROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / 'os/tools'))+from fedora_payload import package_identity, runtime_identity, stage as stage_payloadUSER = 'runuser -u me -- env XDG_RUNTIME_DIR=/run/user/1000 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus '@@ -33,87 +35,9 @@ def frame_contains(output, expected, absent=()):not any(word.casefold() in visible for word in absent))-def runtime_identity(runtime, commit):- info = json.loads((runtime / 'source.json').read_text())- if (info.get('dirty') is not False or info.get('source_commit') != commit or- info.get('architecture') != 'aarch64' or info.get('target') != 'aarch64-unknown-linux-musl'):- raise ValueError('Use the clean native ARM runtime from this source commit.')- if set(info.get('files', {})) != {'harness-tui', 'cli.js', 'notify.mjs'}:- raise ValueError('Runtime is incomplete.')- for name, identity in info['files'].items():- path = runtime / name- if path.is_symlink() or not path.is_file() or path.stat().st_size != identity['bytes'] or digest(path) != identity['sha256']:- raise ValueError('Runtime checksum mismatch: ' + name)- with (runtime / 'harness-tui').open('rb') as handle:- header = handle.read(20)- if header[:6] != b'\x7fELF\x02\x01' or int.from_bytes(header[18:20], 'little') != 183:- raise ValueError('The terminal must be a little-endian ARM64 ELF executable.')- return info--def stage(runtime, destination, commit):- info = runtime_identity(runtime, commit)- # Deliberately select the shared session only. Do not transplant pacman,- # BIOS/EFI installation, x86 driver hooks, or PC update services into Fedora.- paths = [- 'etc/profile.d/harness-os.sh', 'etc/sudoers.d/20-harness-network',- 'etc/NetworkManager/conf.d/10-dns.conf', 'etc/chromium/policies/managed/harness.json',- 'etc/skel/projects/AGENTS.md', 'usr/bin/hn', 'usr/bin/harness', 'usr/bin/hn-browser',- 'usr/share/harness-os/foot.ini', 'usr/share/harness-os/tmux.conf',- 'usr/share/harness-os/guide.md', 'usr/share/harness-os/AGENTS.md',- *['usr/share/harness-os/labwc/' + name for name in ['autostart', 'shutdown', 'rc.xml']],- *['usr/lib/harness-os/' + name for name in- ['session', 'session-settings.py', 'runtime-path', 'wait-runtime', 'virtio-2d', 'open-wifi']],- *['usr/lib/systemd/user/' + name for name in- ['hn-screen.service', 'harness-daemon.service', 'harness-idle.service']],- ]- for name in paths:- target = destination / name- target.parent.mkdir(parents=True, exist_ok=True)- shutil.copy2(ROOT / 'os/root' / name, target)- for source, name in [- *[('os/' + name + '.py', 'usr/lib/harness-os/' + name + '.py') for name in- ['onboarding', 'network', 'projects', 'hardware']],- ('os/tools/hn-os', 'usr/bin/hn-os'), ('tui/README.md', 'usr/share/harness-os/guide/tui.md'),- ('LICENSE', 'usr/share/licenses/harness-os/LICENSE'),- ]:- target = destination / name- target.parent.mkdir(parents=True, exist_ok=True)- shutil.copy2(ROOT / source, target)- library = destination / 'usr/lib/harness'- library.mkdir(parents=True)- for source, target in [('harness-tui', 'harness-tui'), ('cli.js', 'cli.mjs'), ('notify.mjs', 'notify.mjs')]:- shutil.copy2(runtime / source, library / target)- (library / 'hn').symlink_to('harness-tui')- info['files'] = {p.name: {'bytes': p.stat().st_size, 'sha256': digest(p)}- for p in library.iterdir() if not p.is_symlink()}- (destination / 'usr/share/harness-os/runtime.json').write_text(json.dumps(info, indent=2) + '\n')- (destination / 'usr/lib/systemd/user/harness-os.target').write_text(- '[Unit]\nDescription=Private ARM Harness session\n'- 'Wants=hn-screen.service harness-idle.service\nAfter=graphical-session-pre.target\n')- config = destination / 'usr/share/harness-os/labwc/rc.xml'- tree = ET.parse(config)- keyboard = tree.getroot().find('keyboard')- for binding in list(keyboard.findall('keybind')):- if binding.get('key') in ['W-i', 'W-u']:- keyboard.remove(binding)- for action in tree.findall('.//action'):- if action.get('name') == 'NextWindowImmediate':- action.set('name', 'NextWindow') # Fedora's labwc 0.9.6 action name.- tree.write(config, encoding='unicode')- browser = destination / 'usr/bin/hn-browser'- browser.write_text(browser.read_text().replace('/usr/bin/chromium ', '/usr/bin/chromium-browser '))- tmux = destination / 'usr/share/harness-os/tmux.conf'- tmux.write_text('\n'.join(line for line in tmux.read_text().splitlines() if not line.startswith('bind U ')) + '\n')- for directory in ['usr/bin', 'usr/lib/harness-os']:- for path in (destination / directory).iterdir():- path.chmod(0o755)- for name in ['autostart', 'shutdown']:- (destination / 'usr/share/harness-os/labwc' / name).chmod(0o755)- (library / 'harness-tui').chmod(0o755)- (destination / 'etc/sudoers.d/20-harness-network').chmod(0o440)- return {'runtime': info, 'files': {str(p.relative_to(destination)): digest(p)- for p in sorted(destination.rglob('*')) if p.is_file() and not p.is_symlink()}}+ # Kept as a small portable staging check; fresh VM roots install the RPM.+ return stage_payload(ROOT, runtime, destination, commit, commit)class SessionVM(VM):@@ -435,7 +359,7 @@ def run_fixture(folder, output, source, test_source):def main():parser = argparse.ArgumentParser(description=__doc__)inputs = parser.add_mutually_exclusive_group(required=True)- inputs.add_argument('--runtime', type=Path, help='Build a fresh fixture on native ARM Linux.')+ inputs.add_argument('--package', type=Path, help='Build a fresh fixture from a verified Fedora session RPM on native ARM Linux.')inputs.add_argument('--fixture', type=Path, help='Exercise an exact-source prepared fixture on ARM Linux or macOS.')parser.add_argument('--fixture-source', help='Explicit full source SHA of an older immutable fixture; recorded separately from the test source.')parser.add_argument('--prepare-only', action='store_true', help='Prepare a private fixture without claiming acceptance.')@@ -444,15 +368,15 @@ def main():if os.geteuid() == 0:parser.error('Use an ordinary user.')if args.fixture and args.prepare_only:- parser.error('--prepare-only requires --runtime.')+ parser.error('--prepare-only requires --package.')if args.fixture_source and (not args.fixture or not re.fullmatch(r'[a-f0-9]{40}', args.fixture_source)):parser.error('--fixture-source requires --fixture and its full source SHA.')- if args.runtime and (platform.system(), platform.machine()) != ('Linux', 'aarch64'):+ if args.package and (platform.system(), platform.machine()) != ('Linux', 'aarch64'):parser.error('Build the fixture on a native ARM Linux runner.')if args.fixture and (platform.system(), platform.machine()) not in [('Linux', 'aarch64'), ('Darwin', 'arm64')]:parser.error('Exercise the fixture on ARM Linux or Apple Silicon macOS.')required = ['zstd']- if args.runtime:+ if args.package:required += ['docker', 'rpm', 'rpmkeys', 'gpg', 'bsdtar', 'mkfs.ext4', 'sudo']if not args.prepare_only:required += ['qemu-system-aarch64', 'tesseract']@@ -468,14 +392,14 @@ def main():if args.fixture:run_fixture(args.fixture.resolve(), output, args.fixture_source or source, source)return- runtime = args.runtime.resolve()- runtime_identity(runtime, source)+ package_folder = args.package.resolve()+ package = package_identity(package_folder, source)work = Path(tempfile.mkdtemp(prefix='harness-arm-session-', dir=os.environ.get('RUNNER_TEMP')))container = work.namelock = json.loads(Path(__file__).with_name('arm-boot.lock.json').read_text())graphical = json.loads(Path(__file__).with_name('arm-session.lock.json').read_text())receipt = {'status': 'running', 'source_commit': source, 'scope': 'Private Fedora/Asahi graphical VM only',- 'started_at_unix': time.time(), 'kernel_inputs': lock, 'session_inputs': graphical, 'checks': [],+ 'started_at_unix': time.time(), 'package': package, 'kernel_inputs': lock, 'session_inputs': graphical, 'checks': [],'limitations': ['No Apple hardware, firmware provisioning or installer', 'No Fedora update/recovery integration','No OS/runtime release; signed repository package versions are recorded, not snapshot-pinned']}log = (output / 'host.log').open('w')@@ -509,11 +433,11 @@ def main():run(['rpm', '--dbpath', rpmdb, '--import', key])kernel = work / 'kernel'kernel.mkdir()- for package in packages:- signature = run(['rpmkeys', '--dbpath', rpmdb, '--checksig', '--verbose', package], capture=True)+ for kernel_package in packages:+ signature = run(['rpmkeys', '--dbpath', rpmdb, '--checksig', '--verbose', kernel_package], capture=True)if not re.search(r'signature, key (?:ID|fingerprint):? [0-9a-f]+: OK', signature, re.I) or 'NOKEY' in signature or 'NOT OK' in signature:raise ValueError('Missing verified kernel package signature')- run(['bsdtar', '--no-same-owner', '-xpf', package, '-C', kernel])+ run(['bsdtar', '--no-same-owner', '-xpf', kernel_package, '-C', kernel])modules = kernel / 'lib/modules' / lock['kernel_release']compressed, image = work / 'Image.zst', work / 'Image'compressed.write_bytes(zboot_payload((modules / 'vmlinuz').read_bytes()))@@ -522,7 +446,15 @@ def main():receipt['kernel_sha256'] = digest(image)shutil.move(kernel / 'lib/modules', inputs / 'modules')(inputs / 'kernel-release').write_text(lock['kernel_release'] + '\n')- receipt['payload'] = stage(runtime, inputs / 'overlay', source)+ receipt['payload'] = {key: package[key] for key in ['runtime', 'files', 'symlinks']}+ shutil.copyfile(package_folder / package['package']['name'], inputs / 'session.rpm')+ # These are test-image choices, never contents or scriptlets of the RPM.+ for local, name in [('etc/profile.d/harness-os.sh', 'session-login'),+ ('etc/sudoers.d/20-harness-network', 'network-sudoers'),+ ('etc/NetworkManager/conf.d/10-dns.conf', 'dns.conf'),+ ('etc/chromium/policies/managed/harness.json', 'browser-policy.json'),+ ('etc/skel/projects/AGENTS.md', 'project-AGENTS.md')]:+ shutil.copyfile(ROOT / 'os/root' / local, inputs / name)shutil.copy2(Path(__file__).with_name('arm_session_root.sh'), inputs / 'provision')receipt['provision_sha256'] = digest(inputs / 'provision')print('Build a fresh signed Fedora session without a desktop', flush=True)diff --git a/os/tests/arm_session_root.sh b/os/tests/arm_session_root.shindex b671eb5e8..9c0840f68 100644--- a/os/tests/arm_session_root.sh+++ b/os/tests/arm_session_root.sh@@ -4,20 +4,27 @@set -euo pipefailtest -f /.dockerenvtest "$(uname -m)" = aarch64-test -f /inputs/overlay/usr/share/harness-os/runtime.json+test -f /inputs/session.rpmmanager=$(command -v dnf5 || command -v microdnf)"$manager" install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True --nodocs \systemd systemd-udev systemd-pam systemd-resolved dbus-broker dbus-tools \NetworkManager sudo python3 shadow-utils util-linux procps-ng kmod iproute \- labwc xorg-x11-server-Xwayland foot chromium mesa-dri-drivers \- pipewire pipewire-pulseaudio wireplumber swayidle swaylock brightnessctl \- wl-clipboard xdg-utils xdg-desktop-portal-wlr dejavu-sans-mono-fonts \- google-noto-color-emoji-fonts cascadia-mono-nf-fonts \- nodejs22 nodejs22-bin nodejs22-npm nodejs22-npm-bin tmux git curl jq ripgrep less which unzip+ xorg-x11-server-Xwayland chromium mesa-dri-drivers \+ nodejs22-npm nodejs22-npm-bin git curl jq ripgrep less which unzip+# This unsigned private package was checked against the exact-source manifest by+# the host builder. Repository dependencies still require Fedora signatures.+"$manager" install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True \+ --setopt=localpkg_gpgcheck=False --nodocs /inputs/session.rpm"$manager" clean all-cp -a --no-preserve=ownership /inputs/overlay/. /+install -D -m 644 /inputs/session-login /etc/profile.d/harness-os.sh+install -D -m 440 /inputs/network-sudoers /etc/sudoers.d/20-harness-network+install -D -m 644 /inputs/dns.conf /etc/NetworkManager/conf.d/10-dns.conf+install -D -m 644 /inputs/browser-policy.json /etc/chromium/policies/managed/harness.json+install -D -m 644 /inputs/project-AGENTS.md /etc/skel/projects/AGENTS.mdcp -a --no-preserve=ownership /inputs/modules /usr/lib/depmod -a "$(cat /inputs/kernel-release)"+# Agent provisioning remains separate from the session RPM. Capture its lock+# below; this mutable test input is not an image release or a bundled-agent RPM.npm install --prefix /opt/harness-agent --no-audit --no-fund opencode-ailn -s /opt/harness-agent/node_modules/.bin/opencode /usr/bin/opencodeopencode --versiondiff --git a/os/tests/fedora_package_lifecycle.py b/os/tests/fedora_package_lifecycle.pynew file mode 100644index 000000000..53a01a9fa--- /dev/null+++ b/os/tests/fedora_package_lifecycle.py@@ -0,0 +1,279 @@+#!/usr/bin/env python3+"""Exercise the session RPM only inside a disposable native Fedora container.++First provision signed Fedora dependencies with their normal presets, then verify+packaging and existing-user preservation on that base. This does not verify an+installed ARM OS, graphical session, Apple hardware, system updates or boot recovery.+"""+import argparse+import hashlib+import json+import os+from pathlib import Path+import platform+import re+import shutil+import subprocess+import time+++def digest(path):+ with path.open('rb') as handle:+ return hashlib.file_digest(handle, 'sha256').hexdigest()+++def identity(folder, source, producer, expected_runtime):+ manifest = json.loads((folder / 'package-manifest.json').read_text())+ assert (manifest['schema'], manifest['kind'], manifest['architecture'], manifest['published']) == (+ 1, 'harness-os-fedora-session', 'aarch64', False)+ assert manifest['package_source_commit'] == source+ assert manifest['runtime_source_commit'] == producer+ original = manifest['runtime_source_identity']+ assert original == expected_runtime, 'Package runtime differs from the selected producer artifact'+ assert (original['source_commit'], original['dirty'], original['architecture'], original['target']) == (+ producer, False, 'aarch64', 'aarch64-unknown-linux-musl')+ assert set(original['files']) == {'harness-tui', 'cli.js', 'notify.mjs'}+ expected = dict(original, system_profile='fedora', package_source_commit=source,+ files={('cli.mjs' if name == 'cli.js' else name): entry+ for name, entry in original['files'].items()})+ assert manifest['runtime'] == expected, 'Installed runtime identity lost its producer provenance'+ for name, entry in expected['files'].items():+ assert manifest['files']['usr/lib/harness/' + name] == entry['sha256']+ name = manifest['package']['name']+ assert re.fullmatch(r'harness-os-session-[0-9A-Za-z.~+_-]+\.aarch64\.rpm', name), 'Unsafe package filename'+ package = folder / name+ assert package.is_file() and not package.is_symlink()+ assert package.stat().st_size == manifest['package']['bytes']+ assert digest(package) == manifest['package']['sha256']+ assert manifest['runtime']['system_profile'] == 'fedora'+ for relative in [*manifest['files'], *manifest['symlinks']]:+ path = Path(relative)+ assert not path.is_absolute() and '..' not in path.parts and path.parts[0] == 'usr'+ return package, manifest+++def fingerprint(path):+ if path.is_symlink():+ return {'symlink': os.readlink(path)}+ if path.is_file():+ return {'sha256': digest(path), 'mode': path.stat().st_mode & 0o7777}+ if path.is_dir():+ return {str(child.relative_to(path)): fingerprint(child) for child in sorted(path.iterdir())}+ assert not path.exists(), 'Unexpected filesystem object: ' + str(path)+ return None+++def changed_paths(before, after):+ def flatten(path, value):+ if (value is None or isinstance(value.get('sha256'), str) or+ isinstance(value.get('symlink'), str)):+ return {path: value}+ result = {path: {'directory': True}}+ for name, child in value.items():+ result.update(flatten(str(Path(path) / name), child))+ return result++ old = {name: value for path, state in before.items() for name, value in flatten(path, state).items()}+ new = {name: value for path, state in after.items() for name, value in flatten(path, state).items()}+ return [{'path': path, 'before': old.get(path), 'after': new.get(path)}+ for path in sorted(old.keys() | new.keys()) if old.get(path) != new.get(path)]+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--first', type=Path, required=True)+ parser.add_argument('--repeat', type=Path, required=True)+ parser.add_argument('--upgrade', type=Path, required=True)+ parser.add_argument('--source', required=True)+ parser.add_argument('--runtime-source', required=True)+ parser.add_argument('--runtime', type=Path, required=True, help='Original selected producer artifact')+ parser.add_argument('--root-image', required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ if (not Path('/.dockerenv').is_file() or platform.system() != 'Linux' or+ platform.machine() != 'aarch64' or os.geteuid() != 0):+ parser.error('Use a disposable native aarch64 Fedora Docker container, never the host.')+ for value in (args.source, args.runtime_source):+ assert re.fullmatch(r'[a-f0-9]{40}', value), 'Use exact source identities'+ locked_image = json.loads(Path(__file__).with_name('arm-session.lock.json').read_text())['root_image']+ assert args.root_image == locked_image, 'Use the locked Fedora root image'+ assert re.search(r'^ID=fedora$', Path('/etc/os-release').read_text(), re.M)+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ receipt = {'status': 'running', 'started_at': time.time(), 'test_source_commit': args.source,+ 'runtime_source_commit': args.runtime_source, 'root_image': args.root_image,+ 'scope': 'Native RPM reproducibility, Fedora dependency provisioning, then existing-base install/upgrade/removal',+ 'checks': [], 'limitations': ['Container; no graphical, kernel, hardware, boot or system recovery proof']}+ log = (output / 'commands.log').open('w')++ def run(*command, timeout=120, check=True):+ log.write(json.dumps(list(map(str, command))) + '\n')+ log.flush()+ completed = subprocess.run(list(map(str, command)), text=True, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, timeout=timeout)+ log.write(completed.stdout)+ log.flush()+ if check and completed.returncode:+ raise RuntimeError(f'{command[0]} exited {completed.returncode}; see commands.log')+ return completed++ def write_json(name, value):+ (output / name).write_text(json.dumps(value, indent=2) + '\n')++ def inventory(label):+ result = run('rpm', '-qa', '--qf', '%{NAME}\t%{EPOCHNUM}\t%{VERSION}\t%{RELEASE}\t%{ARCH}\t%{SOURCERPM}\n')+ (output / f'packages-{label}.tsv').write_text(+ 'name\tepoch\tversion\trelease\tarchitecture\tsource_rpm\n' ++ '\n'.join(sorted(result.stdout.splitlines())) + '\n')++ def preservation_snapshot(label, before, preserved):+ after = {str(path): fingerprint(path) for path in preserved}+ write_json(f'preservation-{label}.json', after)+ changes = changed_paths(before, after)+ write_json(f'preservation-{label}-changes.json', changes)+ inventory(label)+ paths = {entry['path'] for entry in changes}+ for entry in changes:+ for state in (entry['before'], entry['after']):+ if state and isinstance(state.get('symlink'), str):+ target = Path(state['symlink'])+ if not target.is_absolute():+ target = Path(entry['path']).parent / target+ paths.add(str(target.resolve()))+ ownership, packages = {}, set()+ for path in sorted(paths):+ result = run('rpm', '-qf', '--qf', '%{NAME}\n', path, check=False)+ ownership[path] = {'returncode': result.returncode, 'output': result.stdout}+ if result.returncode == 0:+ packages.update(result.stdout.splitlines())+ write_json(f'preservation-{label}-ownership.json', ownership)+ provenance = {}+ for package in sorted(packages):+ provenance[package] = {}+ for option in ('--scripts', '--triggers'):+ result = run('rpm', '-q', option, package, check=False)+ provenance[package][option] = {'returncode': result.returncode, 'output': result.stdout}+ write_json(f'preservation-{label}-package-scriptlets.json', provenance)+ return after++ try:+ record = args.runtime / 'source.json'+ assert record.is_file() and not record.is_symlink()+ runtime = json.loads(record.read_text())+ assert set(runtime['files']) == {'harness-tui', 'cli.js', 'notify.mjs'}+ for name, entry in runtime['files'].items():+ path = args.runtime / name+ assert path.is_file() and not path.is_symlink()+ assert path.stat().st_size == entry['bytes'] and digest(path) == entry['sha256']+ first, old = identity(args.first, args.source, args.runtime_source, runtime)+ repeat, repeated = identity(args.repeat, args.source, args.runtime_source, runtime)+ upgrade, new = identity(args.upgrade, args.source, args.runtime_source, runtime)+ assert old['runtime_identity_sha256'] == repeated['runtime_identity_sha256'] == new['runtime_identity_sha256'] == digest(record)+ assert first.read_bytes() == repeat.read_bytes(), 'Same inputs produced different RPM bytes'+ assert old['files'] == repeated['files'] == new['files']+ assert old['symlinks'] == repeated['symlinks'] == new['symlinks']+ assert old['package']['version'] == new['package']['version']+ assert str(old['package']['release']) == '1' and str(new['package']['release']) == '2'+ requirements = {}+ for label, rpm in (('first', first), ('upgrade', upgrade)):+ assert not run('rpm', '-qp', '--scripts', rpm).stdout.strip(), 'Package contains service/account scriptlets'+ assert not run('rpm', '-qp', '--triggers', rpm).stdout.strip(), 'Package contains transaction triggers'+ required = run('rpm', '-qp', '--requires', rpm).stdout+ (output / f'package-requires-{label}.txt').write_text(required)+ requirements[label] = [line for line in required.splitlines() if not line.startswith('rpmlib(')]+ assert requirements['first'] == requirements['upgrade'], 'Upgrade changes platform requirements'+ receipt['packages'] = {'first': old, 'upgrade': new}+ receipt['checks'].append('Independent same-input builds produce identical RPM bytes; upgrade changes only RPM release')++ # Fedora dependencies apply their own normal presets. Retain that full+ # configuration delta separately from the Harness lifecycle baseline.+ manager = shutil.which('dnf5') or shutil.which('microdnf')+ assert manager, 'The locked Fedora image must provide a package manager'+ manager_options = [manager, '-y', '--setopt=install_weak_deps=False',+ '--setopt=gpgcheck=True', '--nodocs']+ assert run('rpm', '-q', 'harness-os-session', check=False).returncode == 1+ dependency_before = {'/etc': fingerprint(Path('/etc'))}+ write_json('preservation-before-dependencies.json', dependency_before)+ inventory('before-dependencies')+ try:+ run(*manager_options, 'install', *requirements['first'], timeout=600)+ finally:+ dependency_after = {'/etc': fingerprint(Path('/etc'))}+ write_json('preservation-after-dependencies.json', dependency_after)+ write_json('preservation-dependency-changes.json', changed_paths(dependency_before, dependency_after))+ inventory('after-dependencies')+ assert run('rpm', '-q', 'harness-os-session', check=False).returncode == 1+ receipt['checks'].append('Signed Fedora requirements provisioned with normal presets; configuration delta retained and Harness absent')++ # This existing user's data must survive every package operation. The+ # package must not create the OS image's default account or login policy.+ assert run('getent', 'passwd', 'me', check=False).returncode != 0+ run('useradd', '--create-home', '--shell', '/bin/bash', 'harness-rpm-probe')+ home = Path('/home/harness-rpm-probe')+ for relative, text in [('projects/proof/main.py', 'print("my existing project")\n'),+ ('.config/opencode/AGENTS.md', 'Keep these personal instructions.\n'),+ ('.bash_profile', '# Existing login configuration\n')]:+ target = home / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(text)+ mask = home / '.config/systemd/user/pipewire.service'+ mask.parent.mkdir(parents=True, exist_ok=True)+ mask.symlink_to('/dev/null') # Preserve this user's explicit service choice.+ run('chown', '-h', '-R', 'harness-rpm-probe:harness-rpm-probe', home)+ preserved = [home, Path('/etc/profile.d/harness-os.sh'), Path('/etc/NetworkManager/conf.d/10-dns.conf'),+ Path('/etc/systemd/system/[email protected]'), Path('/etc/systemd/system/default.target'),+ Path('/etc/systemd/user/default.target.wants'), Path('/etc/hostname'), Path('/etc/hosts'),+ Path('/etc/sudoers.d/99-harness-update-test')]+ before = {str(path): fingerprint(path) for path in preserved}+ write_json('preservation-before.json', before)+ inventory('before')+ account = run('getent', 'passwd', 'harness-rpm-probe').stdout+ transaction = [*manager_options, '--setopt=localpkg_gpgcheck=False', 'install']+ for label, rpm, metadata in [('install', first, old), ('upgrade', upgrade, new)]:+ run(*transaction, rpm, timeout=600)+ assert run('rpm', '-q', '--qf', '%{NAME}\t%{VERSION}\t%{RELEASE}\t%{ARCH}',+ 'harness-os-session').stdout == '\t'.join([+ 'harness-os-session', metadata['package']['version'],+ str(metadata['package']['release']), 'aarch64'])+ assert not run('rpm', '-V', 'harness-os-session').stdout.strip()+ installed = set(run('rpm', '-ql', 'harness-os-session').stdout.splitlines())+ expected = {'/' + path for path in [*metadata['files'], *metadata['symlinks']]}+ assert expected <= installed, 'RPM does not own every declared payload file'+ for path in installed:+ assert path.startswith('/usr/'), 'Package owns host configuration or boot data: ' + path+ if not Path(path).is_dir():+ assert path in expected, 'Undeclared file in package: ' + path+ for relative, sha256 in metadata['files'].items():+ assert digest(Path('/') / relative) == sha256, 'Installed bytes differ: ' + relative+ for relative, target in metadata['symlinks'].items():+ assert os.readlink(Path('/') / relative) == target+ owners = run('rpm', '-q', '--qf', '[%{FILEUSERNAME}\t%{FILEGROUPNAME}\n]', 'harness-os-session').stdout+ assert all(line == 'root\troot' for line in owners.splitlines())+ after = preservation_snapshot('after-' + label, before, preserved)+ assert after == before, 'Existing user/login/network policy changed'+ assert run('getent', 'passwd', 'harness-rpm-probe').stdout == account+ assert run('getent', 'passwd', 'me', check=False).returncode != 0, 'Package created a default OS account'+ receipt['checks'].append(f'Native {label}: declared payload owned/verified, existing user and host configuration unchanged')+ # A plain RPM erase is intentional: dependency autoremoval is a separate+ # DNF policy and must not disguise removal of this package's own files.+ run('rpm', '-e', 'harness-os-session')+ assert run('rpm', '-q', 'harness-os-session', check=False).returncode != 0+ for relative in [*new['files'], *new['symlinks']]:+ path = Path('/') / relative+ assert not path.exists() and not path.is_symlink(), 'RPM left an owned file: ' + relative+ after = preservation_snapshot('after-removal', before, preserved)+ assert after == before+ assert run('getent', 'passwd', 'harness-rpm-probe').stdout == account+ receipt['checks'].append('Removal cleans all package-owned files and preserves the existing account, project and configuration')+ receipt['status'] = 'passed'+ except BaseException as error:+ receipt.update(status='failed', error=str(error))+ raise+ finally:+ receipt['finished_at'] = time.time()+ log.close()+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')+++if __name__ == '__main__':+ main()diff --git a/os/tests/fedora_package_vm.py b/os/tests/fedora_package_vm.pynew file mode 100644index 000000000..0dc0840ac--- /dev/null+++ b/os/tests/fedora_package_vm.py@@ -0,0 +1,182 @@+#!/usr/bin/env python3+"""Check the packaged Fedora session on the private 16 KiB ARM VM.++An immutable disposable boot fixture supplies its kernel, firmware and test+login. This checks the session RPM and user runtime, not an Apple installer.+"""+import argparse+from functools import partial+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer+import json+from pathlib import Path+import shlex+import shutil+import subprocess+import tempfile+import threading+import time++from arm_boot import digest+from arm_session import ROOT, SessionVM, failure_evidence, fixture_identity+from arm_update_vm import UserSession, update_identity+from fast_update_vm import exercise+from fedora_package_lifecycle import identity+from session_vm import put+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--fixture', type=Path, required=True)+ parser.add_argument('--fixture-source', required=True)+ parser.add_argument('--packages', type=Path, required=True, help='Verified first/ and upgrade/ package folders')+ parser.add_argument('--package-source', required=True)+ parser.add_argument('--updates', type=Path, required=True)+ parser.add_argument('--updates-source', required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ source = subprocess.check_output(['git', '-C', str(ROOT), 'rev-parse', 'HEAD'], text=True).strip()+ if subprocess.check_output(['git', '-C', str(ROOT), 'status', '--porcelain'], text=True).strip():+ parser.error('Commit the exact test source before native acceptance.')+ fixture, updates = args.fixture.resolve(), args.updates.resolve()+ image = fixture_identity(fixture, args.fixture_source)+ update = update_identity(updates, args.updates_source)+ first, initial = identity(args.packages / 'first', args.package_source, args.updates_source, update['runtime'])+ upgrade, final = identity(args.packages / 'upgrade', args.package_source, args.updates_source, update['runtime'])+ assert initial['package']['version'] == final['package']['version']+ assert str(initial['package']['release']) == '1' and str(final['package']['release']) == '2'+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ result = {'status': 'running', 'started_at': time.time(), 'test_source_commit': source,+ 'image_source_commit': args.fixture_source, 'image_manifest_sha256': digest(fixture / 'manifest.json'),+ 'packages': {'first': initial, 'upgrade': final}, 'update_fixture': update,+ 'scope': 'RPM install/upgrade, native 16 KiB session and per-user runtime updates',+ 'checks': [], 'limitations': ['Private VM test login; never publish this disk',+ 'No Apple firmware, hardware installer, Fedora base update or boot recovery proof',+ 'Saved terminals return after cold boot; automatic agent/conversation restoration is not tested']}+ machine = server = None+ with tempfile.TemporaryDirectory(prefix='harness-fedora-package-') as temporary:+ work = Path(temporary)+ try:+ disk = work / 'guest.raw'+ subprocess.run(['zstd', '-d', '--sparse', str(fixture / 'guest.raw.zst'), '-o', str(disk)],+ check=True, timeout=180)+ assert disk.stat().st_size == image['raw_disk']['bytes'] and digest(disk) == image['raw_disk']['sha256']+ served = work / 'served'+ served.mkdir()+ shutil.copytree(updates, served / 'fast')+ for package in (first, upgrade):+ shutil.copy2(package, served / package.name)+ server = ThreadingHTTPServer(('127.0.0.1', 0), partial(SimpleHTTPRequestHandler, directory=str(served)))+ threading.Thread(target=server.serve_forever, daemon=True).start()+ endpoint = f'http://10.0.2.2:{server.server_port}'+ machine = SessionVM(output / 'package-install', disk, fixture / 'Image')+ machine.start()+ machine.wait_user('test -f ~/.local/state/harness-os/onboarded && pgrep -u 1000 -x opencode >/dev/null', 150)+ machine.user('mkdir -p ~/projects/package-preservation; printf %s keep-my-project '+ '> ~/projects/package-preservation/proof.txt')+ process_probe = '''from pathlib import Path+import json, subprocess+def identity(pid):+ root=Path('/proc')/str(pid)+ return {'pid':pid, 'start_ticks':(root/'stat').read_text().rsplit(')',1)[1].split()[19]}+pids={'agent':int(subprocess.check_output(['pgrep','-o','-u','1000','-x','opencode'],text=True)),+ 'daemon':int(subprocess.check_output(['systemctl','--user','show','harness-daemon','-p','MainPID','--value'],text=True))}+print(json.dumps({key:identity(value) for key,value in pids.items()},sort_keys=True))+'''+ put(machine, '/tmp/harness-package-processes.py', process_probe)+ before, _ = machine.user('python3 /tmp/harness-package-processes.py')+ # The serial transport surrounds command output with markers; save+ # the actual JSON line instead of comparing transport prompt bytes.+ process_line = next(line.strip() for line in before.splitlines() if line.strip().startswith('{'))+ for name, package, metadata in [('install', first, initial), ('upgrade', upgrade, final)]:+ destination = '/tmp/' + package.name+ machine.command('curl -fS --max-time 120 ' + shlex.quote(endpoint + '/' + package.name) ++ ' -o ' + shlex.quote(destination), timeout=130)+ machine.command('printf %s ' + shlex.quote(metadata['package']['sha256'] + ' ' + destination + '\n') ++ ' | sha256sum -c -')+ text, _ = machine.command('manager=$(command -v dnf5 || command -v microdnf); '+ '"$manager" -y --setopt=install_weak_deps=False --setopt=gpgcheck=True '+ '--setopt=localpkg_gpgcheck=False --nodocs install ' + shlex.quote(destination),+ timeout=600)+ (output / (name + '.log')).write_text(text)+ expected = '\t'.join(['harness-os-session', metadata['package']['version'],+ str(metadata['package']['release']), 'aarch64'])+ machine.command('test "$(rpm -q --qf ' + shlex.quote('%{NAME}\t%{VERSION}\t%{RELEASE}\t%{ARCH}') ++ ' harness-os-session)" = ' + shlex.quote(expected))+ machine.command('rpm -V harness-os-session')+ after, _ = machine.user('python3 /tmp/harness-package-processes.py')+ assert process_line in [line.strip() for line in after.splitlines()], 'RPM restarted running work'+ machine.user('test "$(cat ~/projects/package-preservation/proof.txt)" = keep-my-project')+ result['checks'].append('Native RPM install and upgrade preserve the running agent/daemon process identities and project')+ # Keep public releases out of the private fixture. The package bytes+ # and its normal timer remain intact; the shared updater acceptance+ # below starts that timer with its verified local feed.+ machine.user('systemctl --user mask harness-update.timer; '+ 'systemctl --user stop harness-update.timer harness-update.service')+ result['first_shutdown'] = machine.poweroff()+ machine.close()+ machine = SessionVM(output / 'packaged-session', disk, fixture / 'Image')+ machine.start()+ machine.wait_user('systemctl --user is-active --quiet hn-screen harness-daemon', 150)+ machine.user('test "$(cat ~/projects/package-preservation/proof.txt)" = keep-my-project')+ machine.frame('01-packaged-workspace', 'me@harness', 60)+ machine.keyboard('packaged-fedora')+ # Saved terminal panes return after cold boot. The existing fixture+ # does not promise automatic agent/conversation restoration. Start+ # the agent through actual keyboard input and require its UI.+ machine.type_probe('cd /home/me/projects/package-preservation')+ machine.keys('ret')+ machine.type_probe('pwd')+ machine.keys('ret')+ machine.wait_user('hn capture-pane -p | grep -Fx /home/me/projects/package-preservation', 30)+ machine.type_probe('opencode')+ machine.keys('ret')+ machine.wait_user('pgrep -u 1000 -x opencode >/dev/null', 60)+ machine.frame('02-packaged-agent', ['OpenCode', 'Ask anything'], 90)+ machine.command('rpm -V harness-os-session')+ runtime = json.loads(machine.read_file('/usr/share/harness-os/runtime.json'))+ assert runtime == final['runtime'], 'Boot did not use the RPM runtime identity'+ status, exit_status = machine.user('hn-os status', check=False)+ (output / 'system-status.txt').write_text(status)+ assert exit_status == 0 and 'fedora' in status.casefold() and 'Traceback' not in status+ for command in ['hn-os install', 'hn-os update', 'hn-os checkpoint', 'hn-os recover',+ 'harness install', 'harness upgrade', 'harness rollback']:+ text, exit_status = machine.user(command, check=False)+ assert exit_status != 0 and 'fedora' in text.casefold() and 'Traceback' not in text, \+ 'Unavailable platform action did not fail clearly: ' + command+ (output / (command.replace(' ', '-') + '.txt')).write_text(text)+ result['checks'].append('After a real reboot the packaged session renders, accepts QMP virtual keyboard input, explicitly starts OpenCode and reports Fedora without invoking absent PC helpers')+ # Only the test may grant unrestricted sudo for fault injection.+ # The RPM lifecycle separately requires all package files under /usr.+ put(machine, '/etc/sudoers.d/99-harness-update-test', 'me ALL=(ALL) NOPASSWD: ALL\n')+ machine.command('chmod 440 /etc/sudoers.d/99-harness-update-test; '+ 'visudo -cf /etc/sudoers.d/99-harness-update-test')+ machine.user('systemctl --user stop harness-update.timer harness-update.service; '+ 'systemctl --user unmask harness-update.timer; systemctl --user daemon-reload')+ result['fast_updates'] = exercise(UserSession(machine), updates, endpoint)+ machine.keyboard('after-fedora-updates')+ result['checks'].append('The packaged user updater activates and rolls back real ARM binaries, preserving work and keyboard input')+ result['accelerator'] = machine.accelerator+ result['shutdown'] = machine.poweroff()+ result['status'] = 'passed'+ except BaseException as error:+ result.update(status='failed', error=str(error))+ failure_evidence(machine)+ raise+ finally:+ try:+ if machine:+ machine.close()+ if server:+ server.shutdown()+ server.server_close()+ except (OSError, RuntimeError) as error:+ result.update(status='failed', cleanup_error=str(error))+ raise+ finally:+ result['finished_at'] = time.time()+ (output / 'receipt.json').write_text(json.dumps(result, indent=2) + '\n')+++if __name__ == '__main__':+ main()diff --git a/os/tests/test_arm_session.py b/os/tests/test_arm_session.pyindex 0c9263d85..856ececbf 100644--- a/os/tests/test_arm_session.py+++ b/os/tests/test_arm_session.py@@ -19,9 +19,11 @@ class ARMFixture(unittest.TestCase):self.root = Path(self.temp.name)self.runtime = self.root / 'runtime'self.runtime.mkdir()- elf = bytearray(32)- elf[:6] = b'\x7fELF\x02\x01'+ elf = bytearray(64)+ elf[:7] = b'\x7fELF\x02\x01\x01'+ elf[16:18] = (2).to_bytes(2, 'little')elf[18:20] = (183).to_bytes(2, 'little')+ elf[20:24] = (1).to_bytes(4, 'little')for name, data in [('harness-tui', elf), ('cli.js', b'fixture'), ('notify.mjs', b'fixture')]:(self.runtime / name).write_bytes(data)self.info = {'source_commit': 'a' * 40, 'dirty': False, 'architecture': 'aarch64',@@ -55,13 +57,16 @@ class ARMFixture(unittest.TestCase):with self.assertRaisesRegex(ValueError, 'ARM64 ELF'):runtime_identity(self.runtime, 'a' * 40)- def test_session_overlay_contains_no_pc_installer_or_update_services(self):+ def test_session_payload_contains_user_updates_but_no_pc_installer_or_system_updates(self):destination = self.root / 'overlay'receipt = stage(self.runtime, destination, 'a' * 40)files = receipt['files']for path in ['usr/lib/harness-os/install.py', 'usr/lib/harness-os/runtime_update.py',- 'usr/lib/systemd/user/harness-update.timer', 'etc/mkinitcpio.conf.d/20-harness-apple-keyboard.conf']:+ 'usr/lib/harness-os/release_update.py', 'etc/mkinitcpio.conf.d/20-harness-apple-keyboard.conf']:self.assertNotIn(path, files)+ self.assertIn('usr/lib/systemd/user/harness-update.timer', files)+ self.assertIn('usr/lib/harness-os/live_update.py', files)+ self.assertEqual(receipt['runtime']['system_profile'], 'fedora')self.assertEqual((destination / 'usr/lib/harness/hn').readlink(), Path('harness-tui'))self.assertEqual(receipt['runtime']['architecture'], 'aarch64')self.assertIn('chromium-browser', (destination / 'usr/bin/hn-browser').read_text())diff --git a/os/tests/test_fedora_package.py b/os/tests/test_fedora_package.pynew file mode 100644index 000000000..db70d1ef1--- /dev/null+++ b/os/tests/test_fedora_package.py@@ -0,0 +1,181 @@+"""Portable contract checks; real RPM lifecycle belongs to native Fedora."""+import importlib.machinery+import importlib.util+import json+from pathlib import Path+import struct+import sys+import tarfile+import tempfile+import unittest+from unittest.mock import patch++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / 'os/tools'))+import fedora_payload as payload+++def module(name, path):+ spec = importlib.util.spec_from_loader(name, importlib.machinery.SourceFileLoader(name, str(path)))+ result = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(result)+ return result+++builder = module('fedora_builder', ROOT / 'os/tools/build-fedora-package.py')+operations = module('fedora_operations', ROOT / 'os/tools/hn-os')+update = module('fedora_updates', ROOT / 'os/live_update.py')+++class FedoraPayload(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.folder = Path(temporary.name)+ self.runtime = self.folder / 'runtime'+ self.runtime.mkdir()+ elf = struct.pack('<16sHHIQQQIHHHHHH', b'\x7fELF\x02\x01\x01' + b'\0' * 9,+ 2, 183, 1, 0, 64, 0, 0, 64, 56, 0, 0, 0, 0)+ for name, data in [('harness-tui', elf), ('cli.js', b'cli'), ('notify.mjs', b'notify')]:+ (self.runtime / name).write_bytes(data)+ self.info = {'source_commit': 'a' * 40, 'dirty': False, 'architecture': 'aarch64',+ 'target': 'aarch64-unknown-linux-musl',+ 'files': {p.name: {'bytes': p.stat().st_size, 'sha256': payload.digest(p)}+ for p in self.runtime.iterdir()}}+ (self.runtime / 'source.json').write_text(json.dumps(self.info))++ def test_explicit_runtime_producer_remains_separate_from_package_source(self):+ destination = self.folder / 'payload'+ result = payload.stage(ROOT, self.runtime, destination, 'b' * 40, 'a' * 40)+ self.assertEqual(result['runtime']['source_commit'], 'a' * 40)+ self.assertEqual(result['runtime']['package_source_commit'], 'b' * 40)+ self.assertEqual(result['runtime']['system_profile'], 'fedora')+ self.assertEqual(json.loads((self.runtime / 'source.json').read_text()), self.info)+ self.assertEqual((destination / 'usr/lib/harness/cli.mjs').read_bytes(), b'cli')+ self.assertEqual((destination / 'usr/lib/harness/harness-tui').read_bytes(),+ (self.runtime / 'harness-tui').read_bytes())++ def test_inert_profile_contains_no_base_system_or_fixture_takeover(self):+ destination = self.folder / 'payload'+ result = payload.stage(ROOT, self.runtime, destination, 'b' * 40, 'a' * 40)+ self.assertTrue(all(path.startswith('usr/') for path in result['files']))+ for name in ['install.py', 'system.py', 'runtime_update.py', 'release_update.py']:+ self.assertNotIn('usr/lib/harness-os/' + name, result['files'])+ self.assertNotIn('usr/share/harness-os/lock.json', result['files'])+ self.assertIn('usr/lib/harness-os/live_update.py', result['files'])+ self.assertIn('usr/lib/systemd/user/harness-update.timer', result['files'])+ self.assertEqual(result['symlinks']['usr/bin/harness-session'], '../lib/harness-os/session')+ self.assertIn('W-u', (destination / 'usr/share/harness-os/labwc/rc.xml').read_text())+ self.assertNotIn('W-i', (destination / 'usr/share/harness-os/labwc/rc.xml').read_text())+ self.assertNotIn('harness-install', (destination / 'usr/lib/systemd/user/harness-os.target').read_text())+ guide = (destination / 'usr/share/harness-os/AGENTS.md').read_text()+ self.assertIn('Fedora', guide)+ self.assertNotIn('sudo pacman', guide)+ self.assertNotIn('sudo hn-os update', guide)+ inventory = builder.file_list(destination)+ self.assertNotIn('%dir /usr\n', inventory)+ self.assertNotIn('%dir /usr/lib/systemd/user\n', inventory)+ self.assertIn('%dir /usr/lib/harness\n', inventory)+ self.assertIn('%license /usr/share/licenses/harness-os/LICENSE\n', inventory)++ def test_rejects_producer_mismatch_corruption_and_symlink_runtime(self):+ with self.assertRaises(ValueError):+ payload.runtime_identity(self.runtime, 'b' * 40)+ binary = self.runtime / 'harness-tui'+ original = binary.read_bytes()+ binary.write_bytes(original + b'changed')+ with self.assertRaisesRegex(ValueError, 'checksum'):+ payload.runtime_identity(self.runtime, 'a' * 40)+ binary.unlink()+ other = self.folder / 'binary'+ other.write_bytes(original)+ binary.symlink_to(other)+ with self.assertRaisesRegex(ValueError, 'checksum'):+ payload.runtime_identity(self.runtime, 'a' * 40)++ def test_payload_tar_is_reproducible_and_preserves_runtime_bytes_modes(self):+ destination = self.folder / 'payload'+ payload.stage(ROOT, self.runtime, destination, 'b' * 40, 'a' * 40)+ first, second = self.folder / 'a.tar.gz', self.folder / 'b.tar.gz'+ builder.archive_payload(destination, first, 123456)+ builder.archive_payload(destination, second, 123456)+ self.assertEqual(first.read_bytes(), second.read_bytes())+ with tarfile.open(first) as archive:+ binary = archive.getmember('usr/lib/harness/harness-tui')+ self.assertEqual((binary.uid, binary.gid, binary.mode, binary.mtime), (0, 0, 0o755, 123456))+ self.assertEqual(archive.extractfile(binary).read(), (self.runtime / 'harness-tui').read_bytes())+ self.assertTrue(archive.getmember('usr/bin/harness-session').issym())++ def test_fixture_rejects_wrong_package_source_corrupt_bytes_and_symlink(self):+ package = self.folder / 'harness-os-session-0.1.0-1.aarch64.rpm'+ package.write_bytes(b'private package identity fixture, not an installable RPM')+ metadata = {'schema': 1, 'kind': 'harness-os-fedora-session', 'architecture': 'aarch64',+ 'published': False, 'package_source_commit': 'b' * 40, 'runtime_source_commit': 'a' * 40,+ 'runtime': {'source_commit': 'a' * 40, 'system_profile': 'fedora'},+ 'package': {'name': package.name, 'bytes': package.stat().st_size, 'sha256': payload.digest(package)}}+ (self.folder / 'package-manifest.json').write_text(json.dumps(metadata))+ self.assertEqual(payload.package_identity(self.folder, 'b' * 40), metadata)+ with self.assertRaisesRegex(ValueError, 'exact-source'):+ payload.package_identity(self.folder, 'c' * 40)+ original = package.read_bytes()+ package.write_bytes(original + b'corrupt')+ with self.assertRaisesRegex(ValueError, 'checksum'):+ payload.package_identity(self.folder, 'b' * 40)+ package.unlink()+ other = self.folder / 'other.rpm'+ other.write_bytes(original)+ package.symlink_to(other)+ with self.assertRaisesRegex(ValueError, 'checksum'):+ payload.package_identity(self.folder, 'b' * 40)+++class FedoraOperations(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.folder = Path(temporary.name)+ self.identity = self.folder / 'runtime.json'+ self.identity.write_text('{"system_profile":"fedora","source_commit":"original"}\n')+ self.state = self.folder / 'state'+ self.state.mkdir()++ def test_fedora_system_commands_never_execute_pc_helpers(self):+ for command in ['install', 'checkpoint', 'update', 'recover', '_require-pc-system']:+ with self.subTest(command=command), patch.object(operations, 'RUNTIME_ID', self.identity), \+ patch.object(sys, 'argv', ['hn-os', command]), patch.object(operations.os, 'execv') as execute:+ with self.assertRaisesRegex(SystemExit, 'Fedora integration package'):+ operations.main()+ execute.assert_not_called()++ def test_fedora_status_uses_real_runtime_provenance_without_arch_lock(self):+ with patch.object(operations, 'RUNTIME_ID', self.identity), patch.object(sys, 'argv', ['hn-os']), \+ patch.object(operations.subprocess, 'run') as status, patch('builtins.print') as output:+ operations.main()+ self.assertEqual(output.call_args.args[0], self.identity.read_text())+ self.assertIn('hn-screen', status.call_args.args[0])++ def test_legacy_pc_packages_keep_their_system_operations(self):+ self.identity.write_text('{"source_commit":"older-PC-package"}\n')+ with patch.object(operations, 'RUNTIME_ID', self.identity):+ operations.require_pc_system()++ def test_fedora_check_clears_stale_system_error_without_loading_pc_module(self):+ update.write(self.state / 'system.json', {'available': True, 'error': 'old PC check'})+ with patch.object(update, 'BASE_ID', self.identity), patch.object(update, 'STATE', self.state), \+ patch.object(update.importlib.util, 'spec_from_file_location') as discover:+ result = update.check_system(force=True)+ self.assertEqual(result, {'supported': False, 'available': False})+ self.assertNotIn('error', update.read(self.state / 'system.json'))+ discover.assert_not_called()++ def test_stale_system_availability_cannot_execute_privileged_upgrade(self):+ update.write(self.state / 'system.json', {'available': True})+ with patch.object(update, 'BASE_ID', self.identity), patch.object(update, 'STATE', self.state), \+ patch.object(update, 'RESTART_REQUIRED', self.folder / 'absent'), \+ patch.object(update, 'prepared', return_value=None), patch.object(update.subprocess, 'run') as run:+ update.update_all()+ run.assert_not_called()+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/test_first_use.py b/os/tests/test_first_use.pyindex 5ac245398..3aec9c6e6 100644--- a/os/tests/test_first_use.py+++ b/os/tests/test_first_use.py@@ -50,6 +50,7 @@ class FirstUse(unittest.TestCase):def test_install_never_requires_network_setup(self):with patch.object(hn_os.sys, 'argv', ['hn-os', 'install']), \+ patch.object(hn_os, 'system_profile', return_value='arch'), \patch.object(hn_os.os, 'execv', side_effect=SystemExit) as execute, \patch.object(hn_os, 'wifi') as network:with self.assertRaises(SystemExit):diff --git a/os/tools/build-fedora-package.py b/os/tools/build-fedora-package.pynew file mode 100644index 000000000..543cf3f7e--- /dev/null+++ b/os/tools/build-fedora-package.py@@ -0,0 +1,121 @@+#!/usr/bin/env python3+"""Build an unpublished native Fedora session RPM from declared runtime bytes."""+import argparse+import gzip+import json+import os+from pathlib import Path+import platform+import re+import shutil+import subprocess+import tarfile+import tempfile++from fedora_payload import digest, package_identity, runtime_identity, stage+++def command(*args, **kwargs):+ return subprocess.check_output([str(arg) for arg in args], text=True, **kwargs).strip()+++def git(source, *args):+ return command('git', '-c', f'safe.directory={source}', '-C', source, *args)+++def archive_payload(root, output, timestamp):+ with output.open('wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=timestamp) as compressed:+ with tarfile.open(fileobj=compressed, mode='w', dereference=False) as archive:+ for path in sorted(root.rglob('*')):+ info = archive.gettarinfo(str(path), str(path.relative_to(root)))+ info.uid = info.gid = 0+ info.uname = info.gname = 'root'+ info.mtime = timestamp+ if info.isfile():+ with path.open('rb') as handle:+ archive.addfile(info, handle)+ else:+ archive.addfile(info)+++def file_list(root):+ # Own our directories and payload, never Fedora's shared /usr directories.+ lines = []+ for path in sorted(root.rglob('*')):+ name = '/' + str(path.relative_to(root))+ if path.is_dir() and not path.is_symlink():+ if name in ['/usr/lib/harness', '/usr/lib/harness-os', '/usr/share/licenses/harness-os'] or name.startswith('/usr/share/harness-os'):+ lines.append('%dir ' + name)+ else:+ lines.append(('%license ' if name.endswith('/licenses/harness-os/LICENSE') else '') + name)+ return '\n'.join(lines) + '\n'++++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--runtime', type=Path, required=True)+ parser.add_argument('--runtime-source', required=True, help='Full producer SHA of the explicitly selected native runtime.')+ parser.add_argument('--output', type=Path, required=True)+ parser.add_argument('--release', default='1', help='Positive RPM package release, also used for private lifecycle tests.')+ args = parser.parse_args()+ if (platform.system(), platform.machine()) != ('Linux', 'aarch64'):+ parser.error('Build in native Fedora aarch64, without CPU emulation.')+ release_info = platform.freedesktop_os_release()+ if release_info.get('ID') != 'fedora':+ parser.error('Build with Fedora rpm-build in the declared Fedora container.')+ if not re.fullmatch(r'[1-9][0-9]{0,5}', args.release):+ parser.error('--release must be a positive integer.')+ source = Path(__file__).resolve().parents[2]+ if git(source, 'status', '--porcelain', '--untracked-files=normal'):+ parser.error('Commit source changes before packaging.')+ commit = git(source, 'rev-parse', 'HEAD')+ timestamp = int(git(source, 'log', '-1', '--format=%ct'))+ runtime = args.runtime.resolve()+ original_runtime = runtime_identity(runtime, args.runtime_source)+ # The development version identifies this component, not a released ARM OS.+ version = f'0.1.0~dev.{timestamp}.g{commit[:10]}'+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ toolchain = {'rpm': command('rpm', '--version'), 'rpmbuild': command('rpmbuild', '--version'),+ 'python': platform.python_version(), 'os_release': release_info,+ 'buildhost': 'harness-os', 'source_date_epoch': timestamp}+ with tempfile.TemporaryDirectory(prefix='harness-fedora-rpm-') as temporary:+ top = Path(temporary)+ for name in ['SOURCES', 'SPECS', 'BUILD', 'RPMS', 'SRPMS', 'BUILDROOT']:+ (top / name).mkdir()+ payload = top / 'payload'+ identity = stage(source, runtime, payload, commit, args.runtime_source)+ archive_payload(payload, top / 'SOURCES/payload.tar.gz', timestamp)+ (top / 'SOURCES/files.list').write_text(file_list(payload))+ spec = top / 'SPECS/harness-os-session.spec'+ shutil.copyfile(source / 'os/packaging/fedora/harness-os-session.spec', spec)+ subprocess.run(['rpmbuild', '-bb', str(spec), '--define', f'_topdir {top}',+ '--define', f'harness_version {version}', '--define', f'harness_release {args.release}',+ '--define', '_buildhost harness-os', '--define', '_binary_payload w9.gzdio',+ '--define', 'use_source_date_epoch_as_buildtime 1',+ '--define', 'build_mtime_policy clamp_to_source_date_epoch'],+ env=dict(os.environ, SOURCE_DATE_EPOCH=str(timestamp), LC_ALL='C', TZ='UTC'), check=True)+ artifacts = list((top / 'RPMS').rglob('*.rpm'))+ if len(artifacts) != 1:+ raise ValueError('Expected exactly one session RPM.')+ package = output / artifacts[0].name+ shutil.copyfile(artifacts[0], package)+ manifest = {'schema': 1, 'kind': 'harness-os-fedora-session', 'architecture': 'aarch64',+ 'published': False, 'package_source_commit': commit, 'runtime_source_commit': args.runtime_source,+ 'runtime_source_identity': original_runtime, 'runtime_identity_sha256': digest(runtime / 'source.json'),+ **identity, 'toolchain': toolchain,+ 'external_components': {+ 'default_agent': {'owner': 'image', 'included': False, 'fixture_package': 'opencode-ai'},+ 'browser': {'owner': 'image', 'included': False, 'optional': True, 'package': 'chromium'},+ 'platform': {'owner': 'Fedora/Asahi', 'included': False}},+ 'package': {'name': package.name, 'version': version, 'release': args.release,+ 'bytes': package.stat().st_size, 'sha256': digest(package)}}+ record = output / 'package-manifest.json'+ record.write_text(json.dumps(manifest, indent=2) + '\n')+ (output / 'SHA256SUMS').write_text(''.join(f'{digest(path)} {path.name}\n' for path in [package, record]))+ print(json.dumps(manifest['package'], indent=2))+++if __name__ == '__main__':+ main()diff --git a/os/tools/fedora_payload.py b/os/tools/fedora_payload.pynew file mode 100644index 000000000..c64531a2a--- /dev/null+++ b/os/tools/fedora_payload.py@@ -0,0 +1,146 @@+"""The Fedora session payload, shared by RPM packaging and private VM checks.++This is one component of a future Harness OS image. Account setup, platform+packages, boot, networking policy and base-system recovery belong to that image.+"""+import hashlib+import json+from pathlib import Path+import re+import shutil+import xml.etree.ElementTree as ET+++def digest(path):+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def runtime_identity(runtime, commit):+ record = runtime / 'source.json'+ if record.is_symlink() or not record.is_file() or not re.fullmatch(r'[a-f0-9]{40}', commit):+ raise ValueError('Use a regular runtime identity and its full source commit.')+ info = json.loads(record.read_text())+ if (info.get('dirty') is not False or info.get('source_commit') != commit or+ info.get('architecture') != 'aarch64' or info.get('target') != 'aarch64-unknown-linux-musl'):+ raise ValueError('Use the clean native ARM runtime from the declared source commit.')+ if set(info.get('files', {})) != {'harness-tui', 'cli.js', 'notify.mjs'}:+ raise ValueError('Runtime is incomplete.')+ for name, identity in info['files'].items():+ path = runtime / name+ if (not isinstance(identity, dict) or type(identity.get('bytes')) is not int or identity['bytes'] <= 0 or+ not re.fullmatch(r'[a-f0-9]{64}', str(identity.get('sha256'))) or+ path.is_symlink() or not path.is_file() or path.stat().st_size != identity['bytes'] or+ digest(path) != identity['sha256']):+ raise ValueError('Runtime checksum mismatch: ' + name)+ with (runtime / 'harness-tui').open('rb') as handle:+ header = handle.read(64)+ if (len(header) < 64 or header[:7] != b'\x7fELF\x02\x01\x01' or+ int.from_bytes(header[16:18], 'little') not in (2, 3) or+ int.from_bytes(header[18:20], 'little') != 183 or+ int.from_bytes(header[20:24], 'little') != 1):+ raise ValueError('The terminal must be a little-endian ARM64 ELF executable.')+ return info+++def stage(source, runtime, destination, commit, runtime_commit):+ info = runtime_identity(runtime, runtime_commit)+ # An allowlist keeps PC hooks and private fixture provisioning out of RPMs.+ paths = [+ 'usr/bin/hn', 'usr/bin/harness', 'usr/bin/hn-browser',+ 'usr/share/harness-os/foot.ini', 'usr/share/harness-os/tmux.conf',+ *['usr/share/harness-os/labwc/' + name for name in ['autostart', 'shutdown', 'rc.xml']],+ *['usr/lib/harness-os/' + name for name in+ ['session', 'session-settings.py', 'runtime-path', 'wait-runtime', 'virtio-2d', 'open-wifi', 'open-updates']],+ *['usr/lib/systemd/user/' + name for name in+ ['hn-screen.service', 'harness-daemon.service', 'harness-idle.service',+ 'harness-update.service', 'harness-update.timer']],+ ]+ for name in paths:+ target = destination / name+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(source / 'os/root' / name, target)+ for local, name in [+ *[('os/' + name + '.py', 'usr/lib/harness-os/' + name + '.py') for name in+ ['onboarding', 'network', 'projects', 'hardware', 'live_update']],+ ('os/tools/hn-os', 'usr/bin/hn-os'),+ ('tui/README.md', 'usr/share/harness-os/guide/tui.md'),+ ('docs/naming-system.md', 'usr/share/harness-os/guide/naming.md'),+ ('os/packaging/fedora/guide.md', 'usr/share/harness-os/guide.md'),+ ('os/packaging/fedora/AGENTS.md', 'usr/share/harness-os/AGENTS.md'),+ ('LICENSE', 'usr/share/licenses/harness-os/LICENSE'),+ ]:+ target = destination / name+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(source / local, target)+ library = destination / 'usr/lib/harness'+ library.mkdir(parents=True)+ for local, target in [('harness-tui', 'harness-tui'), ('cli.js', 'cli.mjs'), ('notify.mjs', 'notify.mjs')]:+ shutil.copyfile(runtime / local, library / target)+ (library / 'hn').symlink_to('harness-tui')+ (destination / 'usr/bin/harness-session').symlink_to('../lib/harness-os/session')+ info.update(system_profile='fedora', package_source_commit=commit,+ files={p.name: {'bytes': p.stat().st_size, 'sha256': digest(p)}+ for p in library.iterdir() if not p.is_symlink()})+ (destination / 'usr/share/harness-os/runtime.json').write_text(json.dumps(info, indent=2) + '\n')+ (destination / 'usr/share/harness-os/guide/source.json').write_text(json.dumps({+ 'package_source_commit': commit, 'runtime_source_commit': runtime_commit,+ 'tui_reference': 'tui/README.md', 'tui_reference_source_commit': commit,+ }, indent=2) + '\n')+ (destination / 'usr/lib/systemd/user/harness-os.target').write_text(+ '[Unit]\nDescription=The hn screen\n'+ 'Wants=hn-screen.service harness-idle.service harness-update.timer\n'+ 'After=graphical-session-pre.target\n')+ config = destination / 'usr/share/harness-os/labwc/rc.xml'+ tree = ET.parse(config)+ keyboard = tree.getroot().find('keyboard')+ for binding in list(keyboard.findall('keybind')):+ if binding.get('key') == 'W-i':+ keyboard.remove(binding)+ for action in tree.findall('.//action'):+ if action.get('name') == 'NextWindowImmediate':+ action.set('name', 'NextWindow') # Fedora labwc's supported action.+ tree.write(config, encoding='unicode')+ browser = destination / 'usr/bin/hn-browser'+ browser.write_text(browser.read_text().replace('/usr/bin/chromium ', '/usr/bin/chromium-browser '))+ for path in destination.rglob('*'):+ if not path.is_symlink():+ path.chmod(0o755 if path.is_dir() else 0o644)+ for directory in ['usr/bin', 'usr/lib/harness-os']:+ for path in (destination / directory).iterdir():+ if not path.is_symlink():+ path.chmod(0o755)+ for name in ['autostart', 'shutdown']:+ (destination / 'usr/share/harness-os/labwc' / name).chmod(0o755)+ (library / 'harness-tui').chmod(0o755)+ return {'runtime': info, 'files': {str(p.relative_to(destination)): digest(p)+ for p in sorted(destination.rglob('*')) if p.is_file() and not p.is_symlink()},+ 'symlinks': {str(p.relative_to(destination)): str(p.readlink())+ for p in sorted(destination.rglob('*')) if p.is_symlink()}}+++def package_identity(folder, source=None):+ """Check an immutable local package before a private fixture installs it."""+ record = folder / 'package-manifest.json'+ if record.is_symlink() or not record.is_file():+ raise ValueError('Use a regular Fedora package manifest.')+ info = json.loads(record.read_text())+ if (info.get('schema') != 1 or info.get('kind') != 'harness-os-fedora-session' or+ info.get('architecture') != 'aarch64' or info.get('published') is not False or+ not re.fullmatch(r'[a-f0-9]{40}', str(info.get('package_source_commit'))) or+ (source and info['package_source_commit'] != source)):+ raise ValueError('Use an exact-source unpublished Fedora ARM session package.')+ entry = info.get('package', {})+ name = entry.get('name', '')+ if not re.fullmatch(r'harness-os-session-[A-Za-z0-9.~+-]+\.aarch64\.rpm', name):+ raise ValueError('Invalid Fedora package name.')+ artifact = folder / name+ if (type(entry.get('bytes')) is not int or entry['bytes'] <= 0 or+ not re.fullmatch(r'[a-f0-9]{64}', str(entry.get('sha256'))) or+ artifact.is_symlink() or not artifact.is_file() or+ artifact.stat().st_size != entry['bytes'] or digest(artifact) != entry['sha256']):+ raise ValueError('Fedora package checksum mismatch.')+ if (info.get('runtime_source_commit') != info.get('runtime', {}).get('source_commit') or+ not re.fullmatch(r'[a-f0-9]{40}', str(info.get('runtime_source_commit'))) or+ info['runtime'].get('system_profile') != 'fedora'):+ raise ValueError('Missing Fedora runtime provenance.')+ return infodiff --git a/os/tools/hn-os b/os/tools/hn-osindex 4bb5e69b8..e4003c015 100644--- a/os/tools/hn-os+++ b/os/tools/hn-os@@ -7,6 +7,19 @@ import subprocessimport sysimport time+RUNTIME_ID = Path('/usr/share/harness-os/runtime.json')+++def system_profile():+ # Older PC packages predate profiles. Fedora packages always declare theirs.+ return json.loads(RUNTIME_ID.read_text()).get('system_profile', 'arch')+++def require_pc_system():+ if system_profile() != 'arch':+ raise SystemExit('This Fedora integration package does not provide system installation, '+ 'updates or recovery. Use the Fedora/Asahi system tools.')+def capture(*args):result = subprocess.run(args, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)@@ -66,7 +79,11 @@ def try_harness():def main():args = sys.argv[1:]command = args.pop(0) if args else 'status'+ if command == '_require-pc-system':+ require_pc_system()+ returnif command == 'install':+ require_pc_system()os.execv('/usr/bin/python3', ['python3', '/usr/lib/harness-os/install.py', *args])if command == 'browser':os.execv('/usr/bin/hn-browser', ['hn-browser', *args])@@ -82,9 +99,11 @@ def main():if command == 'hardware':os.execv('/usr/bin/python3', ['python3', '/usr/lib/harness-os/hardware.py', 'report', *args])if command in ['checkpoint', 'update', 'recover']:+ require_pc_system()os.execv('/usr/bin/python3', ['python3', '/usr/lib/harness-os/system.py', command, *args])if command == 'status':- print(Path('/usr/share/harness-os/lock.json').read_text())+ identity = RUNTIME_ID if system_profile() != 'arch' else Path('/usr/share/harness-os/lock.json')+ print(identity.read_text())subprocess.run(['systemctl', '--user', '--no-pager', 'status', 'harness-daemon', 'hn-screen'])returnif command == 'measure':@@ -103,7 +122,10 @@ 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 | hardware | try | wifi | install | browser [URL] | measure | checkpoint | update [--snapshot YYYY/MM/DD] | recover ROOT_DEVICE [CHECKPOINT]]')+ commands = 'status | hardware | try | wifi | browser [URL] | measure'+ if system_profile() == 'arch':+ commands += ' | install | checkpoint | update [--snapshot YYYY/MM/DD] | recover ROOT_DEVICE [CHECKPOINT]'+ raise SystemExit('Usage: hn-os [' + commands + ']')if __name__ == '__main__':