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
os: bundle verified OpenCode in the Fedora ARM session package (#912)
Deec3740afafb78
diff --git a/.github/workflows/os-arm-session.yml b/.github/workflows/os-arm-session.ymlindex c62cc1424..f066e3428 100644--- a/.github/workflows/os-arm-session.yml+++ b/.github/workflows/os-arm-session.yml@@ -14,6 +14,7 @@ on:- 'os/tests/test_arm_session.py'- 'os/tests/arm-session.lock.json'- 'os/tools/fedora_payload.py'+ - 'os/tools/opencode_payload.py'- 'os/tools/build-fedora-package.py'- 'os/packaging/fedora/**'- '.github/workflows/os-arm-session.yml'@@ -56,12 +57,14 @@ jobs:make -C os check- name: Build the exact native Harness runtimerun: bash os/tools/build-runtime.sh+ - name: Verify the pinned upstream default agent+ run: python3 os/tools/opencode_payload.py --archives os/work/opencode-archives --output os/work/opencode-payload- name: Build the Fedora session RPM with declared native inputsrun: |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'+ 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)" --agent os/work/opencode-payload --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:diff --git a/.github/workflows/os-fedora-package.yml b/.github/workflows/os-fedora-package.ymlindex 184354e03..11ea3a2f6 100644--- a/.github/workflows/os-fedora-package.yml+++ b/.github/workflows/os-fedora-package.yml@@ -11,6 +11,10 @@ on:description: 'Exact producer commit recorded in that runtime artifact'type: stringrequired: true+ prepare_fixture:+ description: 'Also prepare a fresh private ARM disk for accelerated graphical acceptance'+ type: boolean+ default: falsepermissions:contents: read@@ -53,6 +57,8 @@ jobs:run-id: ${{ env.RUNTIME_RUN }}github-token: ${{ github.token }}path: os/work/fedora-runtime-input+ - name: Verify the pinned upstream default agent+ run: python3 os/tools/opencode_payload.py --archives os/work/opencode-archives --output os/work/opencode-payload- name: Build two identical packages and a real RPM upgraderun: |image=$(python3 -c 'import json; print(json.load(open("os/tests/arm-session.lock.json"))["root_image"])')@@ -65,9 +71,9 @@ jobs:-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+ python3 /source/os/tools/build-fedora-package.py --runtime /source/os/work/fedora-runtime-input/runtime --runtime-source "$RUNTIME_SOURCE" --agent /source/os/work/opencode-payload --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" --agent /source/os/work/opencode-payload --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" --agent /source/os/work/opencode-payload --output /output/upgrade --release 2'- name: Install, upgrade and remove in a fresh Fedora rootrun: |@@ -88,6 +94,12 @@ jobs:--runtime /source/os/work/fedora-runtime-input/runtime \--root-image "$ROOT_IMAGE" --output /evidence/lifecycle'+ - name: Prepare a fresh private graphical fixture from the same package+ if: inputs.prepare_fixture+ run: |+ sudo apt-get update -qq+ sudo apt-get install -y --no-install-recommends qemu-system-arm e2fsprogs rpm libarchive-tools zstd gnupg python3-pil tesseract-ocr+ python3 os/tests/arm_session.py --package os/work/fedora-package-output/first --output os/test-results/arm-session --prepare-only- name: Retain exact package and lifecycle evidenceif: always()uses: actions/upload-artifact@v6@@ -98,6 +110,19 @@ jobs:os/work/fedora-package-output/first/os/work/fedora-package-output/upgrade/os/test-results/fedora-package/+ os/test-results/arm-session/receipt.json+ os/test-results/arm-session/host.log+ os/test-results/arm-session/packages.tsv+ os/test-results/arm-session/agent-lock.jsonif-no-files-found: errorretention-days: 7compression-level: 0+ - name: Retain the private fixture for accelerated acceptance+ if: success() && inputs.prepare_fixture+ uses: actions/upload-artifact@v6+ with:+ name: harness-arm-session-fixture+ path: os/test-results/arm-session/fixture/+ if-no-files-found: error+ retention-days: 3+ compression-level: 0diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.mdindex 99f07d37e..8f3117220 100644--- a/os/DEVELOPMENT.md+++ b/os/DEVELOPMENT.md@@ -608,7 +608,7 @@ VM prototype, not an Apple Silicon installer or a supported hardware image.`tests/arm-session.lock.json` pins the Fedora container and extra graphical kernelmodules. The builder verifies kernel package signatures and hashes, checks theexact clean ARM runtime, installs signed Fedora packages without weak dependencies,-and records their versions and the upstream-default OpenCode lockfile. Fedora+and records their versions and the pinned OpenCode artifact identity. Fedorarepositories remain mutable; this is not a claim of an immutable package snapshot.The tracked fixture accounts for Fedora's browser executable and labwc action@@ -639,19 +639,27 @@ is retained and is not graphical acceptance.Fresh fixtures install the native `harness-os-session` RPM instead of copying anunowned 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+it owns the shared session, verified ARM runtime, OpenCode, Fedora guidance and per-userupdate 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.+Package installation does not start or restart a session. Chromium is optional.+OpenCode's ARM executable and upstream MIT license are pinned by URL, size and+SHA-256 in `packaging/fedora/opencode.lock.json`. The preparer checks upstream+package metadata, ELF architecture and 16 KiB page alignment before staging only+those files. No npm installation scripts run, and no agent download is needed at+first boot. The package keeps upstream model defaults and user credentials.+Update the lock deliberately and repeat the actual 16 KiB first-use/agent test+before using a newer binary; do not resolve a mutable latest version during builds.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/opencode_payload.py --archives /path/to/agent-archives \+ --output /path/to/agent-payloadpython3 os/tools/build-fedora-package.py --runtime /path/to/runtime \- --runtime-source FULL_RUNTIME_PRODUCER_SHA --output /path/to/fresh-package+ --runtime-source FULL_RUNTIME_PRODUCER_SHA --agent /path/to/agent-payload \+ --output /path/to/fresh-packagepython3 os/tests/arm_session.py --package /path/to/fresh-package \--output os/test-results/arm-session --prepare-only```@@ -676,6 +684,10 @@ owned files and strict account/project/configuration preservation. This provespreservation on an existing Fedora base; installing missing platform dependenciescan change Fedora defaults. Only the private local Harness RPMs bypass signaturechecks; repository dependencies still require Fedora signatures.+The optional `prepare_fixture=true` input builds a fresh graphical disk from+the same RPM and frozen runtime after the lifecycle checks. Its separate artifact+is marked prepared, not accepted; run it with HVF/KVM as described below. This+allows OS packaging changes to be checked without rebuilding hn or the CLI.Use its `first/` and `upgrade/` artifacts with the immutable graphical fixtureto check the packaged session across an actual VM reboot and user runtime update:diff --git a/os/packaging/fedora/AGENTS.md b/os/packaging/fedora/AGENTS.mdindex b9ef38576..0a5d73747 100644--- a/os/packaging/fedora/AGENTS.md+++ b/os/packaging/fedora/AGENTS.md@@ -38,8 +38,11 @@ and running agents. Read `guide.md` and the shipped TUI reference before advisin- PipeWire owns audio. Clipboard tools are `wl-copy` and `wl-paste`.- Chromium is optional and remains sandboxed. Install ordinary task dependenciesthrough 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.+- OpenCode is bundled in this RPM with verified upstream bytes and its license.+ `/usr/share/harness-os/opencode.json` records its exact version and checksums.+ It uses upstream model defaults and normal provider authentication; preserve+ the user's credentials and instructions. Update the packaged binary through+ RPM, not by overwriting `/usr/lib/harness-opencode` or running npm as root.- `hn-os status`, `hn-os measure`, and `systemctl --user status hn-screenharness-daemon` report session state. Use `journalctl --user -u hn-screen-u harness-daemon` for logs. Reconnect a failed screen before restarting agents.diff --git a/os/packaging/fedora/guide.md b/os/packaging/fedora/guide.mdindex f14560480..8e42c1da3 100644--- a/os/packaging/fedora/guide.md+++ b/os/packaging/fedora/guide.md@@ -13,8 +13,10 @@ 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.+model access or change providers without a task reason. The session RPM includes+OpenCode and its upstream license. Its pinned binary and package checksums are+recorded in `/usr/share/harness-os/opencode.json`; no agent download is needed to+open the first pane. Conversations with remote models still need a connection.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.@@ -50,8 +52,8 @@ Keep macOS and Apple recovery available; do not use the PC installer on this patInstall the verified private session RPM, then install Fedora's `greetd` packagewith `sudo dnf install greetd`. Fedora supplies its PAM configuration and, on asystem with the targeted SELinux policy, its matching `greetd-selinux` dependency.-Keep those policies enabled and unchanged. Chromium and the default agent remain-separate prerequisites for their respective session features.+Keep those policies enabled and unchanged. OpenCode is included; Chromium is a+separate prerequisite for the optional browser.Choose an existing local account with a usable password and existing permissionto run setup through sudo. First verify its password login and sudo from anotherdiff --git a/os/packaging/fedora/harness-os-session.spec b/os/packaging/fedora/harness-os-session.specindex 7783cac68..ab7786e8b 100644--- a/os/packaging/fedora/harness-os-session.spec+++ b/os/packaging/fedora/harness-os-session.spec@@ -20,10 +20,11 @@ Requires: wl-clipboard, grim, slurp, xdg-utils, xdg-desktop-portal-wlr, dejavu-sRequires: google-noto-color-emoji-fonts, cascadia-mono-nf-fonts%description-The minimal Harness OS session and verified native ARM runtime. This is a+The minimal Harness OS session, verified native ARM runtime and bundled OpenCode.+OpenCode uses its upstream defaults; the package does not select a model. This is acomponent 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.+Chromium is supplied separately when needed.The optional harness-session-setup command uses Fedora's separately installedgreetd package for explicit, reversible next-boot login with an existing account.diff --git a/os/packaging/fedora/opencode.lock.json b/os/packaging/fedora/opencode.lock.jsonnew file mode 100644index 000000000..a2709efb7--- /dev/null+++ b/os/packaging/fedora/opencode.lock.json@@ -0,0 +1,36 @@+{+ "schema": 1,+ "name": "OpenCode",+ "version": "1.18.34",+ "architecture": "aarch64",+ "license": "MIT",+ "upstream": "https://github.com/anomalyco/opencode",+ "archives": {+ "binary": {+ "package": "opencode-linux-arm64",+ "url": "https://registry.npmjs.org/opencode-linux-arm64/-/opencode-linux-arm64-1.18.34.tgz",+ "bytes": 60094599,+ "sha256": "6f212b830b26bf72012f1665559ddb5fd7e928294971d3d1c99a0f9097a3d311"+ },+ "license": {+ "package": "opencode-ai",+ "url": "https://registry.npmjs.org/opencode-ai/-/opencode-ai-1.18.34.tgz",+ "bytes": 3047,+ "sha256": "279923bb5754e810b173a8a7401cf17699fccad3c1159500c10c477887f0b53b"+ }+ },+ "files": {+ "opencode": {+ "archive": "binary",+ "member": "package/bin/opencode",+ "bytes": 185116816,+ "sha256": "415487fcd9b3f06addd6877435783f3d5a236c029066b0dd6597d64980b15351"+ },+ "LICENSE": {+ "archive": "license",+ "member": "package/LICENSE",+ "bytes": 1065,+ "sha256": "625f0f619133f89bbbb2abe37369613dfa1885eba1e50d02170deb62bb42cb6b"+ }+ }+}diff --git a/os/tests/arm_session.py b/os/tests/arm_session.pyindex 451d32d7f..cc1d96285 100644--- a/os/tests/arm_session.py+++ b/os/tests/arm_session.py@@ -93,6 +93,16 @@ class SessionVM(VM):return self.user('for n in $(seq 1 ' + str(seconds * 2) + '); do if ' + command +'; then exit 0; fi; sleep .5; done; exit 1', timeout=seconds + 10)+ def keys(self, *keys):+ # QMP send-key releases held keys on a guest timer. Under HVF load that+ # release can arrive after the compositor starts repeating a character.+ # Queue actual presses and releases together, leaving normal OS repeat+ # settings intact and still exercising the graphical keyboard path.+ events = [{'type': 'key', 'data': {'down': down, 'key': {'type': 'qcode', 'data': key}}}+ for down, chord in [(True, keys), (False, reversed(keys))] for key in chord]+ self.monitor('input-send-event', events=events)+ time.sleep(.12)+def frame(self, name, text, seconds=60, absent=()):from PIL import Image, ImageOpsdeadline = time.monotonic() + seconds@@ -203,6 +213,15 @@ def exercise(vm, result):vm.frame('02-agent', ['OpenCode', 'Ask anything'])output, _ = vm.command('pgrep -u 1000 -x opencode | head -1')pid = re.search(r'(?m)^\d+\r?$', output)[0].strip()+ if result.get('package', {}).get('agent'):+ agent = result['package']['agent']+ vm.command('rpm -V harness-os-session')+ vm.command('test "$(readlink /proc/' + pid + '/exe)" = /usr/lib/harness-opencode/opencode')+ vm.command('test "$(rpm -qf --qf ' + shlex.quote('%{NAME}') ++ ' /usr/lib/harness-opencode/opencode)" = harness-os-session')+ vm.command('printf %s ' + shlex.quote(agent['files']['opencode']['sha256'] ++ ' /usr/lib/harness-opencode/opencode\n') + ' | sha256sum -c -')+ result['checks'].append('The actual first agent executes the RPM-owned, checksum-pinned ARM binary on the 16 KiB kernel')output, _ = vm.command('readlink /proc/' + pid + '/cwd')match = re.search(r'/home/me/projects/[a-zA-Z0-9._-]+', output)if not match:@@ -460,7 +479,7 @@ def main():print('Build a fresh signed Fedora session without a desktop', flush=True)run(['docker', 'run', '--name', container, '--platform', 'linux/arm64', '--memory=4g', '--cpus=2', '--pids-limit=1024','--mount', f'type=bind,source={inputs},target=/inputs,readonly', graphical['root_image'], 'bash', '/inputs/provision'], timeout=1200)- for source_path, name in [('/harness-packages.tsv', 'packages.tsv'), ('/opt/harness-agent/package-lock.json', 'agent-lock.json')]:+ for source_path, name in [('/harness-packages.tsv', 'packages.tsv'), ('/usr/share/harness-os/opencode.json', 'agent-lock.json')]:run(['docker', 'cp', container + ':' + source_path, output / name])archive, root, disk = work / 'root.tar', work / 'root', work / 'guest.raw'root.mkdir()diff --git a/os/tests/arm_session_root.sh b/os/tests/arm_session_root.shindex 9c0840f68..8d398aa15 100644--- a/os/tests/arm_session_root.sh+++ b/os/tests/arm_session_root.sh@@ -23,10 +23,10 @@ install -D -m 644 /inputs/browser-policy.json /etc/chromium/policies/managed/harinstall -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-ai-ln -s /opt/harness-agent/node_modules/.bin/opencode /usr/bin/opencode+# The exact upstream agent and license belong to the session RPM. No untracked+# npm installation or first-boot download is needed.+test "$(rpm -qf --qf '%{NAME}' /usr/bin/opencode /usr/lib/harness-opencode/opencode)" = harness-os-sessionharness-os-session+rpm -V harness-os-sessionopencode --versionuseradd --create-home --uid 1000 --groups wheel --shell /bin/bash me# The empty password belongs only to this test disk and its local QEMU console.diff --git a/os/tests/fedora_package_lifecycle.py b/os/tests/fedora_package_lifecycle.pyindex 53a01a9fa..39f873a1b 100644--- a/os/tests/fedora_package_lifecycle.py+++ b/os/tests/fedora_package_lifecycle.py@@ -14,6 +14,7 @@ import platformimport reimport shutilimport subprocess+import tempfileimport time@@ -247,6 +248,20 @@ def main():assert digest(Path('/') / relative) == sha256, 'Installed bytes differ: ' + relativefor relative, target in metadata['symlinks'].items():assert os.readlink(Path('/') / relative) == target+ agent = metadata['agent']+ assert agent == json.loads(Path('/usr/share/harness-os/opencode.json').read_text())+ # OpenCode initializes XDG directories even for --version. Keep+ # this executable probe separate from the existing-user snapshot,+ # which must measure only the RPM transaction's effects.+ with tempfile.TemporaryDirectory(prefix='harness-agent-version-') as temporary:+ run('chown', 'harness-rpm-probe:harness-rpm-probe', temporary)+ environment = ['HOME=' + temporary, *['XDG_' + kind.upper() + '_HOME=' + temporary + '/' + kind+ for kind in ['config', 'data', 'cache', 'state']]]+ assert run('runuser', '-u', 'harness-rpm-probe', '--', 'env', *environment,+ '/usr/bin/opencode', '--version', timeout=30).stdout.strip() == agent['version']+ assert run('rpm', '-qf', '--qf', '%{NAME}', '/usr/bin/opencode').stdout == 'harness-os-session'+ assert run('rpm', '-qf', '--qf', '%{NAME}', '/usr/lib/harness-opencode/opencode').stdout == 'harness-os-session'+ assert '/usr/share/licenses/harness-opencode/LICENSE' in installedowners = run('rpm', '-q', '--qf', '[%{FILEUSERNAME}\t%{FILEGROUPNAME}\n]', 'harness-os-session').stdoutassert all(line == 'root\troot' for line in owners.splitlines())after = preservation_snapshot('after-' + label, before, preserved)diff --git a/os/tests/fedora_package_vm.py b/os/tests/fedora_package_vm.pyindex 0dc0840ac..1f29d1fc6 100644--- a/os/tests/fedora_package_vm.py+++ b/os/tests/fedora_package_vm.py@@ -70,7 +70,15 @@ def main():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.start(offline=True)+ # Isolate the private update fixture before enabling networking.+ # A slow package transaction otherwise lets the normal timer stage+ # public releases before exercise() supplies its exact test feed.+ machine.wait_user('systemctl --user show-environment >/dev/null', 60)+ machine.user('systemctl --user mask --now harness-update.timer harness-update.service')+ machine.user('test ! -e ~/.local/state/harness-os/updates/ready.json && '+ 'test ! -e ~/.local/state/harness-os/updates/current')+ machine.monitor('set_link', name='hnnet', up=True)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')@@ -94,10 +102,17 @@ print(json.dumps({key:identity(value) for key,value in pids.items()},sort_keys=T' -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 '+ # The prepared image already has the signed Fedora dependencies;+ # the container lifecycle check covers repository provisioning.+ # This local transaction still checks dependencies, without an+ # unrelated mirror refresh delaying the live-process assertions.+ text, _ = machine.command('if command -v dnf5 >/dev/null; then '+ 'manager=dnf5; repo_option="--disable-repo=*"; else '+ 'manager=microdnf; repo_option="--disablerepo=*"; fi; '+ '"$manager" -y "$repo_option" '+ '--setopt=install_weak_deps=False --setopt=gpgcheck=True ''--setopt=localpkg_gpgcheck=False --nodocs install ' + shlex.quote(destination),- timeout=600)+ timeout=180)(output / (name + '.log')).write_text(text)expected = '\t'.join(['harness-os-session', metadata['package']['version'],str(metadata['package']['release']), 'aarch64'])@@ -108,11 +123,6 @@ print(json.dumps({key:identity(value) for key,value in pids.items()},sort_keys=Tassert 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')@@ -152,7 +162,8 @@ print(json.dumps({key:identity(value) for key,value in pids.items()},sort_keys=Tmachine.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')+ 'systemctl --user unmask harness-update.timer harness-update.service; '+ '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')diff --git a/os/tests/test_opencode_payload.py b/os/tests/test_opencode_payload.pynew file mode 100644index 000000000..8fdc4370f--- /dev/null+++ b/os/tests/test_opencode_payload.py@@ -0,0 +1,169 @@+"""Verify agent provenance and reject corrupted/wrong-platform package inputs."""+import copy+import hashlib+import io+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 opencode_payload as agent+++def elf(machine=183, alignment=65536):+ header = struct.pack('<16sHHIQQQIHHHHHH', b'\x7fELF\x02\x01\x01' + b'\0' * 9,+ 2, machine, 1, 0, 64, 0, 0, 64, 56, 1, 0, 0, 0)+ return header + struct.pack('<IIQQQQQQ', 1, 5, 0, 0, 0, 120, 120, alignment)+++def file_info(data):+ return {'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()}+++class AgentPayload(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ self.archives = self.root / 'archives'+ self.archives.mkdir()+ self.lock = agent.read_lock()+ self.files = {'opencode': elf(), 'LICENSE': b'MIT fixture license\n'}+ self.metadata = {+ 'binary': {'name': 'opencode-linux-arm64', 'version': self.lock['version'],+ 'os': ['linux'], 'cpu': ['arm64']},+ 'license': {'name': 'opencode-ai', 'version': self.lock['version'], 'license': 'MIT',+ 'optionalDependencies': {'opencode-linux-arm64': self.lock['version']}},+ }+ self.rebuild()++ def rebuild(self):+ for name, data in self.files.items():+ self.lock['files'][name].update(file_info(data))+ for kind, entry in self.lock['archives'].items():+ path = self.archives / (entry['package'] + '-' + self.lock['version'] + '.tgz')+ with tarfile.open(path, 'w:gz') as archive:+ files = {'package/package.json': json.dumps(self.metadata[kind]).encode(),+ **{self.lock['files'][name]['member']: data for name, data in self.files.items()+ if self.lock['files'][name]['archive'] == kind}}+ for name, data in files.items():+ info = tarfile.TarInfo(name)+ info.size = len(data)+ archive.addfile(info, io.BytesIO(data))+ entry.update(file_info(path.read_bytes()))++ def prepare(self, name='payload'):+ output = self.root / name+ # A cache hit must use the declared bytes without contacting a service.+ with patch.object(agent.urllib.request, 'urlopen', side_effect=AssertionError('Unexpected download')):+ agent.prepare(self.lock, self.archives, output)+ return output++ def test_repeatable_offline_prepare_and_package_owned_binary_license(self):+ first, second = self.prepare(), self.prepare('again')+ self.assertEqual(agent.identity(first, self.lock), self.lock)+ for name in ['opencode', 'LICENSE', 'manifest.json']:+ self.assertEqual((first / name).read_bytes(), (second / name).read_bytes())+ destination = self.root / 'install'+ agent.stage(first, destination, self.lock)+ binary = destination / 'usr/lib/harness-opencode/opencode'+ self.assertEqual(binary.read_bytes(), self.files['opencode'])+ self.assertEqual(binary.stat().st_mode & 0o777, 0o755)+ self.assertEqual((destination / 'usr/bin/opencode').readlink(), Path('../lib/harness-opencode/opencode'))+ self.assertEqual((destination / 'usr/share/licenses/harness-opencode/LICENSE').read_bytes(), self.files['LICENSE'])+ self.assertEqual(json.loads((destination / 'usr/share/harness-os/opencode.json').read_text()), self.lock)+ self.assertFalse((destination / 'etc').exists())++ def test_cached_archive_corruption_is_rejected_without_partial_payload(self):+ path = next(self.archives.glob('opencode-linux-arm64-*'))+ path.write_bytes(path.read_bytes() + b'changed')+ with self.assertRaisesRegex(ValueError, 'checksum'):+ self.prepare()+ self.assertFalse((self.root / 'payload').exists())++ def test_wrong_architecture_and_page_alignment_fail_despite_matching_hashes(self):+ for binary, message in [(elf(machine=62), 'ARM64'), (elf(alignment=4096), '16 KiB')]:+ with self.subTest(message=message):+ self.files['opencode'] = binary+ self.rebuild()+ with self.assertRaisesRegex(ValueError, message):+ self.prepare()+ self.assertFalse((self.root / 'payload').exists())++ def test_package_version_and_license_dependency_must_match(self):+ for kind, key, value in [('binary', 'version', '9.9.9'), ('binary', 'cpu', ['x64']),+ ('license', 'license', 'proprietary'),+ ('license', 'optionalDependencies', {'opencode-linux-arm64': '9.9.9'})]:+ with self.subTest(kind=kind, key=key):+ original = copy.deepcopy(self.metadata)+ self.metadata[kind][key] = value+ self.rebuild()+ with self.assertRaises(ValueError):+ self.prepare()+ self.assertFalse((self.root / 'payload').exists())+ self.metadata = original++ def test_missing_license_and_payload_corruption_cannot_enter_package(self):+ payload = self.prepare()+ license = payload / 'LICENSE'+ original = license.read_bytes()+ for action in ['missing', 'corrupt', 'symlink']:+ with self.subTest(action=action):+ license.unlink(missing_ok=True)+ if action == 'corrupt':+ license.write_bytes(original + b'changed')+ elif action == 'symlink':+ outside = self.root / 'license'+ outside.write_bytes(original)+ license.symlink_to(outside)+ with self.assertRaisesRegex(ValueError, 'checksum'):+ agent.stage(payload, self.root / 'install', self.lock)+ self.assertFalse((self.root / 'install').exists())++ def test_rewritten_manifest_cannot_authorize_changed_binary(self):+ payload = self.prepare()+ (payload / 'opencode').write_bytes(elf() + b'changed')+ altered = copy.deepcopy(self.lock)+ altered['files']['opencode'].update(file_info((payload / 'opencode').read_bytes()))+ (payload / 'manifest.json').write_text(json.dumps(altered))+ with self.assertRaisesRegex(ValueError, 'reviewed lock'):+ agent.identity(payload, self.lock)++ def test_unsafe_archive_members_are_rejected_without_extracting(self):+ for name, kind, duplicate in [('/tmp/escape', tarfile.REGTYPE, False),+ ('package/../../escape', tarfile.REGTYPE, False),+ ('package/bin/opencode', tarfile.SYMTYPE, False),+ ('package/bin/opencode', tarfile.LNKTYPE, False),+ ('package/bin/opencode', tarfile.REGTYPE, True)]:+ with self.subTest(name=name, kind=kind, duplicate=duplicate):+ data = io.BytesIO()+ with tarfile.open(fileobj=data, mode='w') as archive:+ entry = tarfile.TarInfo(name)+ entry.type = kind+ archive.addfile(entry)+ if duplicate:+ archive.addfile(entry)+ data.seek(0)+ with tarfile.open(fileobj=data) as archive, self.assertRaisesRegex(ValueError, 'Unsafe or duplicate'):+ agent.archive_members(archive)++ def test_lock_rejects_unpinned_urls_unbounded_size_and_wrong_platform(self):+ for area, key, value in [('binary', 'url', 'https://registry.npmjs.org/opencode/latest'),+ ('binary', 'bytes', 301 * 1024**2),+ ('binary', 'sha256', 'bad')]:+ changed = copy.deepcopy(self.lock)+ changed['archives'][area][key] = value+ path = self.root / 'lock.json'+ path.write_text(json.dumps(changed))+ with self.assertRaises(ValueError):+ agent.read_lock(path)+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tools/build-fedora-package.py b/os/tools/build-fedora-package.pyindex 543cf3f7e..eda2f8084 100644--- a/os/tools/build-fedora-package.py+++ b/os/tools/build-fedora-package.py@@ -12,7 +12,7 @@ import subprocessimport tarfileimport tempfile-from fedora_payload import digest, package_identity, runtime_identity, stage+from fedora_payload import digest, runtime_identity, stagedef command(*args, **kwargs):@@ -44,10 +44,11 @@ def file_list(root):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'):+ if name in ['/usr/lib/harness', '/usr/lib/harness-os', '/usr/lib/harness-opencode',+ '/usr/share/licenses/harness-os', '/usr/share/licenses/harness-opencode'] or name.startswith('/usr/share/harness-os'):lines.append('%dir ' + name)else:- lines.append(('%license ' if name.endswith('/licenses/harness-os/LICENSE') else '') + name)+ lines.append(('%license ' if name.startswith('/usr/share/licenses/') else '') + name)return '\n'.join(lines) + '\n'@@ -56,6 +57,7 @@ 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('--agent', type=Path, required=True, help='Verified pinned OpenCode payload; no npm scripts run during packaging.')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()@@ -85,7 +87,7 @@ def main():for name in ['SOURCES', 'SPECS', 'BUILD', 'RPMS', 'SRPMS', 'BUILDROOT']:(top / name).mkdir()payload = top / 'payload'- identity = stage(source, runtime, payload, commit, args.runtime_source)+ identity = stage(source, runtime, payload, commit, args.runtime_source, args.agent.resolve())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'@@ -106,7 +108,8 @@ def main():'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'},+ 'default_agent': {'owner': 'harness-os-session', 'included': True,+ 'name': 'OpenCode', 'version': identity['agent']['version']},'browser': {'owner': 'image', 'included': False, 'optional': True, 'package': 'chromium'},'platform': {'owner': 'Fedora/Asahi', 'included': False}},'package': {'name': package.name, 'version': version, 'release': args.release,diff --git a/os/tools/fedora_payload.py b/os/tools/fedora_payload.pyindex 347c67416..9b83a3804 100644--- a/os/tools/fedora_payload.py+++ b/os/tools/fedora_payload.py@@ -10,6 +10,8 @@ import reimport shutilimport xml.etree.ElementTree as ET+import opencode_payload+def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()@@ -42,7 +44,7 @@ def runtime_identity(runtime, commit):return info-def stage(source, runtime, destination, commit, runtime_commit):+def stage(source, runtime, destination, commit, runtime_commit, agent=None):info = runtime_identity(runtime, runtime_commit)# An allowlist keeps PC hooks and private fixture provisioning out of RPMs.paths = [@@ -118,7 +120,9 @@ def stage(source, runtime, destination, commit, runtime_commit):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)+ bundled = (opencode_payload.stage(agent, destination,+ opencode_payload.read_lock(source / 'os/packaging/fedora/opencode.lock.json')) if agent else None)+ return {'runtime': info, 'agent': bundled, '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()}}diff --git a/os/tools/opencode_payload.py b/os/tools/opencode_payload.pynew file mode 100644index 000000000..33000aa57--- /dev/null+++ b/os/tools/opencode_payload.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+"""Prepare the pinned upstream ARM agent without npm or install-time scripts."""+import argparse+import hashlib+import json+from pathlib import Path, PurePosixPath+import re+import shutil+import struct+import tarfile+import tempfile+import urllib.request+++ROOT = Path(__file__).resolve().parents[2]+LOCK = ROOT / 'os/packaging/fedora/opencode.lock.json'+++def digest(path):+ with path.open('rb') as handle:+ return hashlib.file_digest(handle, 'sha256').hexdigest()+++def read_lock(path=LOCK):+ info = json.loads(path.read_text())+ if (info.get('schema'), info.get('name'), info.get('architecture'), info.get('license')) != (+ 1, 'OpenCode', 'aarch64', 'MIT') or not re.fullmatch(r'\d+\.\d+\.\d+', str(info.get('version'))):+ raise ValueError('Use a versioned OpenCode ARM lock.')+ if set(info.get('archives', {})) != {'binary', 'license'} or set(info.get('files', {})) != {'opencode', 'LICENSE'}:+ raise ValueError('Agent lock must include the binary and its license.')+ for key, package in [('binary', 'opencode-linux-arm64'), ('license', 'opencode-ai')]:+ entry = info['archives'][key]+ url = f'https://registry.npmjs.org/{package}/-/{package}-{info["version"]}.tgz'+ if entry.get('package') != package or entry.get('url') != url:+ raise ValueError('Use the pinned upstream npm package URL.')+ for entry in [*info['archives'].values(), *info['files'].values()]:+ if (type(entry.get('bytes')) is not int or not 0 < entry['bytes'] <= 300 * 1024**2 or+ not re.fullmatch(r'[a-f0-9]{64}', str(entry.get('sha256')))):+ raise ValueError('Every agent input needs a bounded size and SHA-256.')+ for name, archive, member in [('opencode', 'binary', 'package/bin/opencode'), ('LICENSE', 'license', 'package/LICENSE')]:+ if (info['files'][name].get('archive'), info['files'][name].get('member')) != (archive, member):+ raise ValueError('Unexpected upstream agent member.')+ return info+++def verify(path, entry):+ if (path.is_symlink() or not path.is_file() or path.stat().st_size != entry['bytes'] or+ digest(path) != entry['sha256']):+ raise ValueError('Agent checksum mismatch: ' + str(path))+++def check_elf(path):+ with path.open('rb') as handle:+ header = handle.read(64)+ if (len(header) != 64 or header[:7] != b'\x7fELF\x02\x01\x01' or+ struct.unpack_from('<H', header, 16)[0] not in (2, 3) or+ struct.unpack_from('<H', header, 18)[0] != 183):+ raise ValueError('OpenCode must be a little-endian ARM64 ELF executable.')+ offset = struct.unpack_from('<Q', header, 32)[0]+ size, count = struct.unpack_from('<HH', header, 54)+ if size != 56 or not 0 < count <= 256 or offset + size * count > path.stat().st_size:+ raise ValueError('Invalid agent ELF program headers.')+ handle.seek(offset)+ entries = [struct.unpack('<IIQQQQQQ', handle.read(size)) for _ in range(count)]+ loads = [entry for entry in entries if entry[0] == 1]+ if not loads or any(entry[7] < 16384 or entry[7] & (entry[7] - 1) or+ entry[2] % 16384 != entry[3] % 16384 for entry in loads):+ raise ValueError('OpenCode must support 16 KiB ARM pages.')+++def archive_members(archive):+ members = {}+ for member in archive.getmembers():+ path = PurePosixPath(member.name)+ if (not member.isfile() or path.is_absolute() or '..' in path.parts or+ str(path) != member.name or not member.name.startswith('package/') or member.name in members):+ raise ValueError('Unsafe or duplicate agent archive member: ' + member.name)+ members[member.name] = member+ return members+++def prepare(lock, archives, output):+ if output.exists() or output.is_symlink():+ raise ValueError('Agent output must be a new directory.')+ archives.mkdir(parents=True, exist_ok=True)+ output.parent.mkdir(parents=True, exist_ok=True)+ # Do not expose a partly prepared payload after a download or checksum failure.+ with tempfile.TemporaryDirectory(prefix='.opencode-', dir=output.parent) as temp:+ payload = Path(temp) / 'payload'+ payload.mkdir()+ for key, entry in lock['archives'].items():+ path = archives / (entry['package'] + '-' + lock['version'] + '.tgz')+ if not path.exists() and not path.is_symlink():+ partial = Path(temp) / (key + '.download')+ with urllib.request.urlopen(entry['url'], timeout=30) as response, partial.open('xb') as handle:+ remaining = entry['bytes'] + 1+ while remaining:+ chunk = response.read(min(1024 * 1024, remaining))+ if not chunk:+ break+ handle.write(chunk)+ remaining -= len(chunk)+ verify(partial, entry)+ partial.replace(path)+ verify(path, entry)+ with tarfile.open(path, 'r:gz') as archive:+ members = archive_members(archive)+ metadata = members.get('package/package.json')+ if metadata is None or metadata.size > 65536:+ raise ValueError('Missing agent package metadata.')+ package = json.load(archive.extractfile(metadata))+ if (package.get('name'), package.get('version')) != (entry['package'], lock['version']):+ raise ValueError('Agent package metadata does not match its lock.')+ if key == 'binary' and (package.get('os'), package.get('cpu')) != (['linux'], ['arm64']):+ raise ValueError('Unexpected agent platform metadata.')+ if key == 'license' and (package.get('license') != 'MIT' or+ package.get('optionalDependencies', {}).get('opencode-linux-arm64') != lock['version']):+ raise ValueError('Agent license or binary dependency does not match.')+ for name, file in lock['files'].items():+ if file['archive'] != key:+ continue+ member = members.get(file['member'])+ if member is None or member.size != file['bytes']:+ raise ValueError('Missing or wrong-size agent payload: ' + name)+ with archive.extractfile(member) as src, (payload / name).open('xb') as dest:+ shutil.copyfileobj(src, dest)+ verify(payload / name, file)+ (payload / name).chmod(0o755 if name == 'opencode' else 0o644)+ check_elf(payload / 'opencode')+ (payload / 'manifest.json').write_text(json.dumps(lock, indent=2) + '\n')+ payload.rename(output)+++def identity(folder, lock):+ manifest = folder / 'manifest.json'+ if manifest.is_symlink() or not manifest.is_file() or json.loads(manifest.read_text()) != lock:+ raise ValueError('Agent provenance does not match the reviewed lock.')+ for name, entry in lock['files'].items():+ verify(folder / name, entry)+ check_elf(folder / 'opencode')+ return lock+++def stage(folder, destination, lock):+ identity(folder, lock)+ for name, target in [('opencode', 'usr/lib/harness-opencode/opencode'),+ ('LICENSE', 'usr/share/licenses/harness-opencode/LICENSE'),+ ('manifest.json', 'usr/share/harness-os/opencode.json')]:+ path = destination / target+ path.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(folder / name, path)+ path.chmod(0o755 if name == 'opencode' else 0o644)+ link = destination / 'usr/bin/opencode'+ link.parent.mkdir(parents=True, exist_ok=True)+ link.symlink_to('../lib/harness-opencode/opencode')+ return lock+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--archives', type=Path, required=True, help='Reusable verified archive cache.')+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ lock = read_lock()+ prepare(lock, args.archives.resolve(), args.output.absolute())+ print(json.dumps({'version': lock['version'], 'architecture': lock['architecture'],+ 'binary_sha256': lock['files']['opencode']['sha256']}))+++if __name__ == '__main__':+ main()