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
Build and validate native ARM Harness OS runtimes (#747)
Dee985367c992f2
diff --git a/.github/workflows/os-runtime.yml b/.github/workflows/os-runtime.ymlnew file mode 100644index 000000000..7f537f918--- /dev/null+++ b/.github/workflows/os-runtime.yml@@ -0,0 +1,90 @@+name: Harness OS native runtimes++on:+ workflow_dispatch:+ push:+ branches: ['os-polish/arm-runtime']+ paths: ['os/tools/build-runtime.sh', 'os/tests/runtime_native.py', '.github/workflows/os-runtime.yml']++permissions:+ contents: read++concurrency:+ group: harness-native-runtime-${{ github.ref }}+ cancel-in-progress: false++jobs:+ runtime:+ strategy:+ fail-fast: false+ matrix:+ include:+ - { architecture: x86_64, runner: ubuntu-24.04 }+ - { architecture: aarch64, runner: ubuntu-24.04-arm }+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 25+ steps:+ - uses: actions/checkout@v7+ with:+ fetch-depth: 0+ - uses: actions/setup-node@v7+ with:+ node-version: 22.23.2+ cache: npm+ cache-dependency-path: cli/package-lock.json+ - uses: dtolnay/rust-toolchain@stable+ with:+ targets: ${{ matrix.architecture }}-unknown-linux-musl+ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2+ with:+ workspaces: tui+ shared-key: tui-${{ matrix.architecture }}-unknown-linux-musl+ cache-bin: false+ - name: Native build tools and portable OS checks+ run: |+ sudo apt-get update -qq+ sudo apt-get install -y --no-install-recommends musl-tools libevent-dev libncurses-dev libutf8proc-dev bison+ make -C os check+ - name: Use the OS tmux release for native comparison+ run: |+ curl --fail --location --retry 3 --max-time 120 \+ https://github.com/tmux/tmux/releases/download/3.7c/tmux-3.7c.tar.gz \+ --output "$RUNNER_TEMP/tmux.tar.gz"+ echo '7c60cae9a0e25288e2e24750aafc9e8800fc7fd4555e447e1b29ee4201cfb3bf tmux.tar.gz' > "$RUNNER_TEMP/tmux.sha256"+ (cd "$RUNNER_TEMP" && sha256sum --check tmux.sha256)+ mkdir "$RUNNER_TEMP/tmux-source"+ tar -xzf "$RUNNER_TEMP/tmux.tar.gz" -C "$RUNNER_TEMP/tmux-source" --strip-components=1+ cd "$RUNNER_TEMP/tmux-source"+ ./configure --prefix="$RUNNER_TEMP/tmux-reference"+ make -j2+ make install+ "$RUNNER_TEMP/tmux-reference/bin/tmux" -V+ echo "$RUNNER_TEMP/tmux-reference/bin" >> "$GITHUB_PATH"+ - name: Build the exact native Harness runtime+ run: bash os/tools/build-runtime.sh+ - name: Existing native terminal acceptance+ run: python3 scripts/validate-tui-native.py os/work/runtime/harness-tui+ - name: Install the agent only on the disposable test runner+ run: |+ npm install --prefix "$RUNNER_TEMP/harness-native-agent" --no-audit --no-fund opencode-ai+ mkdir -p os/test-results+ cp "$RUNNER_TEMP/harness-native-agent/package-lock.json" os/test-results/agent-test-lock.json+ - name: Real daemon, panes, default agent and surviving work+ run: |+ python3 os/tests/runtime_native.py --architecture '${{ matrix.architecture }}' \+ --runtime os/work/runtime \+ --opencode "$RUNNER_TEMP/harness-native-agent/node_modules/.bin/opencode" \+ --output os/test-results/native-runtime+ - name: Retain runtime and scoped native evidence+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: harness-native-runtime-${{ matrix.architecture }}+ path: |+ os/work/runtime/+ os/test-results/native-runtime/+ os/test-results/agent-test-lock.json+ .harness/validation/+ if-no-files-found: error+ retention-days: 14+ compression-level: 0diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.mdindex ba4e53d44..caf3ad039 100644--- a/os/DEVELOPMENT.md+++ b/os/DEVELOPMENT.md@@ -475,6 +475,35 @@ by blindly copying its file.it does **not** update the pinned Harness runtime. Preview 4's ISO does not containthe small updater; install its separately validated development bundle to add it.+## Native ARM runtime development++`os/tools/build-runtime.sh` builds the same CLI and static hn on native x86-64 or+aarch64 Linux. Rust's matching `*-unknown-linux-musl` target and native Node are+required. The output records the clean source commit, release ancestry, CPU/ELF+architecture, versions and file hashes. Use a fresh `HARNESS_OS_RUNTIME_DIR` to+retain another build; the default is `os/work/runtime`.++The **Harness OS native runtimes** workflow builds both architectures on separate+native Linux runners. It runs the existing complete native terminal fixture set,+then starts the exact bundled daemon with an isolated home and no account. Its+real hn panes accept PTY input, run upstream-default OpenCode to create a Python+project, and preserve the shell process/project through daemon restart and screen+reattachment. Independent checks execute the generated code. Agent packages and+test dependencies stay on disposable runners; their exact lockfile accompanies+the receipt.++This establishes a userspace test path, not an ARM operating-system release.+The PC package builder, installer and public updater still reject ARM payloads.+Raspberry Pi board boot and Apple Silicon's Asahi kernel, firmware, partitioning,+graphics and audio integration remain required. An ARM Ubuntu runner does not+establish compatibility with either device, or with a different distribution's+packages. Retain that boundary when reporting the workflow's results.+The reference tmux uses the OS's checksum-pinned 3.7c source on both runners.+The receipt records the actual kernel page size and hn's ELF load alignment.+An aligned ARM executable still needs execution on a 16 KiB-page kernel before+claiming Apple Silicon userspace compatibility; see+[Asahi's page-size requirements](https://asahilinux.org/docs/sw/broken-software/).+## Mac support targetsIntel Macs and Apple Silicon are both intended OS targets. They share the Harnessdiff --git a/os/tests/runtime_native.py b/os/tests/runtime_native.pynew file mode 100644index 000000000..df1c22b8a--- /dev/null+++ b/os/tests/runtime_native.py@@ -0,0 +1,336 @@+#!/usr/bin/env python3+"""Exercise an exact OS runtime in isolated native Linux panes, without a disk image."""+import argparse+import fcntl+import hashlib+import importlib.util+import json+import os+from pathlib import Path+import platform+import pty+import select+import shlex+import shutil+import signal+import socket+import struct+import subprocess+import tempfile+import termios+import threading+import time+from urllib.request import urlopen++ROOT = Path(__file__).resolve().parents[2]+++def wait(predicate, label, seconds=30):+ deadline = time.monotonic() + seconds+ last = None+ while time.monotonic() < deadline:+ try:+ if result := predicate():+ return result+ except (OSError, ValueError, subprocess.SubprocessError) as error:+ last = str(error)+ time.sleep(.1)+ raise RuntimeError(f'{label} timed out; last observation: {last}')+++def checksum(path):+ with path.open('rb') as handle:+ return hashlib.file_digest(handle, 'sha256').hexdigest()+++class Screen:+ def __init__(self, argv, env, cwd):+ self.fd, slave = pty.openpty()+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 32, 100, 0, 0))++ def setup():+ os.setsid()+ fcntl.ioctl(0, termios.TIOCSCTTY, 0)++ self.process = subprocess.Popen(argv, env=env, cwd=cwd, stdin=slave, stdout=slave,+ stderr=slave, preexec_fn=setup)+ os.close(slave)+ self.data = bytearray()+ self.reading = True+ self.thread = threading.Thread(target=self.read, daemon=True)+ self.thread.start()++ def read(self):+ while self.reading:+ if select.select([self.fd], [], [], .1)[0]:+ try:+ chunk = os.read(self.fd, 65536)+ except OSError:+ break+ if not chunk:+ break+ self.data.extend(chunk)++ def write(self, text):+ pending = memoryview(text.encode())+ while pending:+ sent = os.write(self.fd, pending)+ if sent <= 0:+ raise RuntimeError('Terminal input closed')+ pending = pending[sent:]++ def close(self):+ if self.process.poll() is None:+ self.process.terminate()+ self.process.wait(timeout=5)+ self.reading = False+ self.thread.join(timeout=2)+ os.close(self.fd)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--runtime', type=Path, required=True)+ parser.add_argument('--opencode', type=Path, required=True)+ parser.add_argument('--architecture', choices=['x86_64', 'aarch64'], required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ if platform.system() != 'Linux' or platform.machine() != args.architecture or os.geteuid() == 0:+ parser.error('Run as an ordinary user on the matching native Linux runner.')+ runtime = args.runtime.resolve()+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ info = json.loads((runtime / 'source.json').read_text())+ source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()+ assert info['source_commit'] == source and info['dirty'] is False+ assert info['architecture'] == args.architecture+ assert info['target'] == args.architecture + '-unknown-linux-musl'+ assert set(info['files']) == {'harness-tui', 'cli.js', 'notify.mjs'}+ for name, identity in info['files'].items():+ assert (runtime / name).stat().st_size == identity['bytes']+ assert checksum(runtime / name) == identity['sha256']+ assert subprocess.check_output(['node', '-p', 'process.arch'], text=True).strip() == {+ 'x86_64': 'x64', 'aarch64': 'arm64'}[args.architecture]+ with (runtime / 'harness-tui').open('rb') as handle:+ header = handle.read(64)+ phoff = struct.unpack_from('<Q', header, 32)[0]+ phsize, phcount = struct.unpack_from('<HH', header, 54)+ assert phsize == 56 and 0 < phcount < 100+ handle.seek(phoff)+ phdrs = handle.read(phsize * phcount)+ assert header[:6] == b'\x7fELF\x02\x01'+ assert int.from_bytes(header[18:20], 'little') == {'x86_64': 62, 'aarch64': 183}[args.architecture]+ load_alignments = [struct.unpack_from('<IIQQQQQQ', phdrs, index * phsize)[-1]+ for index in range(phcount) if struct.unpack_from('<I', phdrs, index * phsize)[0] == 1]+ assert load_alignments and all(value >= (16384 if args.architecture == 'aarch64' else 4096)+ for value in load_alignments)+ spec = importlib.util.spec_from_file_location('package', ROOT / 'os/tools/build-package.py')+ package = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(package)+ if args.architecture == 'x86_64':+ package.validate_runtime(runtime, source)+ else:+ try:+ package.validate_runtime(runtime, source)+ except ValueError:+ pass+ else:+ raise AssertionError('The PC image must reject an ARM runtime')+ receipt = {'status': 'running', 'scope': 'native userspace; no boot, drivers or platform installation',+ 'architecture': args.architecture, 'kernel': platform.release(), 'runtime': info,+ 'page_size': os.sysconf('SC_PAGE_SIZE'), 'hn_load_alignments': load_alignments,+ 'tmux': subprocess.check_output(['tmux', '-V'], text=True).strip(),+ 'checks': ['Exact source, native ELF/Node architecture, complete hashes and PC packaging boundary verified'],+ 'started_at_unix': time.time()}+ report = output / 'receipt.json'+ report.write_text(json.dumps(receipt, indent=2) + '\n')+ daemon = screen = None+ logs = []+ with tempfile.TemporaryDirectory(prefix='harness-native-', dir='/tmp') as temporary:+ base = Path(temporary)+ home, binaries = base / 'home', base / 'bin'+ project = home / 'projects/native-agent'+ project.mkdir(parents=True)+ binaries.mkdir()+ shutil.copy2(runtime / 'harness-tui', binaries / 'hn')+ wrapper = binaries / 'harness'+ wrapper.write_text('#!/bin/sh\nexec ' + shlex.join([shutil.which('node'), str(runtime / 'cli.js')]) + ' "$@"\n')+ wrapper.chmod(0o755)+ (binaries / 'opencode').symlink_to(args.opencode.resolve())+ # No host HOME, tokens, provider settings, tmux socket or model choice.+ env = {key: os.environ[key] for key in ['PATH', 'LANG', 'LC_ALL', 'TZ'] if key in os.environ}+ with socket.socket() as listener:+ listener.bind(('127.0.0.1', 0))+ port = listener.getsockname()[1]+ prefix = 'harness-native-' + str(os.getpid())+ env.update(HOME=str(home), XDG_CONFIG_HOME=str(home / '.config'),+ XDG_DATA_HOME=str(home / '.local/share'), XDG_STATE_HOME=str(home / '.local/state'),+ XDG_CACHE_HOME=str(home / '.cache'), PATH=str(binaries) + ':' + env['PATH'],+ PORT=str(port), HN_TMPDIR=str(base), HN_SOCKET_NAME=prefix,+ TMUX_TMPDIR=str(base), SHELL='/bin/bash',+ TERM='xterm-256color', HARNESS_OS='1', HARNESS_TUI_DESK='off',+ HARNESS_TUI_NOTIFY='off', HARNESS_TUI_BIN=str(binaries / 'hn'),+ HARNESS_CLI=str(wrapper), HARNESS_CLI_ARGS='[]', ADAPTER_UPDATE_DISABLE='true',+ CABLE_DISABLE='true')+ command = [str(binaries / 'hn'), '-L', prefix, '--port', str(port), '-f',+ str(ROOT / 'os/root/usr/share/harness-os/tmux.conf')]++ def hn(*args, check=True):+ return subprocess.run([*command, *args], cwd=project, env=env, text=True,+ capture_output=True, timeout=15, check=check).stdout.strip()++ def start_daemon():+ log = (output / f'daemon-{len(logs)}.log').open('w')+ logs.append(log)+ process = subprocess.Popen([str(wrapper), 'start', '--foreground'], env=env, cwd=project,+ stdout=log, stderr=subprocess.STDOUT, start_new_session=True)+ return process++ def ready():+ if daemon.poll() is not None:+ raise RuntimeError(f'Harness daemon exited: {daemon.returncode}')+ with urlopen(f'http://127.0.0.1:{port}/api/status', timeout=2) as response:+ status = json.load(response)+ return status.get('discoveryReady') is True and status.get('safeMode') is not True++ def stop_daemon():+ if daemon and daemon.poll() is None:+ os.killpg(daemon.pid, signal.SIGTERM)+ try:+ daemon.wait(timeout=12)+ except subprocess.TimeoutExpired:+ os.killpg(daemon.pid, signal.SIGKILL)+ daemon.wait(timeout=5)++ def stop_tmux():+ # The daemon's terminal backend also needs an isolated server. Never+ # kill the host's default tmux server when cleaning up this fixture.+ tmux_socket = base / f'tmux-{os.getuid()}' / 'default'+ if tmux_socket.exists():+ subprocess.run(['tmux', '-S', str(tmux_socket), 'kill-server'],+ env=env, check=True, capture_output=True, timeout=15)++ def type_into_screen(pane, line):+ hn('select-pane', '-t', pane)+ time.sleep(.2)+ assert screen.process.poll() is None, 'Native terminal closed'+ screen.write(line + '\r')++ try:+ receipt['opencode_version'] = subprocess.check_output([str(binaries / 'opencode'), '--version'],+ env=env, cwd=project, text=True, timeout=30).strip()+ daemon = start_daemon()+ wait(ready, 'Native daemon readiness', 90)+ receipt['checks'].append('The exact bundled CLI starts without an account and becomes discovery-ready')+ shell = hn('new-session', '-d', '-s', 'runtime', '-c', str(project),+ '-x', '100', '-y', '32', '-P', '-F', '#{pane_id}',+ 'bash --noprofile --norc')+ right = hn('split-window', '-h', '-p', '50', '-t', shell, '-c', str(project), '-P', '-F', '#{pane_id}',+ 'bash --noprofile --norc')+ agent = hn('split-window', '-v', '-p', '50', '-t', right, '-c', str(project), '-P', '-F', '#{pane_id}',+ 'bash --noprofile --norc')+ screen = Screen([*command, 'attach-session', '-t', 'runtime'], env, project)+ wait(lambda: screen.data, 'Native screen output')+ # The daemon adopts pending shells asynchronously; a first escape+ # sequence is not proof that a terminal is ready for input yet.+ for pane in [shell, right, agent]:+ wait(lambda: hn('display-message', '-p', '-t', pane, '#{pane_current_path}') == str(project),+ 'Project working directory in ' + pane)+ type_into_screen(shell, 'printf "%s" "$$" > ' + shlex.quote(str(project / 'shell.pid')) ++ '; printf before > ' + shlex.quote(str(project / 'keyboard.txt')))+ wait(lambda: (project / 'keyboard.txt').read_text() == 'before', 'PTY keyboard input')+ # A daemon-backed pane is not a local PTY owner and need not expose+ # pane_pid. Ask the actual shell, independently of UI metadata.+ pid = int((project / 'shell.pid').read_text())+ start_time = Path(f'/proc/{pid}/stat').read_text().split()[21]+ receipt['checks'].append('Three real hn shell panes open; the attached terminal accepts native PTY keyboard input')+ prompt = ('Create sum.py here using only the Python standard library. It must accept zero or more '+ 'signed integer command-line arguments, print their sum as one integer, and exit successfully. '+ 'No arguments must print 0. Test it. Do the work now without questions or subagents.')+ # Keep the agent open as it is on the OS. A completed `opencode run`+ # process is archived by Harness; that is not a running pane to retain.+ agent_command = shlex.join(['opencode', '--prompt', prompt])+ type_into_screen(agent, 'printf "%s" "$$" > agent.pid; exec ' + agent_command)++ def project_passes():+ if not (project / 'sum.py').is_file():+ return False+ before = checksum(project / 'sum.py')+ results = []+ receipt['project_execution'] = results+ for values, expected in [([], '0'), (['13', '-5', '7'], '15'),+ (['999999999999999999999', '1'], '1000000000000000000000')]:+ actual = subprocess.run(['python3', str(project / 'sum.py'), *values], env=env,+ cwd=project, text=True, timeout=5, capture_output=True,+ stdin=subprocess.DEVNULL)+ results.append({'arguments': values, 'expected': expected, 'exit': actual.returncode,+ 'stdout': actual.stdout, 'stderr': actual.stderr})+ if actual.returncode != 0 or actual.stdout.strip() != expected:+ return False+ return before == checksum(project / 'sum.py')++ # Judge the actual work independently, rather than asking the model+ # to manufacture a fixture-only "done" file or trusting its reply.+ wait(project_passes, 'Agent-created Python passes independent execution', 480)+ agent_pid = int((project / 'agent.pid').read_text())+ agent_start_time = Path(f'/proc/{agent_pid}/stat').read_text().split()[21]+ receipt['checks'].append('Upstream-default OpenCode runs inside an hn pane and creates Python code that passes independent execution checks')+ expected_panes = {shell, right, agent}+ before_panes = hn('list-panes', '-t', 'runtime', '-F', '#{pane_id}').splitlines()+ assert set(before_panes) == expected_panes, ('Before restart', before_panes, expected_panes)+ (output / 'agent-before-restart.txt').write_text(hn('capture-pane', '-p', '-t', agent) + '\n')+ project_digest = checksum(project / 'sum.py')+ stop_daemon()+ daemon = start_daemon()+ wait(ready, 'Restarted native daemon readiness', 90)+ assert Path(f'/proc/{pid}/stat').read_text().split()[21] == start_time+ assert Path(f'/proc/{agent_pid}/stat').read_text().split()[21] == agent_start_time+ assert checksum(project / 'sum.py') == project_digest+ screen.close()+ (output / 'before-reconnect.ansi').write_bytes(screen.data)+ screen = None+ screen = Screen([*command, 'attach-session', '-t', 'runtime'], env, project)+ wait(lambda: screen.data, 'Reattached native screen')+ type_into_screen(shell, 'printf after > keyboard.txt')+ wait(lambda: (project / 'keyboard.txt').read_text() == 'after', 'Keyboard input after daemon/screen restart')+ assert Path(f'/proc/{pid}/stat').read_text().split()[21] == start_time+ assert Path(f'/proc/{agent_pid}/stat').read_text().split()[21] == agent_start_time+ after_panes = hn('list-panes', '-t', 'runtime', '-F', '#{pane_id}').splitlines()+ assert set(after_panes) == expected_panes, ('After restart', after_panes, expected_panes)+ (output / 'agent-after-restart.txt').write_text(hn('capture-pane', '-p', '-t', agent) + '\n')+ receipt['checks'].append('The same shell and interactive agent processes, three pane identities and generated project survive daemon restart and screen reattachment; keyboard input still works')+ receipt['surviving_processes'] = {'shell': {'pid': pid, 'start_time': start_time},+ 'opencode_launcher': {'pid': agent_pid, 'start_time': agent_start_time}}+ receipt.update(status='passed', project_sha256=project_digest)+ except BaseException as error:+ receipt.update(status='failed', error=str(error))+ raise+ finally:+ cleanup_errors = []+ if screen:+ (output / 'terminal.ansi').write_bytes(screen.data)+ try:+ screen.close()+ except (OSError, subprocess.SubprocessError) as error:+ cleanup_errors.append(str(error))+ for cleanup in [lambda: hn('kill-server', check=False), stop_daemon, stop_tmux]:+ try:+ cleanup()+ except (OSError, subprocess.SubprocessError) as error:+ cleanup_errors.append(str(error))+ for log in logs:+ log.close()+ for name in ['sum.py', 'agent.pid', 'shell.pid']:+ if (project / name).is_file():+ shutil.copy2(project / name, output / name)+ receipt['finished_at_unix'] = time.time()+ if cleanup_errors:+ receipt.update(status='failed', cleanup_errors=cleanup_errors)+ report.write_text(json.dumps(receipt, indent=2) + '\n')+ if cleanup_errors:+ raise RuntimeError('Native fixture cleanup did not complete: ' + '; '.join(cleanup_errors))+ print(json.dumps(receipt, indent=2))+++if __name__ == '__main__':+ main()diff --git a/os/tests/test_package.py b/os/tests/test_package.pyindex 6c517210d..b81bf4418 100644--- a/os/tests/test_package.py+++ b/os/tests/test_package.py@@ -69,7 +69,8 @@ class PackageIdentity(unittest.TestCase):(root / name).write_text('runtime fixture')(root / 'source.json').write_text(json.dumps(good))self.assertEqual(package.validate_runtime(root, 'a' * 40), good)- for changes in [{'dirty': True}, {'source_commit': 'b' * 40}, {'target': 'aarch64-apple-darwin'}]:+ for changes in [{'dirty': True}, {'source_commit': 'b' * 40}, {'target': 'aarch64-apple-darwin'},+ {'target': 'aarch64-unknown-linux-musl', 'architecture': 'aarch64'}]:(root / 'source.json').write_text(json.dumps(dict(good, **changes)))with self.subTest(changes=changes), self.assertRaises(ValueError):package.validate_runtime(root, 'a' * 40)diff --git a/os/tools/build-runtime.sh b/os/tools/build-runtime.shindex 7ef9abcdf..4f52e84ba 100644--- a/os/tools/build-runtime.sh+++ b/os/tools/build-runtime.sh@@ -1,31 +1,53 @@#!/usr/bin/env bash-# Build as an ordinary user on x86_64 Linux, before the privileged image build.+# Build natively as an ordinary Linux user, before the privileged platform build.set -euo pipefailREPO_DIR=$(cd -- "$(dirname -- "$0")/../.." && pwd)-[[ $(uname -sm) == 'Linux x86_64' ]] || { echo 'OS runtimes require an x86_64 Linux build host.' >&2; exit 1; }+case $(uname -sm) in+ 'Linux x86_64') runtime_arch=x86_64 ;;+ 'Linux aarch64') runtime_arch=aarch64 ;;+ *) echo 'OS runtimes require a native x86_64 or aarch64 Linux build host.' >&2; exit 1 ;;+esac+runtime_target="$runtime_arch-unknown-linux-musl"cd "$REPO_DIR"+runtime_output=${HARNESS_OS_RUNTIME_DIR:-os/work/runtime}+[[ ! -e "$runtime_output" && ! -L "$runtime_output" ]] || { echo 'Use a fresh HARNESS_OS_RUNTIME_DIR; runtime artifacts are immutable.' >&2; exit 1; }# Check ancestry before the expensive build. A source bundle can contain fixes# newer than the public CLI even while package.json retains its development version.python3 os/tools/runtime-baseline.py >/dev/nullnpm ci --prefix cli --no-audit --no-fund(cd cli && node build-bundle.mjs)-cargo build --manifest-path tui/Cargo.toml --locked --release --target x86_64-unknown-linux-musl-mkdir -p os/work/runtime-cp tui/target/x86_64-unknown-linux-musl/release/harness-tui os/work/runtime/-cp cli/dist/cli.js cli/dist/notify.mjs os/work/runtime/-python3 - <<'PY'-import json, pathlib, subprocess, tomllib+cargo build --manifest-path tui/Cargo.toml --locked --release --target "$runtime_target"+runtime_stage=$(mktemp -d "${TMPDIR:-/tmp}/harness-runtime.XXXXXX")+trap 'rm -rf -- "$runtime_stage"' EXIT+cp "tui/target/$runtime_target/release/harness-tui" "$runtime_stage/"+cp cli/dist/cli.js cli/dist/notify.mjs "$runtime_stage/"+HARNESS_RUNTIME_STAGE="$runtime_stage" HARNESS_RUNTIME_ARCH="$runtime_arch" python3 - <<'PY'+import hashlib, json, os, pathlib, subprocess, tomllibdef output(*args):return subprocess.check_output(args, text=True).strip()+folder = pathlib.Path(os.environ['HARNESS_RUNTIME_STAGE'])+architecture = os.environ['HARNESS_RUNTIME_ARCH']+node_arch, elf_machine = {'x86_64': ('x64', 62), 'aarch64': ('arm64', 183)}[architecture]+assert output('node', '-p', 'process.arch') == node_arch, 'Node must match the native build architecture'+with (folder / 'harness-tui').open('rb') as handle:+ header = handle.read(20)+assert header[:6] == b'\x7fELF\x02\x01' and int.from_bytes(header[18:20], 'little') == elf_machine, 'Wrong terminal ELF architecture'data = {'source_commit': output('git', 'rev-parse', 'HEAD'),'dirty': bool(output('git', 'status', '--porcelain', '--untracked-files=no')),'node': output('node', '--version'), 'rust': output('rustc', '--version'),- 'target': 'x86_64-unknown-linux-musl'}+ 'architecture': architecture, 'target': architecture + '-unknown-linux-musl'}+assert not data['dirty'], 'Commit source changes before building a traceable runtime'expected_hn = tomllib.loads(pathlib.Path('tui/Cargo.toml').read_text())['package']['version']expected_cli = json.loads(pathlib.Path('cli/package.json').read_text())['version']-assert output('os/work/runtime/harness-tui', '--version').startswith('hn ' + expected_hn + ' ')-assert output('node', 'cli/dist/cli.js', 'version') == expected_cli+assert output(str(folder / 'harness-tui'), '--version').startswith('hn ' + expected_hn + ' ')+assert output('node', str(folder / 'cli.js'), 'version') == expected_clidata['versions'] = {'hn': expected_hn, 'cli': expected_cli}data['release_baselines'] = json.loads(output('python3', 'os/tools/runtime-baseline.py'))-pathlib.Path('os/work/runtime/source.json').write_text(json.dumps(data, indent=2) + '\n')+data['files'] = {path.name: {'sha256': hashlib.sha256(path.read_bytes()).hexdigest(), 'bytes': path.stat().st_size}+ for path in sorted(folder.iterdir())}+(folder / 'source.json').write_text(json.dumps(data, indent=2) + '\n')PY+mkdir -p -- "$(dirname -- "$runtime_output")"+mkdir -- "$runtime_output"+cp "$runtime_stage/harness-tui" "$runtime_stage/cli.js" "$runtime_stage/notify.mjs" "$runtime_output/"+cp "$runtime_stage/source.json" "$runtime_output/"