Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Add Harness: an operating system built around agents (#669)

Dee4be28872e0dc
diff --git a/.github/workflows/os.yml b/.github/workflows/os.yml
new file mode 100644
index 000000000..5e7b24274
--- /dev/null
+++ b/.github/workflows/os.yml
@@ -0,0 +1,304 @@
+name: Harness OS
+
+on:
+ workflow_dispatch:
+ inputs:
+ image_run_id:
+ description: 'Optional: test an existing image artifact from this workflow run ID'
+ required: false
+ type: string
+ publish_run_id:
+ description: 'Publish a previously passed and visually reviewed machine-test run; image_run_id may identify its image build'
+ required: false
+ type: string
+ dsh_run_id:
+ description: 'Optional for publication: successful DSH machine run for the same image'
+ required: false
+ type: string
+ workloads:
+ description: 'Opt in to real free OpenCode model calls, four project builds and browser/API acceptance in the disposable BIOS VM'
+ required: false
+ default: false
+ type: boolean
+ dsh:
+ description: 'Opt in to three free-model DSH agents and shared Web/Game Viewer acceptance in the disposable BIOS VM'
+ required: false
+ default: false
+ type: boolean
+ workload_seed_run_id:
+ description: 'Optional: reuse the generated projects from this workload run; finish its game agent and rerun all acceptance checks'
+ required: false
+ type: string
+ memory_mib:
+ description: 'VM RAM; 1024 exercises constrained machines, 4096 enables automatic USB copy-to-RAM'
+ required: false
+ default: '2048'
+ type: choice
+ options: ['2048', '1024', '4096']
+ live_transport:
+ description: 'Boot the ISO as a virtual optical disc or a writable USB with a private overlay'
+ required: false
+ default: 'cdrom'
+ type: choice
+ options: ['cdrom', 'usb']
+ development_update:
+ description: 'Build a small Harness package; test offline apply, failure, rollback and reboot using image_run_id'
+ required: false
+ default: false
+ type: boolean
+ push:
+ branches: ['os/**']
+ paths: ['os/**', 'tui/**', 'cli/**', '.github/workflows/os.yml']
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: programmer-os-${{ github.ref }}-${{ inputs.memory_mib || '2048' }}-${{ inputs.live_transport || 'cdrom' }}-${{ inputs.development_update && 'update' || inputs.dsh && 'dsh' || inputs.workloads && 'workloads' || 'image' }}
+ cancel-in-progress: false
+
+jobs:
+ image:
+ if: ${{ !inputs.image_run_id && !inputs.publish_run_id && !inputs.development_update }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 50
+ steps:
+ - uses: actions/checkout@v7
+ - name: Record start and capacity
+ run: |
+ date -u
+ df -h .
+ free -h
+ - name: Validate installer safety and image configuration
+ run: |
+ make -C os check
+ go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os.yml
+ - 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: x86_64-unknown-linux-musl
+ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6
+ with:
+ workspaces: tui
+ shared-key: tui-x86_64-unknown-linux-musl
+ cache-bin: false
+ - name: Build Harness from the exact OS source
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y musl-tools tmux
+ make -C os runtime
+ - name: Validate hn session behavior and native terminal lifecycle
+ run: |
+ npm --prefix cli run typecheck
+ cd cli
+ timeout 3m npx vitest run src/lib/engineInstall.spec.ts src/lib/engineLaunch.spec.ts --maxWorkers=2
+ cd ..
+ timeout 8m cargo test --manifest-path tui/Cargo.toml --locked --release --target x86_64-unknown-linux-musl
+ python3 scripts/validate-tui-native.py tui/target/x86_64-unknown-linux-musl/release/harness-tui
+ - name: Build offline BIOS and UEFI image
+ run: |
+ docker run --rm --privileged \
+ -v "$PWD:/src" -w /src/os \
+ -e SOURCE_DATE_EPOCH="$(git log -1 --format=%ct)" \
+ -e HARNESS_OS_SOURCE_SHA="$(git rev-parse HEAD)" \
+ -e HARNESS_OS_RUNTIME_DIR=/src/os/work/runtime \
+ archlinux:base-devel \
+ bash -c 'set -euo pipefail; pacman -Syu --noconfirm archiso python git; bash build.sh'
+ - name: Inspect image artifact
+ run: |
+ cd os/dist
+ sha256sum -c ./*.sha256
+ cat manifest.json
+ ls -lh ./*.iso
+ - name: Retain image, checksums, package inventory and build manifest
+ uses: actions/upload-artifact@v6
+ with:
+ name: programmer-os-x86_64
+ path: os/dist/
+ retention-days: 14
+ compression-level: 0
+ - name: Retain build diagnostics
+ if: failure()
+ uses: actions/upload-artifact@v6
+ with:
+ name: programmer-os-build-diagnostics
+ path: |
+ .harness/validation/
+ os/work/profile/profiledef.sh
+ os/work/profile/pacman.conf
+ os/work/archiso/x86_64/airootfs/var/log/pacman.log
+ retention-days: 7
+
+ machine:
+ needs: image
+ if: ${{ always() && !inputs.publish_run_id && !inputs.development_update && (needs.image.result == 'success' || inputs.image_run_id != '') && !cancelled() }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 65
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - firmware: bios
+ encryption: ''
+ agents: '--agents'
+ cpu: '--cpu Nehalem'
+ - firmware: uefi
+ encryption: '--encrypt'
+ agents: ''
+ cpu: ''
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/download-artifact@v6
+ with:
+ name: programmer-os-x86_64
+ path: os/dist
+ run-id: ${{ inputs.image_run_id || github.run_id }}
+ github-token: ${{ github.token }}
+ - name: Install VM test tools
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr
+ if test -e /dev/kvm; then sudo chmod a+rw /dev/kvm; fi
+ - name: Restore prior generated workload projects
+ if: ${{ inputs.workload_seed_run_id != '' && matrix.firmware == 'bios' }}
+ uses: actions/download-artifact@v6
+ with:
+ name: programmer-os-vm-bios
+ path: os/work/workload-seed
+ run-id: ${{ inputs.workload_seed_run_id }}
+ github-token: ${{ github.token }}
+ - name: Boot, operate, install and reboot the real image
+ env:
+ OS_WORKLOAD_SOURCE_RUN: ${{ inputs.workload_seed_run_id }}
+ OS_MEMORY_MIB: ${{ inputs.memory_mib || '2048' }}
+ OS_LIVE_TRANSPORT: ${{ inputs.live_transport || 'cdrom' }}
+ run: python3 os/tests/vm.py --iso os/dist/*.iso --memory "$OS_MEMORY_MIB" --live-transport "$OS_LIVE_TRANSPORT" --firmware '${{ matrix.firmware }}' ${{ matrix.encryption }} ${{ matrix.agents }} ${{ matrix.cpu }} ${{ (inputs.workloads || inputs.workload_seed_run_id != '') && matrix.firmware == 'bios' && '--workloads' || '' }} ${{ inputs.dsh && matrix.firmware == 'bios' && '--dsh' || '' }} ${{ inputs.workload_seed_run_id != '' && matrix.firmware == 'bios' && '--workload-seed os/work/workload-seed' || '' }}
+ - name: Show machine failure diagnostics
+ if: failure()
+ run: |
+ find os/test-results -type f \( -name receipt.json -o -name qemu.log -o -name guest-diagnostics.log \) -exec tail -c 14000 {} \;
+ - name: Retain screenshots, measurements and serial diagnostics
+ if: always()
+ uses: actions/upload-artifact@v6
+ with:
+ name: programmer-os-vm-${{ matrix.firmware }}
+ path: |
+ os/test-results/**/*.png
+ os/test-results/**/*.log
+ os/test-results/**/*.txt
+ os/test-results/**/*.json
+ os/test-results/**/*.jsonl
+ os/test-results/**/workloads/**
+ os/test-results/**/dsh/**
+ retention-days: 14
+
+ development-update:
+ if: ${{ inputs.development_update && !inputs.publish_run_id }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v7
+ - name: Check package and updater contracts
+ env:
+ OS_IMAGE_RUN: ${{ inputs.image_run_id }}
+ run: |
+ test -n "$OS_IMAGE_RUN"
+ date -u
+ df -h .
+ make -C os check
+ go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os.yml
+ - 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: x86_64-unknown-linux-musl
+ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6
+ with:
+ workspaces: tui
+ shared-key: tui-x86_64-unknown-linux-musl
+ cache-bin: false
+ - uses: actions/download-artifact@v6
+ with:
+ name: programmer-os-x86_64
+ path: os/dist
+ run-id: ${{ inputs.image_run_id }}
+ github-token: ${{ github.token }}
+ - name: Build the small package from this source
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y musl-tools qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr
+ if test -e /dev/kvm; then sudo chmod a+rw /dev/kvm; fi
+ make -C os runtime
+ python3 os/tools/build-package.py --runtime os/work/runtime --output os/work/development-update --development
+ - name: Exercise apply, rollback, running work and encrypted reboot
+ run: python3 os/tests/update_vm.py --iso os/dist/*.iso --bundle os/work/development-update
+ - name: Show update failure diagnostics
+ if: failure()
+ run: |
+ find os/test-results/runtime-update -type f \( -name receipt.json -o -name qemu.log -o -name update.log -o -name serial.log \) -exec tail -c 10000 {} \;
+ - name: Retain the package and exact update evidence
+ if: always()
+ uses: actions/upload-artifact@v6
+ with:
+ name: harness-development-update
+ path: |
+ os/work/development-update/
+ os/test-results/runtime-update/*.json
+ os/test-results/runtime-update/*.jsonl
+ os/test-results/runtime-update/*.log
+ os/test-results/runtime-update/*.txt
+ os/test-results/runtime-update/*.png
+ retention-days: 14
+ compression-level: 0
+
+ publish:
+ if: ${{ inputs.publish_run_id != '' }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ permissions:
+ contents: write
+ actions: read
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/download-artifact@v6
+ with:
+ name: programmer-os-x86_64
+ path: os/release-input/image
+ run-id: ${{ inputs.image_run_id || inputs.publish_run_id }}
+ github-token: ${{ github.token }}
+ - uses: actions/download-artifact@v6
+ with:
+ pattern: programmer-os-vm-*
+ path: os/release-input/machines
+ run-id: ${{ inputs.publish_run_id }}
+ github-token: ${{ github.token }}
+ - name: Include separately validated DSH examples
+ if: ${{ inputs.dsh_run_id != '' }}
+ uses: actions/download-artifact@v6
+ with:
+ pattern: programmer-os-vm-*
+ path: os/release-input/dsh-machines
+ run-id: ${{ inputs.dsh_run_id }}
+ github-token: ${{ github.token }}
+ - name: Verify prior evidence, publish preview and verify public downloads
+ env:
+ GH_TOKEN: ${{ github.token }}
+ OS_TEST_RUN: ${{ inputs.publish_run_id }}
+ OS_IMAGE_RUN: ${{ inputs.image_run_id || inputs.publish_run_id }}
+ OS_DSH_RUN: ${{ inputs.dsh_run_id }}
+ run: python3 os/tools/publish.py --input os/release-input --tests "$OS_TEST_RUN" --image "$OS_IMAGE_RUN" --dsh "${OS_DSH_RUN:-0}" --repo "$GITHUB_REPOSITORY"
+ - name: Retain publication receipt
+ if: always()
+ uses: actions/upload-artifact@v6
+ with:
+ name: programmer-os-publication
+ path: os/release-input/publication.json
+ retention-days: 30
diff --git a/AGENTS.md b/AGENTS.md
index 87a1ab9e5..23954154d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -3,6 +3,9 @@
Follow [CONTRIBUTING.md](CONTRIBUTING.md) and the component's instructions. For
validation and shipping, use [docs/validation-and-release.md](docs/validation-and-release.md).
+For product names, terminology, and visible copy, follow the
+[Naming System](docs/naming-system.md).
+
- Measure the user's request through completion. Record implementation, validation,
merge, publication, and waiting separately; an Actions duration is not the total.
- Choose the necessary checks before starting them. Run affected tests and relevant
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index deb2527cf..7a5738412 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -29,8 +29,8 @@ The first command links the shared viewer from this checkout. Store installation
that dependency automatically; this also lets you try a new viewer before it is published.
**A harness packages an agent’s instructions, tools, and optional viewer.** Install it,
-start it in your workspace, and group it with other harnesses in a swarm; see the
-[terminology guide](docs/terminology.md). This example has three working files:
+start it in your workspace, and group it with other harnesses in a tab; see the
+[Naming System](docs/naming-system.md). This example has three working files:
- [`harness.json`](store/examples/hello-world/harness.json) declares the agent and its viewer.
- [`AGENTS.md`](store/examples/hello-world/AGENTS.md) teaches the agent to change the greeting.
diff --git a/README.md b/README.md
index f7f35e4d1..ce9131bf7 100644
--- a/README.md
+++ b/README.md
@@ -71,14 +71,14 @@ for workloads, slow tails, connection failures and raw data.
## How it works
In the workspace, a **harness** is one running session of an agent such as Codex
-or Claude Code, with its own conversation and working context. A **swarm** groups
-harnesses. Use **New Harness** to start one and **New Swarm** to group work.
-Enable **Settings → Experimental → Swarm collaboration** to let their agents
-consult peers in the same swarm; it is off by default.
+or Claude Code, with its own conversation and working context. A **tab** groups
+harnesses. Use **New Harness** to start one and **New Tab** to group work.
+Enable **Settings → Experimental → Tab collaboration** to let their agents
+consult peers in the same tab; it is off by default.
The Store offers **harnesses** with instructions, tools, and optional viewers for
specific crafts. Install a harness, then start it in your workspace. See the
-[terminology guide](docs/terminology.md) for the complete naming rules.
+[Naming System](docs/naming-system.md) for the complete naming rules.
One daemon per machine runs your agents in tmux. It dials out, so no machine opens a port.
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index b2a5468a1..38f91b71f 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -6440,6 +6440,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// fires no hook at all (no SessionStart/UserPromptSubmit/Stop) and never streams a single event.
// Idempotent, so paying this on every create against an already-set-up profile is free.
if (codexHome && !env.DISABLE_HOOK_INSTALL) installCodexHooks(hookPort, codexHome)
+ // OpenCode may have upgraded from 1.x to 2.x while this daemon was running. Its new TUI must
+ // not discover our old server plugin; the cached version probe changes with the executable.
+ if (engine === 'opencode' && !env.DISABLE_HOOK_INSTALL) installOpencodePlugin(hookPort)
// Do not start a second interactive login shell merely to ask whether the engine is installed.
// The pane's own shell performs the same check before exec, and installs only when necessary.
// This removes ~1s of shell startup from the click-to-terminal critical path.
diff --git a/cli/src/engines/opencode/version.ts b/cli/src/engines/opencode/version.ts
index 5500598df..aae865e2e 100644
--- a/cli/src/engines/opencode/version.ts
+++ b/cli/src/engines/opencode/version.ts
@@ -10,8 +10,8 @@
* arrived that way, under a running daemon. The file's size and mtime key the cache, so the next
* launch after an update asks again and every other launch costs a `stat`.
*
- * Unknown (not installed, or an answer that is not a version) is `null`, and every caller treats it as
- * v1 — the behaviour it had before this module existed.
+ * Unknown (not installed, or an answer that is not a version) is `null`. Launch flags retain their
+ * v1 fallback; the hook installer waits for a confirmed v1 before writing the incompatible v1 plugin.
*/
import { execFileSync } from 'node:child_process'
diff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.ts
index 6397a0568..b91dc5059 100644
--- a/cli/src/lib/discoveryScripts.spec.ts
+++ b/cli/src/lib/discoveryScripts.spec.ts
@@ -1,14 +1,20 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { pathToFileURL } from 'url'
/** Pi and OpenCode register through generated source, so pin its process-owned wire contract directly. */
const dirs: string[] = []
-beforeEach(() => { vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'] }) })
+const version = vi.hoisted(() => ({ major: 1 as number | null }))
+vi.mock('../engines/opencode/version.js', () => ({ opencodeMajorVersion: () => version.major }))
+beforeEach(() => {
+ version.major = 1
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'] })
+})
afterEach(() => {
vi.useRealTimers()
+ vi.unstubAllEnvs()
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
vi.resetModules()
})
@@ -23,7 +29,7 @@ describe('generated discovery scripts', () => {
it('lets the Pi extension post from any terminal context without launcher metadata', async () => {
const piHome = scratch()
vi.resetModules()
- process.env.PI_HOME = piHome
+ vi.stubEnv('PI_HOME', piHome)
const { installPiExtension } = await import('./hooks.js')
installPiExtension(18473)
@@ -35,9 +41,9 @@ describe('generated discovery scripts', () => {
})
it('lets the OpenCode plugin post from any terminal context without launcher metadata', async () => {
- const pluginDir = scratch()
+ const pluginDir = join(scratch(), 'plugin')
vi.resetModules()
- process.env.OPENCODE_PLUGIN_DIR = pluginDir
+ vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)
const { installOpencodePlugin } = await import('./hooks.js')
installOpencodePlugin(18473)
@@ -51,22 +57,21 @@ describe('generated discovery scripts', () => {
// OpenCode 2.0 loads only `export default { id, setup }`, runs server plugins in one shared service
// (no TMUX_PANE there), and scans `plugins/<dir>/tui.js` for plugins that run IN the pane's TUI. So
- // 2.0 gets a TUI plugin beside the 1.x file — which is left exactly as it was — posting the same
- // session-start the 1.x plugin posts, for the session the pane shows.
- it('adds an OpenCode 2.0 TUI plugin that posts the session the pane shows, and leaves the 1.x file as it was', async () => {
+ // 2.0 gets a TUI plugin posting the same session-start the 1.x plugin posts, for the session the
+ // pane shows. The legacy file must be absent: 2.0 also discovers it, then refuses its old API.
+ it('installs only the compatible OpenCode 2 plugin, posting the session the pane shows', async () => {
const config = scratch()
const data = scratch()
const pluginDir = join(config, 'plugin')
vi.resetModules()
- process.env.OPENCODE_PLUGIN_DIR = pluginDir
- process.env.ADAPTER_DATA_DIR = data
+ version.major = 2
+ vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)
+ vi.stubEnv('ADAPTER_DATA_DIR', data)
writeFileSync(join(data, 'hook-credential'), 'tok-123\n')
const { installOpencodePlugin } = await import('./hooks.js')
installOpencodePlugin(18473)
- const v1 = readFileSync(join(pluginDir, 'launcher-register.js'), 'utf-8')
- expect(v1).toContain('export const MachineRegister')
- expect(v1).not.toContain('export default')
+ expect(existsSync(join(pluginDir, 'launcher-register.js'))).toBe(false)
const tuiPath = join(config, 'plugins', 'launcher-register', 'tui.js')
expect(existsSync(tuiPath)).toBe(true)
@@ -104,4 +109,54 @@ describe('generated discovery scripts', () => {
if (pane === undefined) delete process.env.TMUX_PANE; else process.env.TMUX_PANE = pane
}
})
+
+ it('migrates a running daemon from OpenCode 1 to 2 idempotently and can restore 1.x hooks', async () => {
+ const config = scratch()
+ const pluginDir = join(config, 'plugin')
+ vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)
+ const { installOpencodePlugin } = await import('./hooks.js')
+ const legacy = join(pluginDir, 'launcher-register.js')
+ const tui = join(config, 'plugins', 'launcher-register', 'tui.js')
+ installOpencodePlugin(18473)
+ const original = readFileSync(legacy, 'utf8')
+ expect(original).toContain('export const MachineRegister')
+ const before = statSync(tui).mtimeMs
+ version.major = 2
+ installOpencodePlugin(18473)
+ installOpencodePlugin(18473)
+ expect(existsSync(legacy)).toBe(false)
+ expect(statSync(tui).mtimeMs).toBe(before)
+ version.major = 1
+ installOpencodePlugin(18473)
+ expect(readFileSync(legacy, 'utf8')).toBe(original)
+ })
+
+ it.each([2, null])('preserves foreign files and model settings for OpenCode major %s', async (major) => {
+ const config = scratch()
+ const pluginDir = join(config, 'plugin')
+ mkdirSync(pluginDir)
+ const legacy = join(pluginDir, 'launcher-register.js')
+ const foreign = '// user plugin\nexport default { id: "user", setup() {} }\n'
+ writeFileSync(legacy, foreign)
+ const settings = join(config, 'opencode.json')
+ const settingsText = '{"model":"user/provider-model"}\n'
+ writeFileSync(settings, settingsText)
+ version.major = major
+ vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)
+ const { installOpencodePlugin } = await import('./hooks.js')
+ installOpencodePlugin(18473)
+ expect(readFileSync(legacy, 'utf8')).toBe(foreign)
+ expect(readFileSync(settings, 'utf8')).toBe(settingsText)
+ })
+
+ it('does not plant a v1 plugin before the pane installs OpenCode for the first time', async () => {
+ const config = scratch()
+ const pluginDir = join(config, 'plugin')
+ version.major = null
+ vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)
+ const { installOpencodePlugin } = await import('./hooks.js')
+ installOpencodePlugin(18473)
+ expect(existsSync(join(pluginDir, 'launcher-register.js'))).toBe(false)
+ expect(existsSync(join(config, 'plugins', 'launcher-register', 'tui.js'))).toBe(true)
+ })
})
diff --git a/cli/src/lib/engineBin.spec.ts b/cli/src/lib/engineBin.spec.ts
index 1ae7b17a1..2c6ab5428 100644
--- a/cli/src/lib/engineBin.spec.ts
+++ b/cli/src/lib/engineBin.spec.ts
@@ -2,7 +2,7 @@ import { spawn } from 'node:child_process'
import { copyFileSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import {
agentAliasOwner,
agentCommandOwnershipSnapshot,
@@ -15,13 +15,46 @@ import {
const originalPath = process.env.PATH
const tempDirs: string[] = []
+const overlayInodes = vi.hoisted(() => new Map<string, bigint>())
+
+vi.mock('node:fs', async (importOriginal) => {
+ const fs = await importOriginal<typeof import('node:fs')>()
+ return { ...fs, statSync: (path: Parameters<typeof fs.statSync>[0], options?: { bigint?: boolean }) => {
+ const value = fs.statSync(path, options)
+ const inode = overlayInodes.get(String(path))
+ if (value && inode !== undefined) Object.assign(value, { ino: options?.bigint ? inode : Number(BigInt.asUintN(64, inode)) })
+ return value
+ } }
+})
afterEach(() => {
process.env.PATH = originalPath
+ overlayInodes.clear()
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
describe('canonical engine CLI commands', () => {
+ it('keeps distinct live-USB executables distinct above the JS integer limit', () => {
+ const root = mkdtempSync(join(tmpdir(), 'engine-bin-live-inodes-'))
+ tempDirs.push(root)
+ const opencode = join(root, 'opencode'), shell = join(root, 'bash')
+ writeFileSync(opencode, 'agent', { mode: 0o755 })
+ writeFileSync(shell, 'shell', { mode: 0o755 })
+ // Recorded from the same preview 4 USB in BIOS and UEFI. Node's BigInt
+ // stat uses signed values; its Number stat rounds both to the same value.
+ overlayInodes.set(opencode, -9223372036854773743n)
+ overlayInodes.set(shell, -9223372036854774580n)
+ process.env.PATH = root
+ const snapshot = agentCommandOwnershipSnapshot()
+ const agent = executableFileIdentity(opencode)!
+ const bash = executableFileIdentity(shell)!
+ expect(agent.fileKey).not.toBe(bash.fileKey)
+ expect(agent.fileKey).toMatch(/:9223372036854777873$/)
+ expect(bash.fileKey).toMatch(/:9223372036854777036$/)
+ expect(snapshot.engineFileKeys?.get('opencode')?.has(agent.fileKey)).toBe(true)
+ expect(snapshot.engineFileKeys?.get('opencode')?.has(bash.fileKey)).toBe(false)
+ })
+
it('keeps the user-facing 14-engine command contract exact and ordered', () => {
expect(PROCESS_ENGINES.map((engine) => [engine, ENGINE_CLI_COMMANDS[engine]])).toEqual([
['claude', 'claude'],
diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.ts
index 4032f09d8..5e20f711d 100644
--- a/cli/src/lib/engineBin.ts
+++ b/cli/src/lib/engineBin.ts
@@ -161,13 +161,16 @@ export function executableFileIdentity(path: string): ExecutableFileIdentity | n
// Stat through the supplied path first. `/proc/<pid>/exe` keeps the running inode reachable even
// after an auto-updater replaces its pathname; realpath may then end in "(deleted)" and be
// unstatable despite the process image still being valid.
- const stat = statSync(path)
+ // OverlayFS (including a live USB) can assign 64-bit inode numbers above
+ // Number.MAX_SAFE_INTEGER. Rounded Numbers made unrelated executables
+ // share one owner, so a shell could be promoted to an installed agent.
+ const stat = statSync(path, { bigint: true })
if (!stat.isFile()) return null
let realPath: string
try { realPath = realpathSync(path) } catch {
try { realPath = readlinkSync(path) } catch { realPath = normalize(path) }
}
- return { path: normalize(path), realPath, fileKey: `${String(stat.dev)}:${String(stat.ino)}` }
+ return { path: normalize(path), realPath, fileKey: `${stat.dev}:${BigInt.asUintN(64, stat.ino)}` }
} catch {
return null
}
diff --git a/cli/src/lib/engineInstall.spec.ts b/cli/src/lib/engineInstall.spec.ts
index 7ee1686c9..5635db012 100644
--- a/cli/src/lib/engineInstall.spec.ts
+++ b/cli/src/lib/engineInstall.spec.ts
@@ -8,7 +8,7 @@ const OFFICIAL_COMMANDS = {
claude: 'npm install -g @anthropic-ai/claude-code',
codex: 'npm install -g @openai/codex',
cursor: 'curl https://cursor.com/install -fsS | bash',
- opencode: 'npm install -g opencode-ai',
+ opencode: 'curl -fsSL https://opencode.ai/install | bash',
pi: 'npm install -g --ignore-scripts @earendil-works/pi-coding-agent',
hermes: 'curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash',
commandcode: 'npm i -g command-code',
diff --git a/cli/src/lib/engineInstall.ts b/cli/src/lib/engineInstall.ts
index 8b13c72ed..4e8c65e94 100644
--- a/cli/src/lib/engineInstall.ts
+++ b/cli/src/lib/engineInstall.ts
@@ -54,7 +54,9 @@ export const ENGINE_INSTALL: Readonly<Record<ProcessEngine, EngineInstallRecipe>
executable: { names: ['cursor-agent'], homeRelativePaths: ['.local/bin/cursor-agent'] },
},
opencode: {
- command: 'npm install -g opencode-ai',
+ // The native installer downloads one matching binary. npm installs both the
+ // baseline and AVX2 Linux packages, doubling the installed footprint.
+ command: 'curl -fsSL https://opencode.ai/install | bash',
source: 'https://opencode.ai/docs',
executable: { names: ['opencode'], npmGlobal: true, homeRelativePaths: ['.opencode/bin/opencode'] },
},
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index 3397ef441..8cc80ae68 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -1,4 +1,4 @@
-import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { execFileSync } from 'node:child_process'
import { tmpdir } from 'node:os'
@@ -227,6 +227,15 @@ describe('buildEngineLaunchArgv', () => {
}
})
+ it('opens OS terminals directly at the shell prompt', () => {
+ vi.stubEnv('HARNESS_OS', '1')
+ try {
+ const argv = buildEngineLaunchArgv('terminal', { terminalHint: { machineName: 'programmer-os' } }, '/bin/sh')
+ const out = execFileSync('/bin/sh', ['-c', argv[2], 'harness-terminal', '', '/bin/sh', '-c', 'echo prompt']).toString()
+ expect(out).toBe('prompt\n')
+ } finally { vi.unstubAllEnvs() }
+ })
+
it('the banner names the machine, falls back to "this machine", and fits an 80-column pane unwrapped', () => {
expect(terminalHintLines(' ')).toContain(' Terminal on this machine')
for (const line of terminalHintLines('office-imac')) expect(line.length).toBeLessThanOrEqual(78)
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index a4eb242f9..b56a554b3 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -628,7 +628,7 @@ export function buildTerminalLaunchArgv(
const cwdPrelude = opts.cwd
? `if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; fi\n`
: ''
- const hintPrelude = opts.terminalHint
+ const hintPrelude = opts.terminalHint && process.env.HARNESS_OS !== '1'
? `printf '%s\\n' ${terminalHintLines(opts.terminalHint.machineName).map(shellSingleQuote).join(' ')}\n`
: ''
return [path, '-c', RAISE_OPEN_FILES_SH + clearEnvPrelude(opts.clearEnv) + cwdPrelude + hintPrelude + 'shift\nexec "$@"', 'harness-terminal', opts.cwd ?? '', path, ...loginArgs]
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index 146756464..fc5da6eab 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -5,7 +5,7 @@
* Changes to settings.json take effect on the NEXT claude session start.
*/
-import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from 'fs'
+import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync } from 'fs'
import { basename, join, dirname } from 'path'
import { homedir } from 'os'
import { fileURLToPath } from 'url'
@@ -13,6 +13,7 @@ import { cursorConfigDir, cursorDataDir } from '../engines/cursor/home.js'
import { env } from '../config/env.js'
import { VERSION } from '../version.js'
import { hermesConfigHomes } from '../engines/hermes/home.js'
+import { opencodeMajorVersion } from '../engines/opencode/version.js'
import { managedNodePath } from './nodeRuntime.js'
import { opencodeMemoryPluginSource } from './opencodeMemoryPlugin.js'
import { opencodeRecallPluginSource } from './opencodeRecallPlugin.js'
@@ -1137,11 +1138,26 @@ export function installAmpPlugin(port: number): void {
}
/**
- * Idempotently drop the OpenCode discovery plugin into ~/.config/opencode/plugin/ (1.x, as it always
- * was), and its 2.0 TUI form into ~/.config/opencode/plugins/launcher-register/ (1.x never looks there).
+ * OpenCode 2 still discovers the legacy plugin directory, but rejects its 1.x API. Keep the legacy
+ * file only for a confirmed 1.x binary. Remove only our generated file during migration, preserving
+ * unrelated plugins and user configuration. With no binary yet, prepare the TUI plugin without
+ * planting a legacy file that would fail when the pane installs current OpenCode.
*/
export function installOpencodePlugin(port: number): void {
- installForkPlugin('opencode', OPENCODE_PLUGIN_PATH, 'OpenCode', port)
+ if (opencodeMajorVersion() === 1) {
+ installForkPlugin('opencode', OPENCODE_PLUGIN_PATH, 'OpenCode', port)
+ } else {
+ try {
+ const source = readFileSync(OPENCODE_PLUGIN_PATH, 'utf8')
+ if (source.startsWith('// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n')
+ && source.includes('export const MachineRegister =')) {
+ unlinkSync(OPENCODE_PLUGIN_PATH)
+ console.log('[hooks] removed incompatible OpenCode 1 discovery plugin')
+ }
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') console.error('[hooks] failed to remove OpenCode 1 plugin:', err)
+ }
+ }
installPluginSource('opencode', OPENCODE_TUI_PLUGIN_PATH, 'OpenCode 2 TUI', opencodeTuiPluginSource(port))
}
diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.md
index b55370300..b92df84ac 100644
--- a/desktop/design/desktop-design-system.md
+++ b/desktop/design/desktop-design-system.md
@@ -4,6 +4,9 @@ The canonical system for everything around terminal panes. This supersedes
older BIOS, bracket-button and mixed desktop recipes. The user-approved
direction is the authority: refine one system, then use it everywhere.
+Product names, meanings, and action labels follow the
+[Naming System](../../docs/naming-system.md), shared across the OS, apps, and device.
+
## Character
A calm, precise Mac workspace. Content supplies the personality: an agent's
diff --git a/docs/naming-system.md b/docs/naming-system.md
new file mode 100644
index 000000000..8efb3d8b6
--- /dev/null
+++ b/docs/naming-system.md
@@ -0,0 +1,167 @@
+# Naming System
+
+The source of truth for names and meanings across Harness: the operating system,
+terminal, desktop, web, mobile, device, documentation, and product pages. These
+decisions were approved on October 3, 2026. Use this system when naming a feature,
+writing interface copy, or explaining how the products fit together.
+
+Harness is the software product. Autonomous is the company. Agents are the primary
+way to do work: conversation directs them; terminal output, diffs, and optional
+viewers make their work inspectable. Programmers are the first audience.
+
+This document defines the vocabulary. Component documentation and release evidence
+establish which capabilities are available. Visual presentation follows the
+applicable design system, including the [desktop Design System](../desktop/design/desktop-design-system.md).
+
+## Product names
+
+| Thing | Name | Usage |
+| --- | --- | --- |
+| Company | **Autonomous** | Autonomous builds Harness and the hardware. |
+| Software product | **Harness** | The shared name across its interfaces. |
+| Full Linux installation | **Harness** | Write “the Harness operating system” when the distinction matters. |
+| Terminal interface | **Harness** | “Open Harness in your terminal.” Its command is `hn`. |
+| Desktop, web, and mobile interfaces | **Harness** | Use descriptors such as “the Harness desktop app” or “Harness on your phone.” |
+| Compute hardware | **Autonomous Computer** | The physical computer. “Personal AI computer” can describe it. |
+| Optional companion controller | **Harness device** | The input and status device connected to the computer. |
+| Optional inference network | **Grid** | Routes model requests to the computers serving them. |
+| Open source project and repository | **OpenHarness** | Use for the source project and repository identity; the product interface says Harness. |
+
+Use **Harness** in prose. Wordmarks and ASCII artwork may use their established
+lettering. `hn` and `harness` are commands, not additional product brands.
+Keep vendor names intact: **Claude Code**, **Codex**, **OpenCode**, and **pi**.
+
+The roadmap can be explained in one sentence:
+
+> Use Harness on your own computer, or get an Autonomous Computer with Harness
+> preinstalled and an optional Harness device.
+
+Owning Autonomous hardware is optional. Describe the round and square devices as
+form factors until model names are chosen; a concept image does not establish that
+a variant or integration has shipped. The square device's two modes are **Harness**
+and **Browser**. Technical documentation may still call the terminal interface a TUI.
+
+## Work and interface terms
+
+| Term | Meaning | Example |
+| --- | --- | --- |
+| **Agent** | The agent software chosen, or the AI doing the work. | Choose Codex; the agent is running tests. |
+| **Model** | The model an agent uses. | Change the model while keeping the agent and project. |
+| **Harness** in product copy | The software product. | Open Harness. |
+| **A harness** in the workspace | A running agent session with its own conversation and working context. | Start three Codex harnesses. |
+| **A harness** in the Store | A reusable setup containing agent instructions, tools, and an optional viewer. | Install the Blender harness. |
+| **Tab** | A workspace group of harnesses. | Frontend and Backend tabs. |
+| **Pane** | A visible view of a harness, terminal, or viewer. | Split right; close pane. |
+| **Terminal** | A shell for entering commands. | New terminal. |
+| **Project** | The files and working context for the work, on a particular computer. | Choose the website project. |
+| **Task** | The work requested. | Add a search field. |
+| **Browser** | The optional browser for web content and visual review. | Open the browser. |
+| **Viewer** | A surface for inspecting or interacting with work. | The game viewer; the HTML preview. |
+| **This computer** | The local execution machine. | Run on This computer. |
+| **Store** | The catalog of reusable harnesses and viewers. | Install a harness from the Store. |
+| **Conversation** | An agent's conversation history, including histories started outside Harness. | Provider usage counts native conversations. |
+| **Recorded run** | A saved demonstration of a harness doing work. | Watch the recorded run in the Store. |
+
+Use lowercase *harness* and *tab* in ordinary sentences. The action and context
+distinguish the two uses of *harness*: install or update a package in the Store;
+start, pause, or stop a running harness in the workspace. Keep **agent** for choosing
+the agent software and describing the AI's actions. Preserve **New Harness** as the
+existing action name.
+
+A pane is a view, so closing a pane or tab closes views. **Stop Harness** ends the
+running harness. Adding harnesses to a tab groups them without a separate team
+setup. **Settings → Experimental → Tab collaboration** lets their agents consult
+peers; it is off by default. The word *tab* can also name the keyboard key or a
+browser tab; context distinguishes them.
+
+A project belongs to a computer; identical paths on different computers do not
+identify the same project. Use the actual project or computer name when that
+context matters. A plain terminal opens directly without an agent, project, or
+task form.
+
+## Action names
+
+| Intent | Label |
+| --- | --- |
+| Start a running harness | **New Harness** |
+| Create a workspace group | **New Tab** |
+| Open a shell | **New terminal** |
+| Manage a workspace group | **Rename Tab**, **Close Tab**, **Next Tab**, **Previous Tab** |
+| Manage a running harness | **Rename Harness**, **Pause Harness**, **Resume Harness**, **Restart Harness**, **Stop Harness** |
+| Author a reusable Store package | **Create Harness** |
+| Start the bundled agent from the OS welcome | **Start OpenCode** |
+| Set up wireless networking | **Connect to Wi-Fi** |
+
+Use the object's own name where possible: **Blender**, **Web Viewer**, or the
+person's project name. Keep task instructions in the conversation and technical
+configuration where it affects a decision.
+
+## Operating system copy
+
+| Surface | Wording |
+| --- | --- |
+| Boot and unlock branding | **Harness** |
+| Disk unlock prompt | **Enter your password** |
+| USB welcome primary action | **Install Harness** |
+| USB welcome secondary action | **Try without installing** |
+| Installer title | **Install Harness** |
+| Installer fields | **Disk**, **Encryption**, **Password**, **Repeat password** |
+| Installer action | **Install** |
+| Installation completion | **Harness is installed.** |
+| Completion actions | **Shut down**, **Back to Harness** |
+| Default account | `me` |
+| Default computer name | `harness` |
+| Default shell identity | `me@harness` |
+| Command equivalent of installation | `sudo harness install` |
+| OS page description | **An operating system built around agents.** |
+| Audience description | **Built for programmers first.** |
+
+Installation is directly accessible from the USB welcome. Trying Harness may
+require network setup; offline installation does not. An installed system and
+ordinary hn on macOS or another Linux distribution never show the USB installation
+actions. The `harness install` system command belongs to the OS integration.
+
+The terminal and optional browser are the OS's working surfaces. This does not
+replace the desktop app's design system or require every Harness interface to
+adopt the OS welcome screen.
+
+## Technical names and compatibility
+
+**DSH** means domain-specific harness in authoring documentation, code, and the
+package protocol. Users choose the harness by its name. Keep `harness dsh …`,
+package identifiers, manifests, and existing API names compatible.
+
+Internal names such as `Swarm`, `swarm.new`, `swarms`, `Agent`, `sessionId`, `tabId`,
+`DeskTab`, `channel`, and `--tab` are not renamed by this system. Authentication,
+encryption, tmux, native engine sessions, daemons, and model providers retain their
+technical meanings. Use those terms where they help explain or diagnose behavior.
+
+| Older visible wording | Canonical wording |
+| --- | --- |
+| Programmer OS | **Harness** |
+| programmer or programmer-live as a default identity | **me**, **harness**, or **me@harness**, according to the field |
+| hn or hn TUI as a product name | **Harness**; retain `hn` in command examples |
+| New Swarm or Untitled Tab as an automatic group name | **New Tab** |
+| Swarm as a workspace group | **Tab** |
+| TUI as the square device's mode label | **Harness** |
+| DSH as a user-facing package name | The harness's actual name |
+
+Search can accept older terms as aliases. Preserve explicit custom names, stored
+keys, existing commands, historical evidence, and published artifact URLs. Update
+current visible copy and examples without breaking those references.
+
+## Maintaining the system
+
+Define a new term here before introducing it across interfaces. Give it one clear
+role, an example, and its relationship to the existing terms. Update affected
+labels, documentation, accessibility text, shortcuts, and tests together.
+
+Product claims must describe the tested configuration. In particular, say local
+models work out of the box only after the drivers, inference runtime, model
+provisioning, and agent connection have been verified for that configuration.
+See the [OS coverage](../os/README.md) for current evidence and limitations.
+
+The hardware context lives in [Autonomous Computer](https://github.com/autonomous-ai/autonomous-computer),
+the [Harness device guide](../devices/harness-device/firmware/README.md), and
+[Grid](https://github.com/autonomous-ai/autonomous-grid). These names connect the
+roadmap; they do not make every component a required dependency.
diff --git a/docs/terminology.md b/docs/terminology.md
index 7eea166f6..3ae486872 100644
--- a/docs/terminology.md
+++ b/docs/terminology.md
@@ -1,43 +1,8 @@
# Product terminology
-Use these names consistently in desktop, web, phone, menus, shortcuts, accessibility
-labels, notifications, errors, onboarding, and user documentation.
+The canonical vocabulary is the [Naming System](naming-system.md). It covers
+product and hardware names, agents and harnesses, tabs and panes, action labels,
+OS copy, and compatibility with existing technical identifiers.
-| Term | Meaning | Example |
-| --- | --- | --- |
-| Agent | The coding agent you choose, or the AI doing the work | Codex, Claude Code, Grok |
-| Harness | A reusable agent setup in the Store, or a running agent session in the workspace with its own conversation and working context | Install the Blender harness; start three Codex harnesses |
-| Tab | A workspace tab that groups harnesses | Frontend, Backend |
-| Pane | A view of a harness or its viewer | Split right; close pane |
-
-Use *harness* in both contexts. The screen and action make the meaning clear:
-install or update a harness in the Store; start, pause, or stop a harness in the
-workspace.
-
-**New Harness** starts a harness. **New Tab** opens a tab. Add harnesses to a
-tab to include them; no separate team setup is needed. With **Settings →
-Experimental → Tab collaboration** enabled, agents can consult peers in the
-same tab. Collaboration is off by default. Closing a pane or tab closes its
-views; **Stop Harness** ends the running harness.
-
-Use **Rename Tab**, **Close Tab**, **Next Tab**, and **Previous Tab** for
-group actions, and **Rename Harness**, **Pause Harness**, **Resume Harness**, and
-**Restart Harness** for a running session. Use **Create Harness** for authoring
-a reusable package in the Store. Body copy uses lowercase *harness* and *tab*;
-**Harness** remains the product name.
-
-Use *agent* when choosing Codex or Claude or describing the AI's actions. Use
-*harness* for Store packages and for running work. Provider usage reports count
-native **conversations**, which can also be started outside
-Harness. A recorded Store demonstration is a **recorded run**.
-
-Use **Tab** for the workspace group in all visible copy for now. The word also
-names the keyboard key, browser tabs, and section tabs. Authentication,
-encryption, tmux, and native engine sessions retain their technical meanings.
-
-These are product names, not a protocol migration. Existing command IDs, API
-fields, CLI flags, manifests, and stored keys (including `Swarm`, `swarm.new`,
-`swarms`, `Agent`, `sessionId`, `tabId`, `DeskTab`, `channel`, and `--tab`) remain
-compatible. Search may accept
-older wording as an alias. Saved automatic names such as `New Swarm` and
-`Untitled Tab` display as **New Tab**; explicit custom names stay unchanged.
+This path remains available for existing links. Maintain naming decisions in the
+Naming System so there is one source of truth.
diff --git a/os/.gitignore b/os/.gitignore
new file mode 100644
index 000000000..2fc9e3b53
--- /dev/null
+++ b/os/.gitignore
@@ -0,0 +1,6 @@
+work/
+dist/
+test-results/
+__pycache__/
+*.pyc
+release-input/
diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.md
new file mode 100644
index 000000000..54b353f50
--- /dev/null
+++ b/os/DEVELOPMENT.md
@@ -0,0 +1,181 @@
+# Developing and testing Harness
+
+Use a persistent machine for daily work and a disposable VM for installation and
+boot changes. Reflashing is a release/install test, not the intended way to try
+every interface fix. Keep the development tools on the build/test host; the
+installed OS keeps the same minimal interface.
+
+This plan was recorded on October 3, 2026. Preview 4 and its optional small-package
+update are published. Native update/rollback acceptance passed; remote-launcher
+argument tests passed but remote display/SSH interaction is still unverified.
+
+## The feedback loop
+
+| Work being tested | Best environment | What it proves |
+| --- | --- | --- |
+| Agent chooser, panes, shortcuts, terminal rendering | Native Harness on the developer's Mac plus Linux integration tests | Shared interface behavior; not the OS boot/install path |
+| OS session, first use, installer, encryption, update/recovery | Native x86 Linux VM with KVM, controlled from the Mac | Repeatable PC-image behavior with actual Linux userspace |
+| Wi-Fi, brightness, keyboard layout, battery, suspend, physical boot | Dedicated ThinkPad, then each supported Mac model | The real daily-use experience and hardware behavior |
+| Future arm64 userspace and package compatibility | Accelerated ARM Linux VM on Apple Silicon | ARM application/session behavior; not Apple boot or drivers |
+| Apple boot, internal storage, GPU, input and power management | Physical Mac with the matching hardware stack | Mac OS support for that exact model |
+
+For the current user setup, install preview 4 on the ThinkPad once and use it for
+normal programming. Run installer experiments on the server VM. Record an issue
+with the exact keys/action, expected result, actual result and a screenshot or
+error text. Keep the image version and hardware model with the report.
+
+The target iteration is: reproduce in the VM, fix and run affected checks, deploy
+a versioned development update to the dedicated test installation, then have the
+user repeat the action. Restart only the changed component where its lifecycle
+allows it. Kernel, initramfs and boot changes require a reboot. Periodically test
+a clean USB install to verify that upgrades have not hidden an installation bug.
+
+## What is working now
+
+- The `Harness OS` workflow builds the x86-64 ISO and runs actual BIOS/plain and
+ UEFI/encrypted install, boot, wrong-password retry, update and recovery checks.
+ It retains screenshots, boot-stage timestamps, logs and source/image identity.
+- `image_run_id` tests an existing image without rebuilding it. `memory_mib=1024`
+ exercises a constrained machine; `memory_mib=4096` and `live_transport=usb`
+ exercise automatic copy-to-RAM. `workloads=true` or `dsh=true` runs the relevant
+ real-agent exercises. See the [measured evidence](README.md#real-programmer-exercises).
+- `python3 os/tools/run-vm.py --iso PATH` creates a persistent virtual disk and
+ opens the installer. `--installed` subsequently boots that disk without the ISO.
+ `--directory PATH` keeps independent test machines separate.
+- OpenSSH is installed. An SSH service and keys must be deliberately configured
+ for a dedicated test machine before remote deployment; this plan does not
+ enable a remote service or publish credentials.
+
+The current launcher selects KVM on an x86 Linux host with accessible `/dev/kvm`,
+HVF on an Intel Mac, and TCG emulation otherwise. This M2 Max Mac therefore
+emulates the present x86 image. Earlier emulation checks rendered a browser
+project but later reboot checks failed with soft-lockups. Use the native x86 CI
+results for current performance measurements.
+[QEMU documents these acceleration options](https://www.qemu.org/docs/master/system/introduction.html).
+
+## Small development updates
+
+`tools/build-package.py` assembles the same `harness-os` package used by the ISO.
+On a clean x86 Linux checkout, build a bundle with:
+
+```sh
+make -C os runtime
+python3 os/tools/build-package.py --runtime os/work/runtime --output os/work/my-update --development
+```
+
+The bundle identifies the source commit, architecture, required base image and
+every runtime file. It includes a package, manifest, SHA-256 checksums and a
+standalone bootstrap for preview 4. This is an explicit development installation
+from a trusted build, not an automatic public update channel. Checksums detect
+corruption; they do not authenticate an unknown publisher.
+
+The first [verified development bundle](https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.4/harness-update-preview.4-42c22cece-x86_64.zip)
+is 7.4 MB and targets installed preview 4. Its terminal and CLI binaries match the
+ISO byte for byte; it establishes the update path for future interface fixes.
+Copy the complete extracted bundle to a dedicated installed test machine. The
+bootstrap command is:
+
+```sh
+cd /path/to/bundle
+sha256sum -c SHA256SUMS
+sudo python3 apply-update.py apply "$PWD"
+```
+
+Subsequent bundles can use `sudo harness upgrade /path/to/bundle`. Roll back with
+`sudo harness rollback`, or with `sudo python3 apply-update.py rollback` from the
+retained bootstrap if the installed launcher is unavailable. Use the same
+bootstrap's `status` command to inspect source and transaction identity.
+
+The updater verifies a private copy before changing the installation, makes a
+Btrfs root/boot checkpoint, and retains a package of the previous owned files.
+Pacman performs the actual upgrade and rollback, preserving package ownership
+and dependency checks. Home directories and projects are outside the package.
+An interrupted update retains its receipt and recovery point and requires rollback
+before another runtime update. If the installed system cannot run, use the live
+USB's existing checkpoint recovery. There is no background updater, service
+restart, network requirement or automatic reboot. Reboot when ready to use the
+new session; boot/kernel changes still need image-specific validation.
+
+The workflow input `development_update=true` with `image_run_id=37119543543`
+builds the candidate and tests it against the published preview 4 image. Required
+acceptance covers truncated downloads, a real failed pacman transaction, apply,
+rollback, package identity, project preservation, the same terminal process
+through daemon/screen restarts, and an encrypted reboot with keyboard input.
+All 65 portable checks and workflow lint passed. [Native acceptance on source
+42c22cece](https://github.com/autonomous-ai/openharness/actions/runs/37124241039)
+passed every case above. In that 2 GiB encrypted VM, apply took 3.089 seconds and
+rollback took 1.083 seconds. Actual post-update keyboard and masked-unlock captures
+were reviewed. Public package/guide/evidence downloads were fully SHA-256 and size
+verified. Physical ThinkPad update behavior and timings remain unverified.
+
+Shared hn changes in preview 4 are still on the OS branch. Ordinary Mac/Linux hn
+keeps its usual home and detach/quit behavior; live USB and installed OS welcome
+actions require explicit OS mode. Opening Terminal directly is a shared chooser
+change, explicitly approved for all platforms. It needs normal TUI release review
+along with the shared agent-discovery
+and OpenCode compatibility fixes; publishing the ISO did not release these through
+the general TUI channel. The small updater adds no changes to `tui/` or `cli/`.
+
+## Optional remote VM controls
+
+`run-vm.py --vnc-port 5901 --ssh-port 2222 --remote-host me@build-host
+--require-acceleration` binds both optional listeners to localhost and prints an
+SSH tunnel command. The display port implies headless QEMU; guest SSH still needs
+deliberate service/key setup. Without these flags no TCP listener is added. The
+acceleration flag refuses software emulation instead of silently using it.
+Argument and binding tests pass; real remote display/SSH interaction is not yet
+validated. These host tools add no software to the installed OS.
+
+Stopped-VM snapshot/restore remains future work. Never snapshot a running disk
+by blindly copying its file.
+
+`hn-os update` currently upgrades Arch packages and keeps a recovery checkpoint;
+it does **not** update the pinned Harness runtime. Preview 4's ISO does not contain
+the small updater; install its separately validated development bundle to add it.
+
+## Mac support targets
+
+Intel Macs and Apple Silicon are both intended OS targets. They share the Harness
+interface and behavior, but need separate platform work. None is claimed as a
+validated Harness OS hardware target by preview 4.
+
+| Target | Approach | Current Harness OS status |
+| --- | --- | --- |
+| Older Intel Mac, 64-bit CPU and EFI, without T2 | Reuse x86-64 userspace and validate firmware, graphics, Wi-Fi, input, sleep and installation per model | First physical Mac target; no tested model yet |
+| Intel Mac with T2 | Add the T2 kernel/driver and firmware integration; validate built-in input at encrypted unlock | Separate hardware profile, not covered by generic x86 VM success |
+| Apple Silicon | Build arm64 userspace and integrate the Asahi boot/kernel/graphics/firmware stack | Port required; current x86-64 ISO cannot install natively |
+| Native Harness app/TUI on macOS | Existing arm64 and x64 app/runtime releases | Separate from installing the Linux OS |
+
+The initial Intel scope excludes 32-bit-only CPUs/EFI. T2 machines need specific
+kernel support for built-in input and other hardware; their firmware and install
+preparation differs from an ordinary PC. The maintained references are the
+[t2linux Arch install guide](https://wiki.t2linux.org/distributions/arch/installation/),
+[kernel/input setup](https://wiki.t2linux.org/guides/postinstall/) and
+[pre-install guide](https://wiki.t2linux.org/guides/preinstall/).
+
+For Apple Silicon, evaluate Fedora Asahi Remix Minimal as the first hardware
+bring-up base: it provides a maintained minimal image and the platform packages.
+This is a port candidate, not a shipped change to the Arch PC image. Retain the
+same labwc/foot/Harness/browser experience, while treating distribution-specific
+packaging, updates and recovery as separate integration work.
+[Fedora Asahi Remix](https://asahilinux.org/fedora/) offers Minimal and Server images.
+
+Start with explicitly supported M1/M2 models. The current M2 Max MacBook Pro is a
+candidate: Asahi's detailed table lists its display, keyboard, trackpad, Wi-Fi,
+GPU and sleep support. That is upstream evidence, not a passed Harness test.
+Feature readiness varies by model and generation; recheck the
+[M2 table](https://asahilinux.org/docs/platform/feature-support/m2/) and
+[other device tables](https://asahilinux.org/docs/platform/feature-support/overview/)
+before expanding the target list.
+
+Apple Silicon installation cannot reuse the PC whole-disk USB flow. Asahi starts
+installation from internal macOS and needs internal boot provisioning. Preserve
+macOS/recovery and use an Apple-aware partition/install path. An ARM VM does not
+test that path or the Apple-specific drivers.
+[Asahi installation requirements](https://asahilinux.org/docs/project/faq/).
+
+For each hardware target, retain the model, CPU/GPU, firmware and OS versions,
+install method, encryption status, Wi-Fi/input/display results, suspend/resume,
+and measured boot/idle behavior. Validate a real agent task and browser preview,
+then update and recover without losing the project. A target becomes supported
+only when that evidence exists.
diff --git a/os/INSTALL.md b/os/INSTALL.md
new file mode 100644
index 000000000..f67498ba0
--- /dev/null
+++ b/os/INSTALL.md
@@ -0,0 +1,166 @@
+# Install Harness on a ThinkPad
+
+These instructions are for **0.1.0-preview.4**, using a Mac to prepare the USB.
+The USB starts a live session. Installation begins only when you choose **Install**
+in the installer; it erases the entire selected disk.
+
+## 1. Prepare
+
+- An x86-64 Intel or AMD ThinkPad. A 32-bit-only CPU is not supported.
+- A USB stick of at least 4 GB. Flashing replaces its contents.
+- An internal disk of at least 12 GiB, with important files backed up elsewhere.
+- AC power. Installation works offline; trying a cloud agent needs a connection.
+
+Start with 2 GiB RAM or more. This preview passed installation, reboot, recovery
+and a first OpenCode conversation in 1 GiB VMs. Allow more memory for browser
+tabs, concurrent agents and local models.
+Preview 2 was installed and booted on a physical ThinkPad. Wi-Fi, suspend and GPU
+compute still need testing on the actual hardware.
+
+## 2. Download and verify on the Mac
+
+From the [preview 4 release](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.4),
+download both files into the same folder:
+
+- `harness-0.1.0-preview.4-x86_64.iso`
+- `harness-0.1.0-preview.4-x86_64.iso.sha256`
+
+If they are in Downloads, open Terminal and run:
+
+```sh
+cd ~/Downloads
+shasum -a 256 -c harness-0.1.0-preview.4-x86_64.iso.sha256
+```
+
+The result must say `harness-0.1.0-preview.4-x86_64.iso: OK`.
+If it does not, download the files again before flashing.
+
+## 3. Flash the USB
+
+1. Open [balenaEtcher](https://etcher.balena.io/).
+2. Choose **Flash from file** and select the ISO.
+3. Choose **Select target** and select your USB by its name and capacity.
+4. Choose **Flash**. If macOS asks for administrator authentication, enter your
+ Mac password in its dialog. Let Etcher finish validation.
+5. Eject the USB.
+
+Use an image writer; copying the ISO onto a formatted USB does not create bootable
+installation media. If macOS calls the flashed disk unreadable, choose **Ignore**
+or **Eject**. Do not initialize it.
+
+## 4. Boot the ThinkPad from USB
+
+1. Shut down the ThinkPad and insert the USB.
+2. Power on and tap **F12** at the Lenovo logo. Depending on the model, use
+ **Fn+F12**, or **Enter** first and then **F12**.
+3. Select the USB. Prefer its UEFI entry when available; legacy BIOS also works.
+4. If firmware rejects the image, enter setup with **F1** and disable **Secure
+ Boot**. This preview is unsigned. Leave TPM enabled.
+5. Choose the default **Harness** boot entry.
+
+The exact menu wording varies by model. See Lenovo's
+[boot-menu instructions](https://docs.lenovocdrt.com/ref/bios/startup_menu/).
+If the USB is absent, try another USB port and check that USB boot is enabled.
+
+The welcome screen offers **Enter — Install Harness** and **T — Try without
+installing**. No account or password is needed to use the live session. Work in
+the USB session is temporary and is not copied during installation.
+
+## 5. Install
+
+Press **Enter** on the welcome screen. You do not need to open a terminal or type
+a command. The form has four fields:
+
+1. **Disk:** press Enter, choose the internal disk by its model and capacity, and
+ press Enter again. The live USB is excluded from the choices.
+2. **Encryption:** enabled initially. Use Space to change it if needed.
+3. **Password:** enter the password for your new system.
+4. **Repeat password:** enter it again.
+
+Use Tab or the arrow keys to move between fields. This preview uses a **US keyboard
+layout**, including at disk unlock. Passwords cannot be empty; there is no minimum
+length restriction.
+
+Check the selected disk, then choose **Install** and press Enter. **This immediately
+erases that disk. There is no second confirmation screen.** Choosing a disk alone
+does not start installation. Esc leaves the picker or cancels the main form.
+
+The account and computer name are set to **`me@harness`**. Installation works offline.
+When **Harness is installed.** appears, choose **Shut down**. Once the ThinkPad is
+off, remove the USB and power it on.
+
+While trying the live system, **Ctrl+B**, then **I** opens the same installer.
+The equivalent terminal command is `sudo harness install`.
+
+## 6. First boot
+
+With encryption enabled, the Harness logo appears with **Enter your password**.
+Enter the installation password. Harness then opens without another account
+setup or login prompt. With encryption disabled, log in as **`me`** using that
+password.
+
+The password initially protects both the account and, when enabled, the encrypted
+disk. Changing the account password later does not change the disk password.
+There is no cloud account that resets the disk password.
+
+On the empty home screen, press **Enter** to start OpenCode. If there is no network
+connection, the keyboard network picker opens first. Select your Wi-Fi network
+and enter its password there. **Ctrl+B**, then **W** opens network setup from any
+pane. Ethernet connects automatically when available.
+
+OpenCode is already installed and uses its upstream defaults. Available models
+may change. Other agents install when selected and follow their own account and
+model setup. A Linux account does not sign you into an agent provider.
+
+## 7. Use it
+
+**Super** means the Windows-logo key on a typical ThinkPad. For a Ctrl+B shortcut,
+press Ctrl+B, release both keys, then press the indicated letter. Capital letters
+below mean **Shift + letter**.
+
+| Keys or command | Action |
+| --- | --- |
+| Ctrl+B, then N | New Harness: choose an agent |
+| Ctrl+B, then T | New terminal: open a shell directly |
+| Ctrl+B, then W | Connect to Wi-Fi |
+| Super+B | Open/focus Chromium, or return to Harness |
+| Super+Enter | Focus Harness |
+| Super+L | Lock; unlock with the account password |
+| `hn-browser http://localhost:3000` | Open a local project in the browser |
+| `sudo systemctl poweroff` | Shut down |
+
+Claude Code, Codex, OpenCode and pi each run in their own pane. Let the agent
+install the tools the project needs. Save work under `~/Projects`.
+
+## 8. First manual test
+
+1. Boot with the USB removed. Confirm disk unlock and the Harness home screen.
+2. Connect Wi-Fi, open a terminal, type a command, and exit with Ctrl+D.
+3. Start OpenCode and ask it to build a small website in `~/Projects/hello`, run
+ its server, and give you the address. Open it with `hn-browser ADDRESS`.
+4. Ask an agent to build and test a command-line program, installing tools as needed.
+5. Switch between Harness and the browser. Lock and unlock the computer.
+6. Reboot. Confirm that the files remain and Harness opens again.
+7. Try brightness keys, lid-close/suspend and resume. Report failures with the
+ ThinkPad model; these need physical testing.
+
+Measure installation from pressing Install to the completion screen, separately
+from flashing and filling in the form. For encrypted boot, record the time to the
+unlock screen and the time from submitting the password to Harness separately.
+
+If something fails, keep the exact error and ThinkPad model. `hn-os status` and
+`hn-os measure` provide system information. Keep passwords and agent tokens private.
+The [OS README](https://github.com/autonomous-ai/openharness/blob/os/boot-to-hn/os/README.md#updates-and-recovery) describes updates and recovery.
+
+## Older USB images
+
+Preview 2 may report `Live system payload is missing` after copying the image into
+RAM. If `/run/archiso/copytoram/airootfs.sfs` exists, its workaround is:
+
+```sh
+sudo hn-os install --source /run/archiso/copytoram/airootfs.sfs
+```
+
+Preview 2 can also list the boot USB as a target in RAM mode; choose the internal
+disk carefully. Preview 3 and later detect both payload locations and exclude the
+boot USB. A working installed system does not need reinstalling solely for that fix.
diff --git a/os/Makefile b/os/Makefile
new file mode 100644
index 000000000..d1c180585
--- /dev/null
+++ b/os/Makefile
@@ -0,0 +1,10 @@
+.PHONY: check runtime build vm
+check:
+ python3 -m unittest discover -s tests -p 'test_*.py' -v
+ python3 tools/check.py
+runtime:
+ bash tools/build-runtime.sh
+build:
+ sudo bash build.sh
+vm:
+ python3 tests/vm.py --iso $(ISO) --firmware $(or $(FIRMWARE),bios)
diff --git a/os/README.md b/os/README.md
new file mode 100644
index 000000000..54e82dd9d
--- /dev/null
+++ b/os/README.md
@@ -0,0 +1,282 @@
+# Harness
+
+An operating system built around agents. Boot into `hn`, describe the work,
+and let an agent use the tools it needs. Review its diffs, tests and output in
+the terminal; open the browser when the work needs a visual surface.
+
+Programmers are the first audience. Claude Code, Codex, OpenCode and pi are the
+primary interface. Compilers, databases and other software are installed when
+a task needs them. The product is Harness; “programmer OS” describes its initial
+audience, not its name.
+
+Product names and interface copy follow the [Naming System](../docs/naming-system.md).
+
+**Preview 4:** the USB welcome offers **Install Harness** or **Try without installing**.
+Install works offline. Try opens Wi-Fi setup when needed, then bundled OpenCode
+with its upstream default settings. The installer has four fields and one Install
+action; encrypted boot shows the Harness wordmark and a masked password prompt.
+Both the live and installed system use `me@harness`.
+
+[Download preview 4](https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.4)
+· [Mac → USB → ThinkPad installation guide](INSTALL.md)
+· [Standalone HTML/CSS landing page](site/README.md)
+· [Development feedback loop and Mac support targets](DEVELOPMENT.md)
+
+The exact image passed BIOS/plain and UEFI/encrypted USB installation, boot,
+update retry and recovery at 1 GiB and 4 GiB RAM. First-use model conversations,
+four programmer projects and three DSH exercises passed the checks described below.
+The release includes the matching installation guide and validation evidence.
+
+The user confirmed preview 2 installation and boot from a physical ThinkPad's
+internal disk with the USB removed. Its first-use feedback informed this revision.
+Preview 4 still needs physical Wi-Fi, suspend and NVIDIA testing. A working older
+installation does not need reinstalling solely for the USB payload-location fix.
+
+## Design
+
+- Arch Linux, glibc, systemd and the LTS kernel. User space is rolling; LTS here
+ describes the kernel, not the distribution. Builds use a complete dated Arch
+ repository snapshot and record the installed package inventory.
+- labwc supplies Wayland, focus, input and display management. No panel, launcher,
+ wallpaper process, desktop icons, or notification daemon.
+- One fullscreen foot window displays the existing Rust `hn`. Agent/runtime
+ processes are supervised separately from that window. The image does not fork
+ foot or add a second graphical Harness client.
+ If graphics initialization fails, the login session falls back to hn on the
+ Linux console so drivers can be repaired without a working compositor.
+- Chromium is installed but does not start at boot. `Super+B` opens/focuses it or
+ returns to hn. `Super+Enter` focuses hn; `Alt+Tab` switches available windows.
+ Browser sandboxing and hardware acceleration remain enabled.
+- `Ctrl+B`, then `N` opens the agent picker; `Ctrl+B`, then `T` opens a terminal directly. The normal session
+ has no interactive parent shell to exit into. Shells remain available in hn panes. This is
+ an interface policy, not confinement against someone with shell/admin access.
+- NetworkManager, fonts, clipboard, audio, locking, firmware and zram provide
+ the support needed by actual development machines. OpenCode is bundled. Compilers, IDEs, model weights, CUDA, containers and
+ databases are installed when needed. Python and Node support the OS and Harness runtime.
+- Btrfs root, separate home and snapshot subvolumes, BIOS and UEFI boot, and
+ optional LUKS2 encryption (default on). The installer extracts its immutable
+ payload locally instead of downloading and installing each package again.
+
+The full installation owns the hardware, first boot, authentication, runtime,
+updates and recovery. These are completion gates, not optional follow-up work.
+
+## Build
+
+The GitHub **Harness OS** workflow builds on an isolated x86 Linux runner.
+Local equivalent on an x86 Arch build host:
+
+```sh
+sudo pacman -Syu archiso python git rustup musl nodejs-lts-jod npm
+rustup default stable
+rustup target add x86_64-unknown-linux-musl
+make -C os check
+make -C os runtime
+make -C os build
+```
+
+Use a fresh `HARNESS_OS_BUILD_DIR` for every build. Outputs are in `os/dist`:
+the hybrid USB ISO, its SHA-256 checksum, the package inventory, and a manifest
+with the clean source commit, runtime toolchains and hashes. Commit source changes
+before building; published client binaries do not contain the OS session mode.
+The build independently reads the ISO's SquashFS payload and compares its runtime,
+kernel, configuration and package inventory with the source. `inspection.json`
+records that check; machine validation is still required afterward.
+There is no publication to
+the normal Harness CLI/TUI update channels.
+
+## Try and install
+
+To experiment with the PC image in a Mac window, install QEMU with
+`brew install qemu`, download the ISO and its `manifest.json` into `os/dist/`,
+then run from the repository root:
+
+```sh
+python3 os/tools/run-vm.py
+```
+
+The VM has 2 GiB RAM and its own sparse 24 GiB virtual disk in
+`os/work/interactive-vm/`. That disk consumes only the space actually written.
+Budget 6–8 GB total for the ISO, QEMU and an initial installation; agent downloads
+and projects add more. Run the same installer described below, selecting
+`/dev/vda`. After shutdown, use `python3 os/tools/run-vm.py --installed` to boot
+from the virtual disk. The left Command key supplies the Super shortcuts.
+Apple Silicon uses x86 emulation: this tests the PC image's behavior, while boot
+and application timings need separate native x86 measurements.
+Earlier Mac checks rendered a project in Chromium, but subsequent background
+reboots missed readiness deadlines with guest soft-lockup reports. Preview 4 has
+not been validated interactively on this Mac. Use the native x86 VM evidence for
+measured performance; Apple Silicon emulation is not yet a reliable performance
+or full-experience demonstration.
+
+Write the **whole ISO** to a USB stick using an image writer such as Etcher, then
+boot an x86-64 PC with Secure Boot disabled. TPM can remain enabled. A 32-bit-only
+ThinkPad cannot boot this image. The [installation guide](INSTALL.md) covers the
+Mac download, checksum, flashing and ThinkPad boot menu in full.
+
+On the USB welcome, press **Enter** to install or **T** to try Harness. Installation
+needs no network or terminal command. Trying a cloud agent requires a connection;
+network setup opens when needed. Work in the live USB session is temporary and is
+not copied during installation.
+
+The installer uses `me@harness`. Choose **Disk**, leave **Encryption** enabled or
+change it, then enter **Password** and **Repeat password**. **Install immediately
+erases the selected disk**, as disclosed in the form. There is no second
+confirmation screen. The live USB and mounted disks are excluded. Selecting a
+disk alone does not write to it. Passwords must be nonempty; this preview uses a
+US keyboard layout, including at disk unlock.
+
+Completion stays visible until **Shut down** or **Back to Harness** is chosen.
+Remove the USB after shutdown and boot the internal disk. An encrypted install
+shows the Harness logo and **Enter your password**, then enters hn. An unencrypted
+install requires login as `me`. The password initially protects both the account
+and, when enabled, the disk. There is no first-boot account wizard.
+
+The command equivalent is `sudo harness install`. Advanced overrides remain:
+`--no-encryption`, `--username NAME`, and `--hostname NAME`. With an unattended
+`--config` file, set `username`, `hostname` and `encrypt` in that file instead.
+Ordinary hn on macOS or another Linux distribution does not expose OS installation.
+
+On the installed system's empty home, Enter starts OpenCode. `Ctrl+B`, then `W`
+opens network setup; `Ctrl+B`, then `T` opens a shell directly. Capital letters
+in these prefix shortcuts mean Shift + letter. `Super+L` locks the session.
+Recovery remains available through another console or the USB; the owner retains
+normal Linux administrator control.
+
+## Updates and recovery
+
+`sudo hn-os update` saves a checkpoint and upgrades the whole system to yesterday's
+complete Arch repository snapshot. Use `--snapshot YYYY/MM/DD` to choose a complete
+snapshot at or after the current one. Packages remain signed by Arch; the OS does not
+run an updater or download anything on a schedule.
+The bundled hn and OS integration are pinned to this preview's source build;
+this command updates Arch packages, not the bundled Harness runtime.
+
+An optional [7.4 MB development bundle](https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.4/harness-update-preview.4-42c22cece-x86_64.zip)
+adds small Harness package updates and rollback to an installed preview 4 system.
+It includes its bootstrap, checksums, instructions and native VM evidence; see
+[development updates](DEVELOPMENT.md#small-development-updates). It is separate
+from the ISO and from ordinary hn on Mac/Linux. The first bundle's terminal and
+CLI binaries match the ISO; future interface fixes can use this update path.
+
+A failed or interrupted update blocks ordinary package transactions until
+`sudo hn-os update` completes successfully. Fix the reported
+cause and retry; it keeps the original recovery checkpoint, including across
+reboots. If the installed system cannot complete the update, recover that
+checkpoint from the live USB. This guard applies to updates run through `hn-os`;
+custom package-manager workflows remain the owner's responsibility.
+
+Every package transaction also saves a checkpoint. It contains Btrfs root and a
+checksummed copy of `/boot`, so the package database, kernel, modules and initramfs
+can be recovered together. Home and projects stay outside root rollback.
+Checkpoints consume disk space and are retained until explicitly removed.
+
+To recover, boot the USB, inspect `lsblk -f`, and run `sudo hn-os recover ROOT_DEVICE`
+to list checkpoints. For an encrypted disk, first unlock it with
+`sudo cryptsetup open ROOT_PARTITION hn-recovery`, then use
+`/dev/mapper/hn-recovery` as `ROOT_DEVICE`. Run
+`sudo hn-os recover ROOT_DEVICE CHECKPOINT` to restore. Recovery requires the
+installed root and boot filesystems to be unmounted. The previous root is retained.
+This initial recovery path requires the USB; it is not an automatic boot fallback.
+
+## NVIDIA and local AI
+
+The small base image carries Intel/AMD graphics and Linux firmware. NVIDIA's
+compute driver is installed on demand with
+`sudo pacman -S --needed nvidia-open-lts nvidia-utils`, followed by
+`sudo mkinitcpio -P` and a reboot. These are the matching packages for the included
+LTS kernel and supported Turing-or-newer GPUs, including the intended RTX targets.
+See [Arch's package](https://archlinux.org/packages/extra/x86_64/nvidia-open-lts/)
+and [NVIDIA's supported GPUs](https://github.com/NVIDIA/open-gpu-kernel-modules).
+No NVIDIA hardware validation has been performed yet. Verify `nvidia-smi` and the
+actual AI workload on each physical machine before treating it as supported.
+
+OpenCode is bundled; other agent executables are installed through hn's existing
+engine install recipes when selected. Accounts, API credentials and model downloads are supplied by the
+owner. System guidance for agents lives at `/usr/share/harness-os/AGENTS.md`.
+
+## Validation plan
+
+1. Installer input/disk safety tests, shell/Python/XML/JSON syntax, workflow lint.
+2. Build a real ISO; check checksums, package inventory and configuration in its
+ actual SquashFS filesystem.
+3. Boot the ISO under BIOS and UEFI; verify hn is visible and Chromium is absent
+ until requested. Test browser toggle, clipboard, terminal input, reconnect,
+ last-pane behavior and frontend restart without terminating agent work.
+4. Operate the real installer form on a guest terminal: disk picker, encryption
+ toggle, masked passwords, Back/Esc, a single explicit Install action and persistent completion.
+ Install from the offline image to disposable VM disks, encrypted and plain;
+ reboot from each disk, verify accounts/permissions/bootloaders and defaults.
+5. Exercise real agent executables, dependency installation, parallel panes and
+ ordinary development work. Report credential-dependent rows separately.
+6. Exercise update failure and rollback with matching kernel/initramfs/modules,
+ keeping user projects outside root rollback.
+7. Record installation duration, kernel-to-hn readiness, idle RAM/CPU and image
+ and installed sizes. VM firmware time is not physical power-on time.
+8. Physical old ThinkPad and RTX GPU acceptance remains a separate evidence row.
+ No VM test proves Wi-Fi, suspend, firmware or NVIDIA on the user's hardware.
+
+No benchmark or hardware support claim is considered measured before these
+checks produce artifacts. Build, validation, publication and waiting are tracked
+separately in `progress.json`.
+
+## Measured preview footprint
+
+These measurements cover preview 4 image `21aa5de0bd1a9a8a21cb4be06f83bf65c072a1b8`.
+The ISO is 1,612,300,288 bytes (1.50 GiB), with 405 installed packages. Both test
+environments have two virtual CPUs. [1 GiB USB tests](https://github.com/autonomous-ai/openharness/actions/runs/37119543543)
+boot from the mounted medium; [4 GiB USB tests](https://github.com/autonomous-ai/openharness/actions/runs/37120135497)
+exercise automatic copy-to-RAM. Idle samples are taken on the installed disk,
+with agents and browser closed and the measurement process included.
+
+| Measurement | 1 GiB VM | 4 GiB VM |
+| --- | --- | --- |
+| Installed root used, including home and snapshots | 2.03–2.07 GiB | 2.06–2.08 GiB |
+| Settled RAM, six samples across both firmware modes | 396.02–399.43 MiB | 480.62–511.13 MiB |
+| Settled CPU, six two-second samples | 0.25–1.74% | 0–1.5% |
+| Offline BIOS/plain installation | 35.8 seconds | 30.0 seconds |
+| Offline UEFI/encrypted installation | 57.8 seconds | 44.6 seconds |
+| Installed BIOS boot through hn readiness, including automated login | 16.3 seconds | 17.3 seconds |
+| Encrypted boot to password prompt | 4.9 seconds | 4.6 seconds |
+| Password submission to hn readiness, including diagnostic login | 8.1 seconds | 8.3 seconds |
+
+Encrypted tests also wait 100 seconds before attempting a wrong password and
+then the correct one. The raw totals include that wait, retry and automated typing;
+`boot-events.jsonl` records each stage so human interaction is not reported as OS
+startup time. A previous instrumented run made the serial port the primary console
+and delayed the graphical prompt; keeping the screen primary corrected the test
+configuration. Ordinary installations do not add the diagnostic serial console.
+
+The installer limits its extraction caches to 64 MiB. This fixed an actual
+out-of-memory failure after trying OpenCode and Chromium in the 1 GiB live session.
+The 1 GiB runs now pass installation, boot, recovery and the first model conversation.
+Leave more memory for browser tabs, concurrent agents and local model weights.
+These are native x86 VM observations, not physical laptop power-on benchmarks.
+The BIOS agent checks use a Nehalem CPU profile without AVX2. Physical GPUs keep
+hardware acceleration; software rendering is selected only for a detected 2D
+virtio display.
+
+## Real programmer exercises
+
+[Four project checks](https://github.com/autonomous-ai/openharness/actions/runs/37120135497)
+passed on this image: a Python log-analysis CLI, a keyboard-accessible conference
+website, a canvas game and a Fastify/SQLite issue tracker. Three completed projects
+from the earlier preview 4 validation were reused; the game agent ran again and
+all 31 project unit tests and independent checks reran on this exact image.
+The independent tester checks file/stdin behavior, keyboard navigation, mobile
+layout, game controls and state, API validation, CRUD and persistence across a
+server restart. A separate compiler check installs gcc/make and builds C.
+
+[Three fresh DSH exercises](https://github.com/autonomous-ai/openharness/actions/runs/37120138348)
+use the repository's Web Viewer and Game Viewer. They materialize managed agent
+workspaces, edit and reload HTML, build a terminal CSV tool, and change/play/export
+a game. Tests use the OS's sandboxed Chromium. OpenCode uses upstream model
+defaults; availability can change. Project source, screenshots and receipts ship
+in `harness-examples.zip` and `machine-evidence.zip`. Test projects and test tools
+are separate from the minimal ISO.
+
+To repeat these exercises, dispatch **Harness OS** with
+`image_run_id=37119543543` and either `workloads=true` or `dsh=true`, using
+`memory_mib=4096` and `live_transport=usb`. `memory_mib=1024` selects the constrained
+base-machine journey. Model calls have deadlines; agent completion and independent
+acceptance are recorded separately. The publisher rejects failed or mismatched
+machine evidence and a guide that names a different ISO.
diff --git a/os/build.sh b/os/build.sh
new file mode 100644
index 000000000..466d3d9e3
--- /dev/null
+++ b/os/build.sh
@@ -0,0 +1,100 @@
+#!/usr/bin/env bash
+# Build on x86_64 Arch Linux as root (the workflow uses an isolated container).
+set -euo pipefail
+OS_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
+[[ $(uname -m) == x86_64 && $EUID == 0 ]] || { echo 'Build requires x86_64 Linux and root.' >&2; exit 1; }
+cd "$OS_DIR"
+SOURCE_ROOT=$(cd "$OS_DIR/.." && pwd)
+[[ -z $(git -c safe.directory="$SOURCE_ROOT" -C "$SOURCE_ROOT" status --porcelain --untracked-files=normal) ]] || {
+ echo 'Commit source changes before building a traceable OS image.' >&2
+ exit 1
+}
+export HARNESS_OS_SOURCE_SHA=${HARNESS_OS_SOURCE_SHA:-$(git -c safe.directory="$SOURCE_ROOT" -C "$SOURCE_ROOT" rev-parse HEAD)}
+VERSION=$(python3 -c 'import json; print(json.load(open("lock.json"))["version"])')
+SNAPSHOT=$(python3 -c 'import json; print(json.load(open("lock.json"))["arch_snapshot"])')
+BUILD_DIR=${HARNESS_OS_BUILD_DIR:-$OS_DIR/work}
+RUNTIME_DIR=${HARNESS_OS_RUNTIME_DIR:-$OS_DIR/work/runtime}
+[[ -s "$RUNTIME_DIR/source.json" && -x "$RUNTIME_DIR/harness-tui" ]] || {
+ echo 'Build the OS runtimes first with make -C os runtime on x86_64 Linux.' >&2
+ exit 1
+}
+mkdir -p "$BUILD_DIR" "$OS_DIR/dist"
+[[ ! -e "$BUILD_DIR/profile" ]] || { echo 'Use a fresh build directory; refusing to reuse an incomplete image.' >&2; exit 1; }
+cp -a /usr/share/archiso/configs/releng "$BUILD_DIR/profile"
+PROFILE="$BUILD_DIR/profile"
+# The source profile supplies the upstream BIOS/UEFI boot machinery only.
+rm -rf "$PROFILE/airootfs"
+mkdir -p "$PROFILE/airootfs"
+cp packages.x86_64 "$PROFILE/packages.x86_64"
+cat > "$PROFILE/pacman.conf" <<EOF
+[options]
+Architecture = auto
+CheckSpace
+ParallelDownloads = 8
+SigLevel = Required DatabaseOptional
+LocalFileSigLevel = Optional
+[harness-build]
+SigLevel = Optional TrustAll
+Server = file://$BUILD_DIR/repo
+[core]
+Server = https://archive.archlinux.org/repos/$SNAPSHOT/\$repo/os/\$arch
+[extra]
+Server = https://archive.archlinux.org/repos/$SNAPSHOT/\$repo/os/\$arch
+EOF
+# Reuse the same package assembly for fresh images and small development updates.
+python3 tools/build-package.py --runtime "$RUNTIME_DIR" --output "$BUILD_DIR/repo"
+repo-add "$BUILD_DIR/repo/harness-build.db.tar.gz" "$BUILD_DIR/repo/"*.pkg.tar.gz
+cp -a live/. "$PROFILE/airootfs/"
+mkdir -p "$PROFILE/airootfs/root" "$PROFILE/airootfs/etc/pacman.d/hooks"
+cp tools/customize-live.sh "$PROFILE/airootfs/root/setup-live.sh"
+cat > "$PROFILE/airootfs/etc/pacman.d/hooks/99-harness-live.hook" <<'EOF'
+[Trigger]
+Operation = Install
+Type = Package
+Target = harness-os
+[Action]
+Description = Preparing the Harness live session
+When = PostTransaction
+Exec = /bin/bash /root/setup-live.sh
+EOF
+cat >> "$PROFILE/profiledef.sh" <<EOF
+
+iso_name="harness"
+iso_label="HN_OS"
+iso_publisher="OpenHarness"
+iso_application="Harness: boot into hn"
+iso_version="$VERSION"
+airootfs_image_type="squashfs"
+airootfs_image_tool_options=("-comp" "zstd" "-Xcompression-level" "6" "-b" "1M")
+file_permissions=(
+ ["/root"]="0:0:750"
+)
+EOF
+# Use the same LTS kernel in the live USB and on disk.
+python3 - "$PROFILE" <<'PY'
+from pathlib import Path
+import re, sys
+p = Path(sys.argv[1])
+for d in ['syslinux', 'efiboot', 'grub']:
+ for f in (p / d).rglob('*'):
+ if f.is_file():
+ try: s = f.read_text()
+ except UnicodeDecodeError: continue
+ s = s.replace('vmlinuz-linux', 'vmlinuz-linux-lts').replace('initramfs-linux.img', 'initramfs-linux-lts.img')
+ s = s.replace('Arch Linux install medium', 'Harness - try or install')
+ # The 256 MiB Archiso default cannot install even one current agent.
+ # tmpfs grows on demand; this is a ceiling, not reserved memory.
+ s = s.replace('archisobasedir=%INSTALL_DIR%', 'archisobasedir=%INSTALL_DIR% cow_spacesize=50%')
+ # Keep a short opportunity to choose recovery media or firmware tools.
+ s = re.sub(r'(?m)^timeout(?:=|\s+)\d+', lambda m: 'timeout=1' if '=' in m[0] else 'timeout 1', s)
+ s = re.sub(r'(?m)^TIMEOUT\s+\d+', 'TIMEOUT 10', s) # Syslinux uses tenths of a second.
+ s = re.sub(r'(?m)^beep on$', 'beep off', s)
+ s = re.sub(r'(?m)^play .*$', '', s)
+ s = s.replace('MENU TITLE Arch Linux', 'MENU TITLE Harness')
+ s = re.sub(r'(?m)^MENU BACKGROUND .*\n', '', s)
+ f.write_text(s)
+PY
+chown -R 0:0 "$PROFILE/airootfs"
+mkarchiso -v -w "$BUILD_DIR/archiso" -o "$OS_DIR/dist" "$PROFILE"
+python3 tools/manifest.py "$OS_DIR/dist" "$BUILD_DIR/archiso/x86_64/airootfs"
+python3 tools/inspect_image.py "$OS_DIR/dist/"*.iso
diff --git a/os/installer.py b/os/installer.py
new file mode 100644
index 000000000..b88574895
--- /dev/null
+++ b/os/installer.py
@@ -0,0 +1,562 @@
+#!/usr/bin/env python3
+"""Offline full-disk installer. Nothing is erased until the exact disk is confirmed."""
+from __future__ import annotations
+import argparse
+import curses
+from datetime import datetime, timezone
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+import time
+
+MIN_DISK_BYTES = 12 * 1024**3
+LIVE_PAYLOADS = (Path('/run/archiso/copytoram/airootfs.sfs'),
+ Path('/run/archiso/bootmnt/arch/x86_64/airootfs.sfs'))
+
+
+def run(*args, input=None, capture=False):
+ result = subprocess.run([str(a) for a in args], input=input, check=True,
+ stdout=subprocess.PIPE if capture else None)
+ return result.stdout.decode().strip() if capture else None
+
+
+def partitions(disk):
+ separator = 'p' if disk[-1].isdigit() else ''
+ return [f'{disk}{separator}{n}' for n in (1, 2, 3)]
+
+
+def validate_config(config):
+ if not isinstance(config, dict) or any(not isinstance(config.get(key), str) for key in ['username', 'hostname', 'password', 'disk']):
+ raise ValueError('Account, computer, password and disk fields must be text.')
+ if not re.fullmatch(r'[a-z_][a-z0-9_-]{0,30}', config.get('username', '')):
+ raise ValueError('Use a Linux username: lowercase letters, digits, underscores or hyphens.')
+ if config['username'] == 'root':
+ raise ValueError('Create a regular user, not root.')
+ if not re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', config.get('hostname', '')):
+ raise ValueError('Invalid hostname.')
+ password = config.get('password', '')
+ if not password:
+ raise ValueError('Enter a password.')
+ if any(c in password for c in '\r\n\0'):
+ raise ValueError('The password cannot contain line breaks or null characters.')
+ if type(config.get('encrypt')) is not bool:
+ raise ValueError('encrypt must be true or false.')
+ if not re.fullmatch(r'/dev/[a-zA-Z0-9_-]+', config.get('disk', '')):
+ raise ValueError('Select a whole /dev disk.')
+
+
+def validate_disk(device, expected_serial=None):
+ if device.get('type') != 'disk' or device.get('ro'):
+ raise ValueError('Target must be a writable whole disk.')
+ if int(device.get('size') or 0) < MIN_DISK_BYTES:
+ raise ValueError('The target needs at least 12 GiB.')
+ def mounted(node):
+ return any(node.get('mountpoints') or []) or any(mounted(c) for c in node.get('children', []))
+ if mounted(device):
+ raise ValueError('The disk has mounted filesystems. The live USB and active disks cannot be erased.')
+ def live_medium(node):
+ return (node.get('fstype') == 'iso9660' and node.get('label') == 'HN_OS') or any(
+ live_medium(c) for c in node.get('children', []))
+ if live_medium(device):
+ raise ValueError('The Harness USB cannot be an installation target, even when booted into RAM.')
+ if expected_serial is not None and str(device.get('serial') or '').strip() != expected_serial:
+ raise ValueError('Disk serial does not match the unattended installation configuration.')
+
+
+def inventory():
+ return json.loads(run('lsblk', '--json', '--bytes', '--paths', '--output',
+ 'NAME,TYPE,SIZE,RO,RM,MOUNTPOINTS,MODEL,SERIAL,FSTYPE,LABEL', capture=True))['blockdevices']
+
+
+def live_payload(source=None):
+ # Archiso automatically copies USB media to RAM when enough memory is free,
+ # then unmounts bootmnt. Prefer that running image over any removable copy.
+ candidates = (source,) if source is not None else LIVE_PAYLOADS
+ for candidate in candidates:
+ if candidate.is_file():
+ return candidate
+ checked = ', '.join(str(path) for path in candidates)
+ raise ValueError(f'Live system payload is missing (checked {checked}); boot the Harness USB.')
+
+
+def selected_disk(config):
+ devices = [d for d in inventory() if d['name'] == config['disk']]
+ if len(devices) != 1:
+ raise ValueError('Target disk was not found.')
+ validate_disk(devices[0], config.get('expected_serial'))
+ return devices[0]
+
+
+def write(root, path, text, mode=0o644):
+ target = root / path.lstrip('/')
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(text)
+ target.chmod(mode)
+
+
+def chroot(root, *args, **kwargs):
+ return run('arch-chroot', root, *args, **kwargs)
+
+
+def validate_image_account(passwd, username):
+ names = {line.split(':', 1)[0] for line in passwd.splitlines()}
+ if username != 'me' and username in names:
+ raise ValueError(f'The image reserves the username {username}; choose a different account name.')
+
+
+def preflight(config, source):
+ for command in ['sgdisk', 'udevadm', 'mkfs.fat', 'mkfs.btrfs', 'cryptsetup',
+ 'mount', 'umount', 'btrfs', 'unsquashfs', 'arch-chroot', 'blkid']:
+ if not shutil.which(command):
+ raise ValueError(f'The installer is missing {command}. Boot an intact Harness image.')
+ validate_image_account(run('unsquashfs', '-cat', source, 'etc/passwd', capture=True), config['username'])
+ lock = json.loads(run('unsquashfs', '-cat', source, 'usr/share/harness-os/lock.json', capture=True))
+ if lock.get('architecture') != 'x86_64' or not lock.get('version'):
+ raise ValueError('The source is not a Harness x86_64 image.')
+ kernel = json.loads(run('unsquashfs', '-cat', source, 'usr/share/harness-os/kernel.json', capture=True))
+ if not re.fullmatch(r'usr/lib/modules/[a-zA-Z0-9._+-]+/vmlinuz', kernel.get('path', '')) or not re.fullmatch(r'[a-f0-9]{64}', kernel.get('sha256', '')):
+ raise ValueError('The image has an invalid kernel manifest.')
+ payload = subprocess.check_output(['unsquashfs', '-cat', str(source), kernel['path']])
+ if hashlib.sha256(payload).hexdigest() != kernel['sha256']:
+ raise ValueError('The installation kernel failed verification. No disk has been erased.')
+ return kernel
+
+
+def install(config, source, target):
+ validate_config(config)
+ # Inspect again immediately before partitioning, rather than trusting the picker.
+ selected_disk(config)
+ if not source.is_file():
+ raise ValueError('Live system payload is missing; boot the Harness USB.')
+ if target.exists() and any(target.iterdir()):
+ raise ValueError('Installation mountpoint is not empty.')
+ if config.get('confirm_erase') != config['disk']:
+ raise ValueError('Explicit confirmation of the exact disk is required.')
+ kernel = preflight(config, source)
+ selected_disk(config)
+ started = time.monotonic()
+ disk = config['disk']
+ _, boot, root_partition = partitions(disk)
+ target.mkdir(parents=True, exist_ok=True)
+ mapper = f'hn-install-{os.getpid()}'
+ opened = False
+ mounted = False
+ try:
+ print(f'Erasing {disk} and installing Harness...', flush=True)
+ run('sgdisk', '--zap-all', disk)
+ run('sgdisk', '-n', '1:1MiB:+2MiB', '-t', '1:ef02', '-c', '1:HN BIOS',
+ '-n', '2:0:+1GiB', '-t', '2:ef00', '-c', '2:HN BOOT',
+ '-n', '3:0:0', '-t', '3:8309' if config['encrypt'] else '3:8300', '-c', '3:HN ROOT', disk)
+ run('udevadm', 'settle')
+ run('mkfs.fat', '-F', '32', '-n', 'HNBOOT', boot)
+ root_device = root_partition
+ luks_uuid = None
+ if config['encrypt']:
+ secret = config['password'].encode()
+ run('cryptsetup', 'luksFormat', '--type', 'luks2', '--batch-mode', '--key-file=-', root_partition, input=secret)
+ run('cryptsetup', 'open', '--key-file=-', root_partition, mapper, input=secret)
+ opened = True
+ root_device = f'/dev/mapper/{mapper}'
+ luks_uuid = run('blkid', '-s', 'UUID', '-o', 'value', root_partition, capture=True)
+ run('mkfs.btrfs', '-f', '-L', 'HNROOT', root_device)
+ run('mount', root_device, target)
+ mounted = True
+ for name in ('@', '@home', '@snapshots'):
+ run('btrfs', 'subvolume', 'create', target / name)
+ run('umount', target)
+ mounted = False
+ run('mount', '-o', 'subvol=@,compress=zstd:1,noatime', root_device, target)
+ mounted = True
+ for name, subvol in [('home', '@home'), ('.snapshots', '@snapshots')]:
+ (target / name).mkdir()
+ run('mount', '-o', f'subvol={subvol},compress=zstd:1,noatime', root_device, target / name)
+ print('Copying the verified offline system...', flush=True)
+ # Unsquashfs defaults to 512 MiB of caches. Bound them so installation
+ # still fits on a 1 GiB machine after trying the bundled agent/browser.
+ run('unsquashfs', '-mem', '64M', '-f', '-no-progress', '-d', target, source)
+ # Extract on Btrfs first: FAT cannot represent the image's Unix metadata.
+ # Copy boot contents without that metadata before regenerating initramfs.
+ boot_staging = target / 'boot.from-image'
+ (target / 'boot').rename(boot_staging)
+ (target / 'boot').mkdir()
+ run('mount', boot, target / 'boot')
+ for path in boot_staging.rglob('*'):
+ destination = target / 'boot' / path.relative_to(boot_staging)
+ if path.is_dir():
+ destination.mkdir(parents=True, exist_ok=True)
+ elif path.is_file():
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(path, destination)
+ shutil.rmtree(boot_staging)
+ # mkarchiso moves the live /boot files out of SquashFS. Regenerate the
+ # disk initramfs around this verified, package-owned kernel instead.
+ shutil.copyfile(target / kernel['path'], target / 'boot/vmlinuz-linux-lts')
+ print('Configuring account, boot and recovery...', flush=True)
+ # The live image is immutable. No live passwords, SSH keys or sessions are copied.
+ for path in ['etc/sudoers.d/10-live', 'etc/mkinitcpio.conf.d/archiso.conf',
+ 'etc/systemd/system/[email protected]/live.conf',
+ 'etc/pacman.d/hooks/99-harness-live.hook', 'root/setup-live.sh', 'etc/harness-live']:
+ (target / path).unlink(missing_ok=True)
+ for path in ['etc/systemd/system/[email protected]', 'root/.ssh']:
+ shutil.rmtree(target / path, ignore_errors=True)
+ if (target / 'etc/passwd').read_text().find('\nme:') >= 0:
+ chroot(target, 'userdel', '-r', 'me')
+ chroot(target, 'useradd', '-m', '-G', 'wheel,video,audio', '-s', '/bin/bash', config['username'])
+ chroot(target, 'chpasswd', input=f"{config['username']}:{config['password']}\n".encode())
+ chroot(target, 'passwd', '-l', 'root')
+ (target / 'var/lib/systemd/linger/me').unlink(missing_ok=True)
+ write(target, f'/var/lib/systemd/linger/{config["username"]}', '')
+ home = target / 'home' / config['username']
+ (home / 'Projects').mkdir(exist_ok=True)
+ chroot(target, 'chown', '-R', f"{config['username']}:{config['username']}", f"/home/{config['username']}")
+ write(target, '/etc/sudoers.d/10-harness', '%wheel ALL=(ALL:ALL) ALL\n', 0o440)
+ write(target, '/etc/hostname', config['hostname'] + '\n')
+ write(target, '/etc/hosts', f"127.0.0.1 localhost\n::1 localhost\n127.0.1.1 {config['hostname']}\n")
+ write(target, '/etc/machine-id', '')
+ write(target, '/etc/mkinitcpio.conf',
+ 'HOOKS=(base systemd autodetect microcode modconf kms keyboard sd-vconsole '
+ + ('plymouth ' if config['encrypt'] else '')
+ + 'block sd-encrypt filesystems fsck)\nCOMPRESSION="zstd"\n')
+ write(target, '/etc/vconsole.conf', 'KEYMAP=us\n')
+ if config['encrypt']:
+ write(target, '/etc/plymouth/plymouthd.conf',
+ '[Daemon]\nTheme=harness\nShowDelay=0\nDeviceTimeout=5\n')
+ root_uuid = run('blkid', '-s', 'UUID', '-o', 'value', root_device, capture=True)
+ boot_uuid = run('blkid', '-s', 'UUID', '-o', 'value', boot, capture=True)
+ write(target, '/etc/fstab',
+ f'UUID={root_uuid} / btrfs subvol=@,compress=zstd:1,noatime 0 0\n'
+ f'UUID={root_uuid} /home btrfs subvol=@home,compress=zstd:1,noatime 0 0\n'
+ f'UUID={root_uuid} /.snapshots btrfs subvol=@snapshots,compress=zstd:1,noatime 0 0\n'
+ f'UUID={boot_uuid} /boot vfat umask=0077 0 2\n')
+ # The disk-unlock password is the authentication step on encrypted installs.
+ # Unencrypted installs require a normal console login instead of autologin.
+ if config['encrypt']:
+ write(target, '/etc/systemd/system/[email protected]/autologin.conf',
+ '[Service]\nExecStart=\n' + f'ExecStart=-/usr/bin/agetty --autologin {config["username"]} --noclear %I $TERM\n')
+ # An encrypted root cannot appear until its owner returns to unlock it.
+ # Do not send a person who paused at the prompt into emergency mode.
+ root_flags = 'subvol=@' + (',x-systemd.device-timeout=0' if config['encrypt'] else '')
+ kernel_args = f'quiet loglevel=3 rootflags={root_flags}'
+ if config.get('serial_console'):
+ # Keep the screen as /dev/console, as on an ordinary installation.
+ # Making the diagnostic serial port primary can introduce serial-TTY
+ # setup delays before Plymouth can display its unlock prompt.
+ kernel_args += ' console=ttyS0,115200 console=tty0 plymouth.ignore-serial-consoles'
+ if luks_uuid:
+ kernel_args += f' rd.luks.name={luks_uuid}=cryptroot splash'
+ write(target, '/etc/default/grub',
+ 'GRUB_DEFAULT=0\nGRUB_TIMEOUT=1\nGRUB_DISTRIBUTOR="Harness"\n'
+ 'GRUB_DISABLE_OS_PROBER=true\n' + f'GRUB_CMDLINE_LINUX="{kernel_args}"\n')
+ lock = json.loads((target / 'usr/share/harness-os/lock.json').read_text())
+ snapshot = lock['arch_snapshot']
+ write(target, '/etc/pacman.conf',
+ '[options]\nArchitecture = auto\nCheckSpace\nSigLevel = Required DatabaseOptional\nLocalFileSigLevel = Optional\n'
+ + ''.join(f'[{repo}]\nServer = https://archive.archlinux.org/repos/{snapshot}/$repo/os/$arch\n' for repo in ['core', 'extra']))
+ # Retain network configuration explicitly, not the live user's home or credentials.
+ networks = Path('/etc/NetworkManager/system-connections')
+ if networks.exists():
+ shutil.copytree(networks, target / 'etc/NetworkManager/system-connections', dirs_exist_ok=True)
+ chroot(target, 'systemctl', 'enable', 'NetworkManager', 'systemd-resolved', 'systemd-timesyncd')
+ chroot(target, 'systemctl', 'disable', 'sshd.service')
+ chroot(target, '/usr/lib/harness-os/init-keyring')
+ chroot(target, 'mkinitcpio', '-P')
+ chroot(target, 'grub-install', '--target=i386-pc', '--recheck', disk)
+ chroot(target, 'grub-install', '--target=x86_64-efi', '--efi-directory=/boot', '--boot-directory=/boot', '--removable', '--no-nvram')
+ chroot(target, 'grub-mkconfig', '-o', '/boot/grub/grub.cfg')
+ receipt = {'version': lock['version'], 'installed_at': datetime.now(timezone.utc).isoformat(),
+ 'duration_seconds': round(time.monotonic() - started, 3), 'encrypted': config['encrypt'],
+ 'disk_bytes': selected_size(config), 'root_uuid': root_uuid, 'boot_uuid': boot_uuid}
+ write(target, '/var/lib/harness-os/install.json', json.dumps(receipt, indent=2) + '\n')
+ run('sync')
+ print(f"Installed in {receipt['duration_seconds']:.1f}s. Shut down, remove the USB, and boot the disk.", flush=True)
+ finally:
+ if mounted:
+ run('umount', '-R', target)
+ if opened:
+ run('cryptsetup', 'close', mapper)
+
+
+def selected_size(config):
+ # After installation the target is mounted, so this is not a safety check.
+ return next(int(d['size']) for d in inventory() if d['name'] == config['disk'])
+
+
+def display_text(value):
+ # Device metadata must not inject terminal controls or extra form rows.
+ return ''.join(c if c.isprintable() else '?' for c in str(value or '')).strip()
+
+
+def disk_label(disk):
+ size = f"{int(disk['size']) / 1_000_000_000:.1f}".removesuffix('.0')
+ return f"{display_text(disk.get('model')) or 'Disk'} {size} GB"
+
+
+class InstallForm:
+ """Small keyboard form using the Python/ncurses already in the image."""
+ def __init__(self, screen, candidates, username, hostname, encrypt):
+ self.screen, self.disks = screen, candidates
+ self.username, self.hostname, self.encrypt = username, hostname, encrypt
+ self.selected, self.focus = 0, 0
+ self.passwords, self.positions = ['', ''], [0, 0]
+ self.error = ''
+ self.title = None
+ self.cursor_visible = None
+
+ def line(self, row, text, active=False, bold=False):
+ height, width = self.screen.getmaxyx()
+ if row >= height or width < 5:
+ return
+ attr = curses.A_REVERSE if active else curses.A_BOLD if bold else curses.A_NORMAL
+ self.screen.addnstr(row, 2, text, width - 4, attr)
+
+ def cursor(self, visible):
+ if visible == self.cursor_visible:
+ return
+ try:
+ curses.curs_set(int(visible))
+ except curses.error:
+ pass # Some serial terminals cannot change cursor visibility.
+ self.cursor_visible = visible
+
+ def begin(self, title):
+ if title != self.title:
+ self.screen.clear()
+ self.title = title
+ else:
+ self.screen.erase()
+ height, width = self.screen.getmaxyx()
+ if height < 18 or width < 54:
+ self.cursor(False)
+ self.line(0, 'Resize terminal to at least 54 columns and 18 rows.')
+ self.line(2, 'Esc cancels. No disk has been changed.')
+ self.screen.refresh()
+ if self.key() == '\x1b':
+ raise KeyboardInterrupt('Cancelled.')
+ return False
+ self.line(1, title, bold=True)
+ return True
+
+ def key(self):
+ key = self.screen.get_wch()
+ if key == '\x03':
+ raise KeyboardInterrupt('Cancelled.')
+ return key
+
+ @staticmethod
+ def enter(key):
+ return key in ('\n', '\r', curses.KEY_ENTER)
+
+ def pick_disk(self):
+ selected = self.selected
+ while True:
+ if not self.begin('Select disk'):
+ continue
+ height, _ = self.screen.getmaxyx()
+ count = max(1, height - 8)
+ start = (selected // count) * count
+ for index in range(start, min(start + count, len(self.disks))):
+ disk = self.disks[index]
+ row = 4 + index - start
+ self.line(row, ('> ' if index == selected else ' ') + disk_label(disk) + ' ' + disk['name'], index == selected)
+ self.cursor(False)
+ self.screen.refresh()
+ key = self.key()
+ if key == '\x1b':
+ return
+ if self.enter(key):
+ self.selected = selected
+ return
+ if key in (curses.KEY_UP, curses.KEY_BTAB):
+ selected = (selected - 1) % len(self.disks)
+ elif key in (curses.KEY_DOWN, '\t'):
+ selected = (selected + 1) % len(self.disks)
+
+ def edit_password(self, index, key):
+ value, position = self.passwords[index], self.positions[index]
+ if key in (curses.KEY_BACKSPACE, '\x7f', '\b') and position:
+ value, position = value[:position - 1] + value[position:], position - 1
+ elif key == curses.KEY_DC:
+ value = value[:position] + value[position + 1:]
+ elif key == '\x15': # Ctrl+U clears a hidden field without revealing it.
+ value, position = '', 0
+ elif key == curses.KEY_LEFT:
+ position = max(0, position - 1)
+ elif key == curses.KEY_RIGHT:
+ position = min(len(value), position + 1)
+ elif key == curses.KEY_HOME:
+ position = 0
+ elif key == curses.KEY_END:
+ position = len(value)
+ elif isinstance(key, str) and key.isprintable() and len(value) < 4096:
+ value, position = value[:position] + key + value[position:], position + len(key)
+ self.passwords[index], self.positions[index] = value, position
+ self.error = ''
+
+ def run(self):
+ self.screen.keypad(True)
+ while True:
+ if not self.begin('Install Harness'):
+ continue
+ disk = self.disks[self.selected]
+ self.line(4, f"{'Disk':18}{disk_label(disk)}", self.focus == 0)
+ self.line(6, f"{'Encryption':18}[{'x' if self.encrypt else ' '}]", self.focus == 1)
+ capacity = min(32, self.screen.getmaxyx()[1] - 24)
+ for index, label in enumerate(('Password', 'Repeat password')):
+ position = self.positions[index]
+ offset = max(0, position - capacity + 1)
+ mask = '*' * len(self.passwords[index][offset:offset + capacity])
+ self.line(8 + index * 2, f'{label:<18}[{mask:<{capacity}}]', self.focus == index + 2)
+ self.line(12, self.error)
+ self.line(14, f"{'':18}[ Install ]", self.focus == 4)
+ self.line(16, 'All data on this disk will be erased.')
+ self.cursor(self.focus in (2, 3))
+ if self.focus in (2, 3):
+ position = self.positions[self.focus - 2]
+ self.screen.move(8 + (self.focus - 2) * 2, 21 + min(position, capacity - 1))
+ self.screen.refresh()
+ key = self.key()
+ if key == '\x1b':
+ raise KeyboardInterrupt('Cancelled.')
+ if key in ('\t', curses.KEY_DOWN):
+ self.focus = (self.focus + 1) % 5
+ elif key in (curses.KEY_BTAB, curses.KEY_UP):
+ self.focus = (self.focus - 1) % 5
+ elif key == ' ' and self.focus == 1:
+ self.encrypt = not self.encrypt
+ elif self.enter(key):
+ if self.focus == 0:
+ self.pick_disk()
+ elif self.focus == 1:
+ self.encrypt = not self.encrypt
+ elif self.focus in (2, 3):
+ self.focus += 1
+ else:
+ config = dict(disk=disk['name'], username=self.username, hostname=self.hostname,
+ encrypt=self.encrypt, password=self.passwords[0],
+ expected_serial=str(disk.get('serial') or '').strip())
+ try:
+ validate_config(config)
+ if self.passwords[0] != self.passwords[1]:
+ raise ValueError('Passwords do not match.')
+ selected_disk(config)
+ except ValueError as error:
+ self.error = str(error)
+ continue
+ config['confirm_erase'] = disk['name']
+ return config
+ elif self.focus in (2, 3):
+ self.edit_password(self.focus - 2, key)
+
+
+def interactive(username='me', hostname='harness', encrypt=True):
+ candidates = []
+ for disk in inventory():
+ try:
+ validate_disk(disk)
+ except ValueError:
+ continue
+ candidates.append(disk)
+ if not candidates:
+ raise ValueError('No unmounted, writable whole disk of at least 12 GiB is available.')
+ validate_config(dict(username=username, hostname=hostname, encrypt=encrypt,
+ disk=candidates[0]['name'], password='validation-only'))
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
+ raise ValueError('Interactive installation needs a terminal. Use --config for unattended installation.')
+ curses.set_escdelay(25)
+ return curses.wrapper(lambda screen: InstallForm(screen, candidates, username, hostname, encrypt).run())
+
+
+def completion(screen):
+ """Keep success visible when the installer owns an hn pane, then shut down on request."""
+ screen.keypad(True)
+ curses.flushinp()
+ try:
+ curses.curs_set(0)
+ except curses.error:
+ pass
+ selected = 0
+ while True:
+ screen.erase()
+ height, width = screen.getmaxyx()
+ rows = [(1, 'Harness is installed.', curses.A_BOLD),
+ (4, 'Remove the USB after shutdown.', curses.A_NORMAL),
+ (5, 'Then turn on this computer.', curses.A_NORMAL),
+ (8, '[ Shut down ]', curses.A_REVERSE if selected == 0 else curses.A_NORMAL),
+ (10, 'Back to Harness', curses.A_REVERSE if selected == 1 else curses.A_NORMAL)]
+ for row, text, attr in rows:
+ if row < height and width >= 5:
+ screen.addnstr(row, 2, text, width - 4, attr)
+ screen.refresh()
+ key = screen.get_wch()
+ if key in ('\x1b', '\x03'):
+ return False
+ if key in ('\t', curses.KEY_BTAB, curses.KEY_UP, curses.KEY_DOWN):
+ selected = 1 - selected
+ elif InstallForm.enter(key):
+ return selected == 0
+
+
+def arguments():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--config', type=Path)
+ parser.add_argument('--username', help='Override the default local account name (me)')
+ parser.add_argument('--hostname', help='Override the default computer name (harness)')
+ parser.add_argument('--no-encryption', action='store_true', help='Explicitly install without disk encryption')
+ parser.add_argument('--yes-erase-disk', action='store_true')
+ parser.add_argument('--source', type=Path, help='Override the automatically detected live system image')
+ return parser.parse_args()
+
+
+def main(args=None):
+ args = arguments() if args is None else args
+ if os.geteuid() != 0:
+ raise SystemExit('Run sudo harness install from the live USB.')
+ if args.config:
+ if args.username is not None or args.hostname is not None or args.no_encryption:
+ raise ValueError('With --config, set account names and encryption in that file instead of command-line overrides.')
+ config = json.loads(args.config.read_text())
+ if not args.yes_erase_disk or not config.get('expected_serial'):
+ raise ValueError('Unattended installs require --yes-erase-disk and an exact expected_serial.')
+ source = live_payload(args.source)
+ else:
+ if args.yes_erase_disk:
+ raise ValueError('--yes-erase-disk requires a configuration file.')
+ # Fail before collecting passwords if neither supported boot mode has
+ # an image. An explicit missing --source never falls back silently.
+ source = live_payload(args.source)
+ config = interactive(username=args.username if args.username is not None else 'me',
+ hostname=args.hostname if args.hostname is not None else 'harness',
+ encrypt=not args.no_encryption)
+ install(config, source, Path('/mnt/harness-os'))
+ if not args.config:
+ if curses.wrapper(completion):
+ run('systemctl', 'poweroff')
+
+
+def entrypoint():
+ args = arguments()
+ try:
+ main(args)
+ except KeyboardInterrupt:
+ return 130
+ except (ValueError, OSError, curses.error, subprocess.CalledProcessError) as error:
+ print(f'Installation stopped: {error}', file=sys.stderr, flush=True)
+ # An installer launched from the USB welcome owns its pane. Retain the
+ # error until it has been read instead of closing the pane immediately.
+ # Unattended configuration files and piped callers never wait for input.
+ if not args.config and sys.stdin.isatty() and sys.stderr.isatty():
+ try:
+ input('Press Enter to return to Harness.')
+ except (EOFError, KeyboardInterrupt):
+ pass
+ return 1
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(entrypoint())
diff --git a/os/live/etc/mkinitcpio.conf.d/archiso.conf b/os/live/etc/mkinitcpio.conf.d/archiso.conf
new file mode 100644
index 000000000..300df6f45
--- /dev/null
+++ b/os/live/etc/mkinitcpio.conf.d/archiso.conf
@@ -0,0 +1,4 @@
+# Graphics firmware is available as soon as the live root is mounted. Packing
+# every GPU into this early image duplicates it in both BIOS and UEFI media.
+HOOKS=(base udev microcode modconf memdisk archiso archiso_loop_mnt block filesystems keyboard)
+COMPRESSION="zstd"
diff --git a/os/live/etc/systemd/system/[email protected]/autologin.conf b/os/live/etc/systemd/system/[email protected]/autologin.conf
new file mode 100644
index 000000000..301fed7c5
--- /dev/null
+++ b/os/live/etc/systemd/system/[email protected]/autologin.conf
@@ -0,0 +1,3 @@
+[Service]
+ExecStart=
+ExecStart=-/usr/bin/agetty --autologin me --noclear %I $TERM
diff --git a/os/lock.json b/os/lock.json
new file mode 100644
index 000000000..120837695
--- /dev/null
+++ b/os/lock.json
@@ -0,0 +1,5 @@
+{
+ "version": "0.1.0-preview.4",
+ "arch_snapshot": "2026/10/01",
+ "architecture": "x86_64"
+}
diff --git a/os/packages.x86_64 b/os/packages.x86_64
new file mode 100644
index 000000000..b8775a424
--- /dev/null
+++ b/os/packages.x86_64
@@ -0,0 +1,64 @@
+# Boot, storage, hardware, and ordinary Linux package management.
+base
+linux-lts
+linux-firmware
+sof-firmware
+intel-ucode
+amd-ucode
+mkinitcpio
+mkinitcpio-archiso
+arch-install-scripts
+grub
+efibootmgr
+syslinux
+edk2-shell
+memtest86+
+memtest86+-efi
+dosfstools
+e2fsprogs
+btrfs-progs
+cryptsetup
+plymouth
+gptfdisk
+squashfs-tools
+sudo
+python
+openssh
+networkmanager
+systemd-resolvconf
+zram-generator
+wireless-regdb
+# Exactly one terminal surface and an on-demand browser.
+labwc
+foot
+chromium
+mesa
+vulkan-intel
+vulkan-radeon
+libva-intel-driver
+intel-media-driver
+wl-clipboard
+xdg-utils
+xdg-desktop-portal-wlr
+pipewire
+pipewire-pulse
+wireplumber
+swayidle
+swaylock
+brightnessctl
+ttf-dejavu
+ttf-nerd-fonts-symbols-mono
+noto-fonts-emoji
+# Harness and the package tools needed to bootstrap agent engines.
+nodejs-lts-jod
+npm
+tmux
+git
+curl
+jq
+ripgrep
+less
+which
+unzip
+harness-os
+opencode
diff --git a/os/progress.json b/os/progress.json
new file mode 100644
index 000000000..de83f52bc
--- /dev/null
+++ b/os/progress.json
@@ -0,0 +1,1584 @@
+{
+ "request_started_utc": "2026-10-02T17:09:32Z",
+ "implementation_started_utc": "2026-10-02T17:10:08Z",
+ "implementation_complete_utc": "2026-10-03T01:54:40.607222+00:00",
+ "validation_complete_utc": "2026-10-03T01:49:00Z",
+ "merge_utc": null,
+ "publication_utc": "2026-10-03T02:03:47Z",
+ "completion_utc": null,
+ "status": "Preview 4 and optional development update are public and verified. User reports physical ThinkPad install/boot/use success. Updating the agents-as-apps landing page and validating the authorized main merge. Physical Wi-Fi/suspend/Mac/NVIDIA and browser visual review remain unverified.",
+ "evidence": [
+ {
+ "scope": "Installer/recovery guard tests, real-shell VM command framing, and Python/JSON/XML/Bash syntax",
+ "command": "make -C os check",
+ "result": "passed",
+ "test_count": 14,
+ "at_utc": "2026-10-02T22:01:21Z",
+ "source_sha256": {
+ "os/installer.py": "7703760b9192f727e9e1daafe80e984774a68b47226cf4f6e96115719b51aa7a",
+ "os/system.py": "d4151c2c0d02d8a99a733ad8abb0f334a2e40562421215638dadcef81d853379",
+ "os/tests/test_installer.py": "a91f0916da58620b4256a36ccb4341c0ab2de3d2ba11d10a90e635838dd61a9b",
+ "os/tests/test_system.py": "f028ed6d3ab27f1802fe504ed99cb209a07c57dd9e6837cc5a3a5bca6265a336",
+ "os/tests/test_vm_protocol.py": "14a8657be48778ca38778321e0ebbc7b42970822c9cb69277c7667ca59089ea8"
+ },
+ "limitations": "No claim of real image boot, installation, recovery, or hardware support."
+ },
+ {
+ "scope": "Full hn unit suite and ten native terminal fixtures",
+ "result": "passed",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37044532366",
+ "image_job_id": 110962557234,
+ "source_commit": "4677aa7e7596a93a88dd08d31481fa8c758c8d4a",
+ "tui_tree": "edde219331358a43c6749c4b9447e3aaa27455ca",
+ "cli_tree": "9860ed1e27314ff796374a0e84c7c8b2e6120394",
+ "environment": "Ubuntu 24.04 x86_64; Rust stable musl target; Node 22.23.2",
+ "limitations": "Covers unchanged hn/CLI source; does not validate the assembled OS session."
+ },
+ {
+ "scope": "Real hybrid ISO assembly, checksums and build manifest",
+ "result": "passed",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37044532366",
+ "source_commit": "4677aa7e7596a93a88dd08d31481fa8c758c8d4a",
+ "artifact_id": 11244280283,
+ "artifact_archive_bytes": 1820435868,
+ "limitations": "First development image only. Later local fixes are not in this artifact. Not recommended for installation."
+ },
+ {
+ "scope": "BIOS and UEFI machine tests",
+ "result": "failed before guest boot",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37044532366",
+ "reason": "QEMU rejected the disk serial option on -drive. Corrected locally to a virtio-blk-pci device property; rerun pending."
+ },
+ {
+ "scope": "Actual ISO payload, boot entries, configuration, root ownership, runtime and offline kernel hashes",
+ "result": "passed",
+ "source_commit": "151572d6e76d5802aa53d7ef31b2008791cf44a2",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37071830823",
+ "iso_sha256": "1b4026ee97ddd8b3b3bf38181c6a280ef6b1c14fa25b2ed562006008b8d64051",
+ "limitations": "Machine tests failed on the obsolete foot [colors] section. This artifact is not install-ready."
+ },
+ {
+ "scope": "Installer, recovery, publication guards and real-shell VM protocol",
+ "result": "passed",
+ "test_count": 15,
+ "command": "make -C os check",
+ "source_commit": "1a71edc0dd2ece66781ff94073acdd17f30e1bf9",
+ "limitations": "Portable guard/syntax checks only. Actual VM installation/recovery remains pending."
+ },
+ {
+ "scope": "BIOS/plain and UEFI/encrypted live boot, installation, reboot and offline recovery",
+ "result": "passed",
+ "source_commit": "7d778fe8586fc74cb7133896086537fb16f410de",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37075579216",
+ "limitations": "This image precedes the discovered last-terminal identity fix; physical hardware and real model turns unverified."
+ },
+ {
+ "scope": "On-demand gcc/make, C compilation, Git diff and local web preview",
+ "result": "failed after compiler success",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37076181584",
+ "reason": "Closing the last terminal restarts the underlying tmux server and reuses a pane ID before discovery forgets the old row. Fixed OS tmux server policy in f0b3c0488."
+ },
+ {
+ "scope": "Native terminal regression fixture",
+ "result": "first attempt failed in reference tmux; bounded retry passed all unit, native and machine checks",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37077942258",
+ "reason": "hn reported expected exit status 9; the unchanged reference tmux fixture reported an empty dead status. Other nine native fixtures and 334 unit tests passed. No required check bypassed."
+ },
+ {
+ "scope": "BIOS/plain and UEFI/encrypted installation, recovery, terminal reopen, compiler/browser preview and four vendor agent binaries",
+ "result": "passed",
+ "source_commit": "f0b3c0488c6709ce7afc49224659d5890d9c2584",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37077942258",
+ "limitations": "Visual review found the screen can appear before daemon discovery is ready. Readiness and timing checks strengthened for the next image. No model calls in this suite."
+ },
+ {
+ "scope": "Runtime readiness, live scratch capacity and delayed encrypted unlock",
+ "result": "passed",
+ "image_source_commit": "a19a4de6127b94ecd6ea14a5076e470ec3978af4",
+ "test_source_commit": "2cc57da13dee90c84e8b6a4c668d1d820c46f1da",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37082675625",
+ "limitations": "Whole run failed two additional workload gates: interrupted game agent and malformed DELETE request in acceptance code."
+ },
+ {
+ "scope": "Four real free OpenCode project builds inside installed OS",
+ "result": "partial",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37082675625",
+ "projects": [
+ "Python logscope CLI",
+ "Terminal Days conference website",
+ "Signal Run keyboard game",
+ "Fastify/SQLite Patchboard fullstack app"
+ ],
+ "unit_tests_passed": 94,
+ "independent_checks_passed": [
+ "CLI file/stdin/malformed/filter/empty",
+ "Website keyboard search/day filter/help/mobile layout",
+ "Game movement/pause/restart/snapshot restore",
+ "Backend create/update/validation and persistence after restart"
+ ],
+ "remaining": [
+ "Game agent exceeded 12-minute limit after writing code and passing 23 tests",
+ "DELETE acceptance sent content-type JSON with no body; corrected test is running against retained projects"
+ ],
+ "reported_model_cost": 0
+ },
+ {
+ "scope": "CLI typecheck, affected engine launch/install unit tests, full hn unit suite and native terminal fixtures",
+ "result": "passed",
+ "source_commit": "dfbb815f05a0cbe3c01e474ff83edce5315f6142",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37083780202",
+ "cli_unit_tests_passed": 89,
+ "cli_unit_tests_skipped": 1,
+ "tui_unit_tests_passed": 335,
+ "tui_unit_tests_ignored": 1,
+ "native_fixtures_passed": 10
+ },
+ {
+ "scope": "Smaller ISO; complete BIOS/plain and UEFI/encrypted installation/recovery; real four-agent executable and compiler checks",
+ "result": "passed",
+ "source_commit": "dfbb815f05a0cbe3c01e474ff83edce5315f6142",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37083780202",
+ "iso_bytes": 1525678080,
+ "iso_sha256": "51e3315843440bcdd445ead6b55d281dd1ae40685f3399c084ac5cf33cf5bce6",
+ "bios_install_seconds": 36.512,
+ "bios_ready_seconds_including_test_login": 19.3,
+ "uefi_ready_seconds_including_test_login_and_deliberate_100s_unlock_wait": 110.953,
+ "settled_idle_mib": [
+ 397.59,
+ 397.32,
+ 397.32,
+ 399.3,
+ 396.62,
+ 400.62
+ ],
+ "settled_cpu_percent_2s_samples": [
+ 0.75,
+ 0,
+ 0,
+ 0.25,
+ 0.75,
+ 0
+ ],
+ "limitations": "2-vCPU/2-GiB x86 VMs; measurements include the measurement process. Physical ThinkPad, Wi-Fi, suspend and RTX compute remain unverified."
+ },
+ {
+ "scope": "Four retained free OpenCode projects; focused game layout fix, all unit tests and independent browser/API checks",
+ "result": "passed",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37086423516",
+ "image_source_commit": "dfbb815f05a0cbe3c01e474ff83edce5315f6142",
+ "test_source_commit": "a2b2f1a38d8f283b45d0b414a2b303647273d47f",
+ "unit_tests_passed": 103,
+ "project_origins": [
+ 37082675625,
+ 37084999965
+ ],
+ "limitations": "Three completed model turns reused; all project and independent checks reran. Prior game deadlines remain failed evidence."
+ },
+ {
+ "scope": "Three managed free OpenCode DSHs, shared viewers, CSV tool, keyboard game/pause/restart/export and viewport fit",
+ "result": "passed",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37086603345",
+ "image_source_commit": "dfbb815f05a0cbe3c01e474ff83edce5315f6142",
+ "test_source_commit": "4c9d1a47c20ce06a6f4fbc311d6cca12efd1d3b4"
+ },
+ {
+ "scope": "1 GiB RAM BIOS/plain and UEFI/encrypted full install/recovery; browser, compiler and agent executable checks",
+ "result": "passed",
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37086919917",
+ "image_source_commit": "dfbb815f05a0cbe3c01e474ff83edce5315f6142",
+ "limitations": "No concurrent live model workload at 1 GiB; physical devices remain unverified."
+ },
+ {
+ "scope": "Public preview publication and all nine public downloads",
+ "result": "passed",
+ "release_url": "https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.1",
+ "source_commit": "dfbb815f05a0cbe3c01e474ff83edce5315f6142",
+ "verified_assets": [
+ "boot-layout.txt",
+ "inspection.json",
+ "machine-evidence.zip",
+ "manifest.json",
+ "packages.txt",
+ "programmer-examples.zip",
+ "programmer-os-0.1.0-preview.1-x86_64.iso",
+ "programmer-os-0.1.0-preview.1-x86_64.iso.sha256",
+ "validation.json"
+ ],
+ "iso_sha256": "51e3315843440bcdd445ead6b55d281dd1ae40685f3399c084ac5cf33cf5bce6",
+ "finished_at_utc": "2026-10-03T02:06:57.675352+00:00",
+ "method": "Same guarded publisher run locally with authorized gh authentication; Actions run 37087917557 could not create release (403 Resource not accessible by integration). Receipt reused; no duplicate download cycle."
+ },
+ {
+ "scope": "Mac refreshed runtime and retained examples",
+ "result": "partial",
+ "runtime_source_commit": "dfbb815f05a0cbe3c01e474ff83edce5315f6142",
+ "verified": [
+ "published hn and CLI SHA-256 values inside the VM disk",
+ "all four original example directories retained",
+ "verified public project and DSH archive installed under Projects/preview-examples",
+ "qcow2 integrity check passed",
+ "normal graphical boot configuration restored"
+ ],
+ "failed": [
+ "background Mac reboot readiness",
+ "single-CPU emulation trial"
+ ],
+ "at_utc": "2026-10-03T03:21:35.153023+00:00",
+ "limitations": "Apple Silicon x86 TCG emulation; no new native x86 runtime failure. Earlier Chromium project rendering is separate evidence."
+ }
+ ],
+ "waiting": [
+ {
+ "started_utc": "2026-10-02T18:15:44Z",
+ "ended_utc": "2026-10-02T22:01:42Z",
+ "reason": "GitHub CLI/Git TLS resets and timeouts; intermittent connector RPC failures; connector lacks repository-content write permission and cannot download artifacts above 512 MiB. Native QEMU install failed fetching ghcr.io. Existing Colima VM now runs, but its Ubuntu package-index transfers time out. Some automatic approval reviews timed out; retries sometimes succeeded.",
+ "local_implementation_continued": true,
+ "overlaps_other_stages": true,
+ "resolution": "User restored network access. Git push and local VM package downloads succeeded."
+ },
+ {
+ "started_utc": "2026-10-03T01:54:40.607222+00:00",
+ "ended_utc": "2026-10-03T01:55:13.285215+00:00",
+ "reason": "Automatic approval review rejected public ISO/examples/evidence publication without explicit approval. Exact local bundle prepared and approval requested.",
+ "local_implementation_continued": true,
+ "overlaps_other_stages": true,
+ "resolution": "User approved publishing the exact prepared preview to autonomous-ai/openharness."
+ },
+ {
+ "started_utc": null,
+ "ended_utc": null,
+ "reason": "User approved the local landing-page and VM visual checks, but the browser reports a saved blocking preference and native computer use still refuses the VM app. Awaiting tool permission changes.",
+ "local_implementation_continued": true,
+ "overlaps_other_stages": true
+ }
+ ],
+ "remaining": [
+ "Landing-page visual and keyboard validation: user approved, but saved browser permission still blocks localhost access",
+ "Mac VM visual validation: user approved, but native computer-use tool still denies the application; test VM stopped safely",
+ "Physical ThinkPad boot, installation, Wi-Fi, suspend and hardware verification; user will test manually"
+ ],
+ "last_updated_utc": "2026-10-03T11:39:35.289044+00:00",
+ "remote_build_commit": "dfbb815f05a0cbe3c01e474ff83edce5315f6142",
+ "local_commit_before_latest_test_changes": "9476a2e11cdbc9f83681b3b591f51588e6e7a842",
+ "build_attempts": [
+ {
+ "run_id": 37041386511,
+ "result": "failed",
+ "reason": "HTTP 403 fetching published runtime; replaced with source builds"
+ },
+ {
+ "run_id": 37042351034,
+ "result": "failed",
+ "reason": "Incorrect zram package name; corrected to zram-generator"
+ },
+ {
+ "run_id": 37043363506,
+ "result": "failed",
+ "reason": "Package conflict on Bash skeleton files; replaced with profile.d integration"
+ },
+ {
+ "run_id": 37044532366,
+ "result": "image passed; machine harness failed before guest boot"
+ },
+ {
+ "run_id": 37070229186,
+ "result": "failed",
+ "reason": "All 14 Linux guard/protocol tests passed. Workflow lint rejected two unprefixed file globs; corrected with ./ prefixes."
+ },
+ {
+ "run_id": 37070493791,
+ "result": "ISO assembled; inspection failed",
+ "reason": "Python inspector shadowed the standard inspect module; renamed it and normalized packaged system ownership to root."
+ },
+ {
+ "run_id": 37071830823,
+ "result": "Image inspection passed; machine tests failed",
+ "reason": "Real UEFI boot reached Linux. Shipped foot rejected obsolete [colors] section; corrected to [colors-dark] and added validation by the packaged binary during construction."
+ },
+ {
+ "run_id": 37072955865,
+ "result": "in progress",
+ "source_commit": "1a71edc0dd2ece66781ff94073acdd17f30e1bf9"
+ }
+ ],
+ "recent_implementation": [
+ "Verify and restore the package-owned kernel removed from /boot by Archiso before offline installation",
+ "Initialize a fresh package-verification keyring per machine and pin live-session repositories",
+ "Start the agent runtime with the graphical environment; browser requests use the current user-service environment",
+ "Exercise a real offline package transaction and clear its stale database lock during recovery",
+ "Inspect the actual ISO payload and shorten the USB boot-menu delay to one second",
+ "Guard preview publication with matching full machine evidence and verify all public assets after publishing",
+ "Add an interactive QEMU launcher for the full installation and reboot experience on macOS"
+ ],
+ "additional_user_requested_work": [
+ "Use OpenCode free models for real development inside the installed VM",
+ "Build and exercise a terminal tool, website and keyboard-controlled game",
+ "Build a full-stack application with dependencies, persistent data and automated tests",
+ "Create several DSH packages using existing repository components; exercise native hn and HTML viewers",
+ "Measure and reduce boot time, steady idle CPU/RAM and image footprint without losing functionality"
+ ],
+ "computer_use": {
+ "status": "User explicitly approved local landing-page and native VM visual checks. Both tools still rejected access; no workaround used.",
+ "browser": "Saved user permission blocks http://127.0.0.1:18092. Asked user to change the saved setting.",
+ "native_vm": "Local app launched successfully after renewed approval. cua.getApp(local.programmer-os.vm) refused computer use. Stopped that VM through its own QMP control socket; preserved disk and projects.",
+ "latest_retry": {
+ "at_utc": "2026-10-03T05:44:11.773434+00:00",
+ "user_confirmed": "Any App and Chrome enabled; exact http://127.0.0.1:18092 Browsing rule says Always allow.",
+ "browser": "Exact open Chrome Dee tab still refused: saved permission setting blocks this action.",
+ "native_vm": "cua.getApp(local.programmer-os.vm) still returned Computer Use was not approved.",
+ "next_step": "User may restart Chrome/ChatGPT to refresh connection or permission state. No bypass attempted."
+ }
+ },
+ "additional_work_window": {
+ "started_utc": "2026-10-02T23:33:00Z",
+ "requested_hours": 4,
+ "expected_user_return_utc": "2026-10-03T03:33:00Z",
+ "ended_utc": "2026-10-03T03:33:35.279197+00:00"
+ },
+ "publication_prepared_utc": "2026-10-03T01:54:40.607222+00:00",
+ "publication_approved_utc": "2026-10-03T01:55:13.285215+00:00",
+ "publication_trigger_utc": "2026-10-03T01:55:13.285215+00:00",
+ "publication_verified_utc": "2026-10-03T02:06:57.675352+00:00",
+ "landing_page": {
+ "path": "os/site",
+ "implementation": "Plain HTML/CSS, local WOFF fonts, actual OS and generated-game screenshots",
+ "initial_asset_bytes_before_compression": 156626,
+ "validation": "Static assets, fragment references, fonts, image dimensions and verified release asset names passed",
+ "browser_validation": "Unverified: renewed user approval received, but saved browser permission continues to block the exact local URL.",
+ "implementation_commit": "86955f946"
+ },
+ "mac_vm": {
+ "status": "partial; readiness failures retained",
+ "runtime_hashes_match_published_image": true,
+ "saved_projects": [
+ "os-components",
+ "os-examples",
+ "os-workloads",
+ "preview-examples"
+ ],
+ "normal_graphical_boot_configuration": "restored after stopping the failed test VM",
+ "disk": "os/work/interactive-vm/disk.qcow2",
+ "backup": "os/work/interactive-vm/disk-before-control-recovery.qcow2",
+ "mac_application_boot": "Failed readiness deadline with two emulated CPUs; one-CPU trial also failed. No performance improvement is claimed.",
+ "discarded_experiments": [
+ "one TCG CPU",
+ "application scheduling wrapper",
+ "temporary wake assertion in launcher"
+ ],
+ "computer_use": "Renewed explicit user approval received. VM launched once, but native computer-use tool still denied Programmer OS VM. VM stopped safely; no alternate observation path attempted."
+ },
+ "review_url": "https://github.com/autonomous-ai/openharness/pull/669",
+ "handoff_prepared_utc": "2026-10-03T03:33:35.279197+00:00",
+ "continued_work": {
+ "request_started_utc": null,
+ "request": "User asked to keep working while postponing local visual permission changes.",
+ "implementation_started_utc": null,
+ "implementation_ready_utc": "2026-10-03T04:13:24.219808+00:00",
+ "candidate_version": "0.1.0-preview.2",
+ "published_version": "0.1.0-preview.2",
+ "changes": [
+ "Persist incomplete full-update state before repository or package changes.",
+ "Block ordinary package transactions until a full-update retry succeeds.",
+ "Retain the original recovery checkpoint across failed and interrupted retries.",
+ "Identify the OS package with the candidate image version using pacman prerelease ordering.",
+ "Use the user-selected editable installer defaults me@harness and validate installation under that account."
+ ],
+ "validation_plan": [
+ "Portable installer/recovery/publication/protocol tests and source syntax checks.",
+ "Build a fresh candidate ISO and inspect its exact payload, package version and manifest.",
+ "Native BIOS/plain and UEFI/encrypted installation, update failure and successful retry, original checkpoint retention, package hook, offline recovery and reboot.",
+ "Existing hn/CLI lifecycle, compiler and applicable agent executable checks in the native workflow.",
+ "Verify the installed me account, /home/me, hostname harness, and authentication in both firmware modes."
+ ],
+ "local_validation": {
+ "system_unit_tests": "10 passed during implementation",
+ "portable_checks": "22 passed during implementation",
+ "final_script_syntax_and_diff_check": "passed",
+ "validated_runtime_sha256": {
+ "os/system.py": "5e04e3f213cf0276df6cd7724af734d6f52f59f8aa1a7dce057347805c81c05b",
+ "os/tests/test_system.py": "3e5f226ef656c0a830ec8ee6904b359b516dea009acfe9cc147feefec13908df"
+ },
+ "affected_installer_tests": "7 passed; final syntax and diff checks passed",
+ "working_copy_after_cli_options": {
+ "result": "26 portable tests and Python/JSON/XML/shell syntax passed",
+ "scope": "Includes uncommitted interactive CLI changes, not present in the previously built ISO; does not validate the proposed disk picker/checkbox interface.",
+ "sha256": {
+ "os/installer.py": "2b0f58bedf6fc1107c384535d3c80ea54ecdac449d35d9b02f13867f643d159f",
+ "os/tests/test_installer.py": "a7265db6cdd3b6ad93acb7ad456f9b3753af6ac71814a1453135c0f4298863a7",
+ "os/tests/vm.py": "3ebfb7dc815b77e1969c0ae62667e2c1b34411f829356504cb6054876da5c14a"
+ }
+ }
+ },
+ "native_validation_started_utc": "2026-10-03T04:13:46Z",
+ "native_validation_completed_utc": "2026-10-03T04:53:50Z",
+ "merge_utc": null,
+ "publication_utc": "2026-10-03T07:04:33Z",
+ "limitations": "Preview 2 keyboard installer image and both native machine paths passed on a155a16850438e04315a1959b1bfd1c387d8bf99; all eight public downloads passed full size/SHA-256 verification. Historical real-model project/DSH and 1 GiB results remain tied to preview 1. Physical hardware and local computer-use review remain unverified.",
+ "implementation_revised_utc": "2026-10-03T04:28:01.749594+00:00",
+ "installer_defaults": {
+ "username": "me",
+ "hostname": "harness",
+ "editable": "Account and hostname overrides remain on the command line; encryption is editable in the main form.",
+ "encryption_default": true,
+ "selection_recorded_utc": "2026-10-03T04:28:01.749594+00:00"
+ },
+ "native_attempts": [
+ {
+ "run_id": 37095837835,
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37095837835",
+ "source_commit": "8d3b09afda1e5be67d7581b07eff3db826649b79",
+ "iso_sha256": "67816cd667a4be9c2f0560f8f9e4981a28b5ffcc0a4d1a9c1161764aaf0ff221",
+ "image": "passed",
+ "bios": "failed in the new update fixture after successful installation and boot",
+ "uefi": "failed in the new update fixture after successful encrypted installation and boot",
+ "diagnosis": "Pacman stops at the first unreachable repository; appending the local fixture after core prevented it from syncing. Put the local repository first so the check exercises a real partially synchronized database state.",
+ "evidence": "os/test-results/ci-37095837835-bios/bios-plain/update-retry.log"
+ },
+ {
+ "run_id": 37096639763,
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37096639763",
+ "source_commit": "7a64753b25819b833d5b20f39862f9fab8d97e2a",
+ "iso_sha256": "6c8ee5a89ae8dda35c133276d50fa22635c1e726c96ced94ee82505e7ec2985c",
+ "started_utc": "2026-10-03T04:28:09Z",
+ "completed_utc": "2026-10-03T04:41:00Z",
+ "image": "passed",
+ "bios": "failed after successful installation and boot, before the update fixture",
+ "uefi": "failed after successful encrypted installation and boot, before the update fixture",
+ "diagnosis": "The account/hostname assertion invoked hostname, which is not installed in the minimal image. Use coreutils uname -n to inspect the active kernel hostname without adding a package. Guest shell metadata already showed me@harness; update retry and later checks were not reached.",
+ "evidence": [
+ "os/test-results/ci-37096639763-bios/bios-plain/receipt.json",
+ "os/test-results/ci-37096639763-uefi/uefi-encrypted/receipt.json"
+ ]
+ },
+ {
+ "run_id": 37097681222,
+ "run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37097681222",
+ "source_commit": "147b7458f1974c1bebadf275cfdfa6a02a2fe510",
+ "image_source_commit": "7a64753b25819b833d5b20f39862f9fab8d97e2a",
+ "image_run_id": 37096639763,
+ "iso_sha256": "6c8ee5a89ae8dda35c133276d50fa22635c1e726c96ced94ee82505e7ec2985c",
+ "started_utc": "2026-10-03T04:47:00Z",
+ "status": "passed",
+ "scope": "Reuse the unchanged inspected ISO; rerun BIOS/plain and UEFI/encrypted machine checks with corrected hostname assertion. Uncommitted interactive installer changes are excluded.",
+ "completed_utc": "2026-10-03T04:53:50Z",
+ "bios": "passed",
+ "uefi": "passed"
+ }
+ ],
+ "test_fixture_revised_utc": "2026-10-03T04:46:52.305584+00:00",
+ "installer_ux_proposal": "Approved and implemented: disk picker, encryption checked directly below the disk, password twice, Continue, separate Back/Erase and install confirmation. Back is initially selected. No device-path typing or first-boot account wizard.",
+ "installer_experience": {
+ "request_started_utc": "2026-10-03T05:20:11Z",
+ "request_time_basis": "First implementation action after explicit approval; design discussion and prior draft started earlier.",
+ "implementation_ready_utc": "2026-10-03T05:44:11.773434+00:00",
+ "required_validation_started_utc": "2026-10-03T05:44:11.852041+00:00",
+ "required_validation_completed_utc": "2026-10-03T06:12:04Z",
+ "merge_utc": null,
+ "publication_utc": "2026-10-03T07:04:33Z",
+ "publication_requested": "User will wait for the new public download, then write it to USB and install on a ThinkPad.",
+ "validation_plan": [
+ "Portable installer/recovery/publication/serial tests and syntax with a bounded source receipt",
+ "Fresh source ISO build and exact payload/manifest inspection",
+ "Real guest terminal disk picker, encryption toggle, password entry, Back/Esc and explicit confirmation feeding the actual installer",
+ "BIOS/plain and UEFI/encrypted offline installation, reboot to me@harness, update failure/retry, recovery, browser/clipboard/terminal lifecycle and applicable compiler/agent executable checks",
+ "Prepare and publish the verified preview; verify each public asset size and SHA-256"
+ ],
+ "local_results": [
+ "19 installer tests passed during implementation",
+ "Real macOS PTY with fixture-only disk inventory: disk picker, encryption toggle, masked passwords, Back/Esc and explicit confirmation returned the expected config; no real disk was exposed"
+ ],
+ "limitations": "Native guest-terminal installer and machine checks passed. CI screenshots were visually inspected. Local computer-use review of the landing page and Mac VM remains blocked; physical ThinkPad, Wi-Fi, suspend and NVIDIA remain unverified. Historical real-model project and DSH results remain tied to preview 1.",
+ "local_validation_receipt": {
+ "path": ".harness/validation/20261003T054411.851664Z-23170/receipt.json",
+ "status": "passed",
+ "tests": 34,
+ "base_commit": "147b7458f1974c1bebadf275cfdfa6a02a2fe510",
+ "working_changes_sha256": "0875172f2f8736a8289199158f01d918cd134039e9b8d900e4d0f4b74373e086",
+ "finished_at_utc": "2026-10-03T05:44:12.850298+00:00",
+ "coverage": "All runtime and test edits in this commit; only progress metadata changed after the receipt."
+ },
+ "source_commit": "a155a16850438e04315a1959b1bfd1c387d8bf99",
+ "native_run_id": 37101103529,
+ "native_run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37101103529",
+ "native_validation_started_utc": "2026-10-03T05:50:12Z",
+ "native_attempts": [
+ {
+ "attempt": 1,
+ "started_utc": "2026-10-03T05:50:12Z",
+ "failed_step_utc": "2026-10-03T05:56:33.447257Z",
+ "result": "failed before image production; machine checks not run",
+ "passed": "34 portable tests, workflow lint, runtime build, CLI typecheck/affected tests, hn unit tests and native terminal fixtures",
+ "reason": "archive.archlinux.org package/signature downloads timed out at less than 1 byte/sec for 10 seconds; pacstrap stopped before package installation",
+ "evidence": "os/test-results/ci-37101103529-build/attempt-1.log",
+ "response": "One bounded failed-job rerun on unchanged source and package snapshot, started 2026-10-03T05:58:31Z."
+ },
+ {
+ "attempt": 2,
+ "started_utc": "2026-10-03T05:58:26Z",
+ "completed_utc": "2026-10-03T06:12:04Z",
+ "status": "passed",
+ "image_source_commit": "a155a16850438e04315a1959b1bfd1c387d8bf99",
+ "test_source_commit": "a155a16850438e04315a1959b1bfd1c387d8bf99",
+ "iso_sha256": "7eae886e3f9a77cc5831fae591d4de1f095ff16e43a412f0c714a09042b933d2",
+ "scope": "Image inspection; 34 portable tests; CLI typecheck and 89 affected tests (1 unavailable row skipped); 335 hn tests (1 benchmark ignored); ten native terminal fixtures; BIOS/plain and UEFI/encrypted keyboard installer, offline installation, reboot, update failure/retry, checkpoint recovery; BIOS compiler and four agent executables."
+ }
+ ],
+ "native_validation_completed_utc": "2026-10-03T06:12:04Z",
+ "machine_measurements": [
+ {
+ "firmware": "bios",
+ "encrypted": false,
+ "status": "passed",
+ "receipt": "os/work/release-preview2/machines/bios/bios-plain/receipt.json",
+ "checks_passed": 18,
+ "install_seconds": 30.418,
+ "installed_hn_ready_seconds_including_test_login": 17.819,
+ "deliberate_unlock_delay_seconds": 0,
+ "idle_mib": [
+ 404.37,
+ 403.89,
+ 401.02
+ ],
+ "idle_cpu_percent": [
+ 1.0,
+ 1.0,
+ 0.75
+ ]
+ },
+ {
+ "firmware": "uefi",
+ "encrypted": true,
+ "status": "passed",
+ "receipt": "os/work/release-preview2/machines/uefi/uefi-encrypted/receipt.json",
+ "checks_passed": 17,
+ "install_seconds": 49.341,
+ "installed_hn_ready_seconds_including_test_login": 111.696,
+ "deliberate_unlock_delay_seconds": 100,
+ "idle_mib": [
+ 400.12,
+ 395.05,
+ 396.91
+ ],
+ "idle_cpu_percent": [
+ 1.25,
+ 0.25,
+ 0.0
+ ]
+ }
+ ],
+ "publication_trigger_utc": "2026-10-03T06:25:51.506554+00:00",
+ "usb_flash": {
+ "status": "Not flashed by assistant; raw disk write denied before any image bytes, then Etcher startup crash during user attempt",
+ "target": "Kingston DataTraveler 3.0, 124 GB external USB",
+ "source_iso_sha256": "7eae886e3f9a77cc5831fae591d4de1f095ff16e43a412f0c714a09042b933d2",
+ "authorization": "User asked the assistant to flash the plugged-in clean USB. macOS administrator authorization completed, but raw disk open failed with Operation not permitted.",
+ "result": "Source hash and device identity verified; disk unmounted; dd failed before writing; original volume remounted. User offered Etcher or disk-access troubleshooting.",
+ "local_iso": "~/Downloads/programmer-os-0.1.0-preview.2-x86_64.iso",
+ "public_receipt": false,
+ "etcher": {
+ "installed_version": "2.1.7",
+ "path": "/Applications/balenaEtcher.app",
+ "computer_use": "cua.getApp rejected access: Computer Use was not approved to use balenaEtcher. No alternate UI route used.",
+ "user_observed_error": "Error opening source: (0 , h.requestMetadata) is not a function",
+ "iso_recheck": "Downloads ISO matches released source: 1525678080 bytes, SHA-256 7eae886e3f9a77cc5831fae591d4de1f095ff16e43a412f0c714a09042b933d2",
+ "diagnosis": "macOS crash report confirms etcher-util ARM64 aborted at startup in V8 Heap::SetUp/FatalProcessOutOfMemory. Installed helper has an empty entitlement dictionary. Upstream 2.1.7 hardening commit 26ad031b removed the helper JIT entitlements. This suggests a packaging regression; no OS image or USB write was reached by that helper.",
+ "workaround": "Official 2.1.6 ARM64 DMG downloaded to ~/Downloads/balenaEtcher-2.1.6-arm64.dmg and verified against GitHub asset SHA-256 ecf71fb5e74803ea8d7d16c54378a6a8d964e9808594b867c088222a8cfe3d2b. User instructed to quit 2.1.7 and replace it through Finder. GUI success remains unverified."
+ }
+ },
+ "publication_attempts": [
+ {
+ "result": "Draft created; seven small assets uploaded; ISO upload failed with TLS handshake timeout",
+ "evidence": "os/work/release-preview2/publication.log"
+ },
+ {
+ "result": "Bounded ISO-only upload retry completed; all eight GitHub asset sizes and SHA-256 digests match local verified assets",
+ "evidence": "os/work/release-preview2/upload-retry.log"
+ },
+ {
+ "result": "Existing draft published; all eight anonymous public downloads verified by full size and SHA-256",
+ "evidence": "os/work/release-preview2/public-verification.log"
+ }
+ ],
+ "publication_verified_utc": "2026-10-03T07:07:19.173864+00:00",
+ "publication_receipt": "os/work/release-preview2/publication.json",
+ "publication_completion_reported_utc": "2026-10-03T07:09:06.191273+00:00",
+ "installation_guide": "os/INSTALL.md",
+ "documentation_validation": "Relative Markdown links and code fences; static page assets, anchors, fonts and image dimensions; JSON; git diff --check passed. Local page visual review remains blocked.",
+ "elapsed_seconds": {
+ "first_implementation_action_to_verified_publication": 6428.174,
+ "implementation": 1440.773,
+ "required_validation": 1672.148,
+ "artifact_transfer_and_release_preparation": 827.507,
+ "publication_including_failed_transfer_retry_and_public_downloads": 2487.667,
+ "merge": null
+ },
+ "waiting": [
+ {
+ "started_utc": "2026-10-03T05:56:33.447257Z",
+ "ended_utc": "2026-10-03T05:58:26Z",
+ "reason": "One bounded retry after Arch package/signature download timeout; source unchanged."
+ },
+ {
+ "started_utc": "2026-10-03T06:12:04Z",
+ "ended_utc": "2026-10-03T07:07:19.173864+00:00",
+ "reason": "Artifact transfer, publication upload/TLS timeout and retry, then public download verification. Documentation and USB/Etcher troubleshooting continued during transfer waits. This overlaps publication and is not subtracted from total elapsed."
+ }
+ ]
+ }
+ },
+ "published_version": "0.1.0-preview.3",
+ "latest_publication": {
+ "version": "0.1.0-preview.4",
+ "source_commit": "21aa5de0bd1a9a8a21cb4be06f83bf65c072a1b8",
+ "release_url": "https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.4",
+ "published_at": "2026-10-03T12:03:40Z",
+ "verified_at": "2026-10-03T12:04:09.527570+00:00",
+ "verified_assets": [
+ "boot-layout.txt",
+ "harness-0.1.0-preview.4-x86_64.iso",
+ "harness-0.1.0-preview.4-x86_64.iso.sha256",
+ "harness-examples.zip",
+ "inspection.json",
+ "INSTALL.md",
+ "machine-evidence.zip",
+ "manifest.json",
+ "packages.txt",
+ "validation.json"
+ ],
+ "receipt": "os/work/release-preview4-37119543543/publication-ci/publication.json",
+ "verification_run": "https://github.com/autonomous-ai/openharness/actions/runs/37121570059"
+ },
+ "physical_thinkpad": {
+ "live_boot": {
+ "status": "passed by user report",
+ "reported_utc": "2026-10-03T07:19:35.550371+00:00",
+ "evidence": "User: ok i boot sucessfully and now in hn",
+ "model": "not yet provided",
+ "scope": "USB reaches hn on a physical ThinkPad; installation, encrypted disk boot, network and suspend not yet verified"
+ },
+ "installation": "Passed by user report using the explicit RAM-image --source workaround; user confirms shutdown, USB removal and successful boot into hn from the internal disk. Encryption choice and hardware model remain unknown.",
+ "workaround_result": {
+ "recorded_utc": "2026-10-03T07:47:40.256187+00:00",
+ "evidence": "User: yeah it works i'm in hn now but there are a few issues",
+ "status": "workaround passed by user report; remaining issue details pending"
+ },
+ "installed_boot": {
+ "status": "passed by user report",
+ "recorded_utc": "2026-10-03T07:49:33.368095+00:00",
+ "evidence": "User answered Yes, booted with USB removed to the internal-disk boot question.",
+ "limitations": "Further issues reported; user will describe them later. No physical performance, Wi-Fi, suspend or NVIDIA measurements established."
+ }
+ },
+ "resumed_goal_audit": {
+ "started_utc": "2026-10-03T07:19:35.550371+00:00",
+ "previous_turn_classification": "progress: preview 2 published and every public asset verified; complete manual guide delivered; Etcher startup failure diagnosed and official workaround downloaded",
+ "status": "Console fallback and RAM-copy installer fix validated and published. Physical installation/internal-disk boot passed by user report; remaining hardware issue details pending.",
+ "next_work": "Investigate the physical ThinkPad issues when described; retain unverified Wi-Fi, suspend, NVIDIA and local page/VM visual rows.",
+ "validation_plan": [
+ "Python and shell syntax for the test-only change",
+ "Native BIOS/plain and UEFI/encrypted machine workflow reusing image run 37101103529; no new ISO/runtime build or duplicate application unit suite"
+ ],
+ "runtime_source_unchanged": "a155a16850438e04315a1959b1bfd1c387d8bf99",
+ "new_runtime_verification_started_utc": "2026-10-03T07:20:27Z",
+ "new_runtime_verification_completed_utc": "2026-10-03T07:26:14.932472+00:00",
+ "console_fallback_run": {
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37106021765",
+ "status": "passed",
+ "test_source_commit": "89836662a54e27d01aaf01d1f27b9d68fd7e68d5",
+ "image_source_commit": "a155a16850438e04315a1959b1bfd1c387d8bf99",
+ "scope": "Both firmware paths: forced compositor failure, real tty1 keyboard input through hn, original work survives, graphics restored; all existing installation/recovery and applicable agent checks also passed.",
+ "visual_review": "Inspected BIOS tty1 screenshot with typed ready input, and UEFI restored fullscreen hn screenshot; both show working terminal surfaces."
+ }
+ },
+ "ram_copy_installer_fix": {
+ "recorded_utc": "2026-10-03T07:32:02.276978+00:00",
+ "request_started_utc": null,
+ "request_time_basis": "User reported the physical USB error in the active turn; exact message timestamp unavailable.",
+ "implementation_ready_utc": "2026-10-03T07:34:37.125072+00:00",
+ "source_version": "0.1.0-preview.3",
+ "published_version": "0.1.0-preview.3",
+ "cause": "Archiso 73 automatically copies a USB root image into RAM when it has enough free memory, then removes bootmnt. The installer only knew the bootmnt path. Previous native tests used virtual optical discs, where automatic RAM copying is disabled.",
+ "changes": [
+ "Detect both copytoram and bootmnt before collecting passwords; explicit missing source fails without fallback.",
+ "Reject the HN_OS ISO medium even after RAM boot unmounts it.",
+ "Test a 16 GiB writable virtual USB backed by a private qcow2 overlay, at 4 GiB guest memory, so actual automatic RAM boot and boot-device exclusion are exercised."
+ ],
+ "validation_plan": [
+ "24 affected installer tests, portable syntax and diff checks",
+ "Pinned actionlint in the fresh image workflow",
+ "Fresh source image build, payload inspection and original BIOS/plain plus UEFI/encrypted machine gates",
+ "Reuse that exact image for both firmware modes booted from a writable virtual USB at 4096 MiB; require RAM payload, excluded live medium, actual offline installation/reboot/recovery",
+ "Publish immutable preview 3 only after all required gates pass and public assets verify"
+ ],
+ "local_installer_tests": "24 passed",
+ "native_validation_started_utc": "2026-10-03T07:34:41Z",
+ "native_validation_completed_utc": "2026-10-03T07:49:43Z",
+ "merge_utc": null,
+ "publication_utc": "2026-10-03T07:53:11Z",
+ "local_validation": {
+ "result": "39 portable tests and Python/JSON/XML/shell syntax passed; git diff --check passed",
+ "recorded_utc": "2026-10-03T07:34:37.125072+00:00",
+ "source_sha256": {
+ "os/installer.py": "ac844e24cf50256b43bf7ec5aa9cdd6a54bc2bcba8ab174c120a830c76800578",
+ "os/tests/test_installer.py": "a50a5a7bee2c9c0f2b9ec3d2775c89a9d89ed0826c2acd9deb9cdc4d56f96f07",
+ "os/tests/vm.py": "bf6828befe0a8f5945471207178507958ee989e771c3d50755ee7ac845179920",
+ ".github/workflows/os.yml": "3a47cdb4695facdef02e74b0b825d49de8dd893498387c2e30d394e8f18f783b",
+ "os/lock.json": "55dbc169ebc74eadd4a99c83839b3c9f92c84238a46aa7fd8f689c8365c89399"
+ },
+ "coverage": "Installer/unit source unchanged since the passed run; final QEMU removable-device flag is verified against local device help and requires the native USB run. Workflow actionlint runs in the build job."
+ },
+ "source_commit": "bbf6442d9c62fc8a4e9ad9acf5668159f35c99f0",
+ "native_run_id": 37106807986,
+ "native_run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37106807986",
+ "usb_run_id": 37107310576,
+ "usb_run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37107310576",
+ "usb_validation_started_utc": "2026-10-03T07:43:51Z",
+ "next_step": "Published installer fix complete. Await reported ThinkPad issue details and continue physical hardware acceptance; local page visual/keyboard verification remains unavailable.",
+ "publication_trigger_utc": "2026-10-03T07:51:39Z",
+ "publication_verified_utc": "2026-10-03T07:53:47.799570+00:00",
+ "publication_run_id": 37107746318,
+ "publication_run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37107746318",
+ "publication_receipt": "os/work/release-preview3/publication-ci/publication.json",
+ "native_validation_result": "All required exact-source checks passed: 39 portable tests, pinned actionlint, CLI typecheck/affected tests, 335 hn unit tests (one benchmark ignored), ten native terminal fixtures, ISO inspection, optical BIOS/plain and UEFI/encrypted machine tests, and writable USB RAM-copy BIOS/plain and UEFI/encrypted tests.",
+ "machine_checks": {
+ "optical_2gib": {
+ "bios_plain": 20,
+ "uefi_encrypted": 19
+ },
+ "usb_4gib": {
+ "bios_plain": 22,
+ "uefi_encrypted": 21
+ }
+ },
+ "measurements": [
+ {
+ "mode": "cdrom",
+ "firmware": "bios",
+ "memory_mib": 2048,
+ "install_seconds": 33.764,
+ "boot_seconds": 17.509,
+ "unlock_wait_seconds": 0,
+ "idle_mib": [
+ 398.02,
+ 397.88,
+ 397.77
+ ],
+ "idle_cpu_percent": [
+ 0.75,
+ 0.25,
+ 0.0
+ ],
+ "root_gib": [
+ 1.9095,
+ 1.9103,
+ 1.9103
+ ]
+ },
+ {
+ "mode": "cdrom",
+ "firmware": "uefi",
+ "memory_mib": 2048,
+ "install_seconds": 47.013,
+ "boot_seconds": 111.998,
+ "unlock_wait_seconds": 100,
+ "idle_mib": [
+ 403.73,
+ 403.73,
+ 407.73
+ ],
+ "idle_cpu_percent": [
+ 1.5,
+ 0.25,
+ 0.25
+ ],
+ "root_gib": [
+ 1.9395,
+ 1.9395,
+ 1.9395
+ ]
+ },
+ {
+ "mode": "usb",
+ "firmware": "bios",
+ "memory_mib": 4096,
+ "install_seconds": 34.698,
+ "boot_seconds": 18.067,
+ "unlock_wait_seconds": 0,
+ "idle_mib": [
+ 471.6,
+ 471.71,
+ 469.92
+ ],
+ "idle_cpu_percent": [
+ 0.5,
+ 0.5,
+ 0.0
+ ],
+ "root_gib": [
+ 1.9664,
+ 1.9672,
+ 1.9672
+ ]
+ },
+ {
+ "mode": "usb",
+ "firmware": "uefi",
+ "memory_mib": 4096,
+ "install_seconds": 42.136,
+ "boot_seconds": 111.029,
+ "unlock_wait_seconds": 100,
+ "idle_mib": [
+ 510.91,
+ 510.62,
+ 513.75
+ ],
+ "idle_cpu_percent": [
+ 0.75,
+ 0.25,
+ 0.25
+ ],
+ "root_gib": [
+ 1.9338,
+ 1.9338,
+ 1.9338
+ ]
+ }
+ ],
+ "visual_review": "Reviewed actual BIOS installed hn home and local development browser screenshots. UEFI installed/recovered captures show early startup states; live-session operation, installed readiness and recovery are covered by the passing machine checks. No completed UEFI home screenshot is claimed.",
+ "elapsed_seconds": {
+ "request_to_completion": null,
+ "first_recorded_fix_to_public_verification": 1305.523,
+ "implementation_recorded_interval": 154.848,
+ "native_validation": 902.0,
+ "artifact_review_and_publication_preparation": 116.0,
+ "publication_and_full_public_download_verification": 128.8,
+ "merge": null
+ },
+ "waiting": [
+ {
+ "started_utc": "2026-10-03T07:34:41Z",
+ "ended_utc": "2026-10-03T07:49:43Z",
+ "reason": "Fresh image and two parallel native VM environments; user workaround support and documentation continued."
+ },
+ {
+ "started_utc": "2026-10-03T07:43:51Z",
+ "reason": "Optional local ISO mirror was slow and was cancelled after roughly ten minutes. Publication proceeded in CI, which verified every public asset; no duplicate full local download is required. Exact cancellation timestamp was not recorded.",
+ "recorded_utc": "2026-10-03T08:00:05.732467+00:00",
+ "ended_utc": null
+ }
+ ],
+ "documentation_validation": {
+ "recorded_utc": "2026-10-03T08:03:04.680531+00:00",
+ "result": "Passed local HTML/CSS assets and fonts, fragment targets, PNG dimensions, public asset names, Markdown file links/fences, JSON and git diff --check. Current BIOS screenshot inspected. Full local page visual/keyboard validation remains unverified."
+ }
+ },
+ "keyboard_readiness_audit": {
+ "started_utc": "2026-10-03T08:05:05Z",
+ "previous_goal_turn": "progress: preview 3 USB fix published and all public assets verified; user confirmed successful physical installation and internal-disk boot with USB removed.",
+ "requirement": "Boot into a usable hn surface; test keyboard input through the graphical session rather than only service/process readiness.",
+ "finding": "hn displays Finding your harnesses for the first three seconds on an empty initial session. Earlier installed/recovered screenshots can catch this or the initial tmux notice. No persistent UI failure is established by those captures.",
+ "image_source_commit": "bbf6442d9c62fc8a4e9ad9acf5668159f35c99f0",
+ "image_run_id": 37106807986,
+ "implementation_ready_utc": "2026-10-03T08:10:55.937569+00:00",
+ "test_script_sha256": "af7981eac1f5e3a39bdac751df44fb83547e2dd66261e8c6057f1e3850e9a049",
+ "validation_plan": [
+ "Portable tests and syntax/whitespace for test-runner change",
+ "Reuse the exact published preview 3 ISO in one BIOS/plain and UEFI/encrypted writable-USB machine workflow; no runtime rebuild or redundant Rust/CLI suite",
+ "Type a unique echo command through the physical VM keyboard after installed and recovered boot; verify standalone response in the hn pane, capture its framebuffer, close the shell through Ctrl+D and capture returned home",
+ "Record process readiness and keyboard-confirmed readiness separately, including automated typing overhead; inspect final screenshots"
+ ],
+ "local_validation": "39 portable tests and Python/JSON/XML/shell syntax passed; git diff --check passed",
+ "native_status": "passed",
+ "remaining_physical_work": "ThinkPad issue details promised by user; Wi-Fi, suspend and GPU evidence still unavailable.",
+ "test_source_commit": "909ca1ac43654875c256a024406d6f87ddc823eb",
+ "native_run_id": 37108853927,
+ "native_run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37108853927",
+ "native_validation_started_utc": "2026-10-03T08:11:19Z",
+ "native_validation_completed_utc": "2026-10-03T08:18:10Z",
+ "visual_review_utc": "2026-10-03T08:28:25.074631+00:00",
+ "visual_review": "Installed and recovered terminal screenshots show the physical-keyboard probe and response in both firmware modes; installed home screenshots show hn after closing the pane.",
+ "measurements": {
+ "uefi-encrypted": {
+ "installed_keyboard_readiness": {
+ "confirmed_seconds_since_boot": 118.341,
+ "probe_seconds_including_automated_typing": 6.057
+ },
+ "recovered_keyboard_readiness": {
+ "confirmed_seconds_since_boot": 18.086,
+ "probe_seconds_including_automated_typing": 6.053
+ }
+ },
+ "bios-plain": {
+ "installed_keyboard_readiness": {
+ "confirmed_seconds_since_boot": 25.056,
+ "probe_seconds_including_automated_typing": 6.045
+ },
+ "recovered_keyboard_readiness": {
+ "confirmed_seconds_since_boot": 24.67,
+ "probe_seconds_including_automated_typing": 6.042
+ }
+ }
+ },
+ "limitations": "Encrypted installed boot includes the intentional 100-second password delay. Readiness times include about six seconds of automated typing. These are VM observations, not ThinkPad boot measurements."
+ },
+ "usb_first_use_revision": {
+ "request_received_utc": null,
+ "first_recorded_utc": "2026-10-03T08:28:25.074631+00:00",
+ "status": "Published and verified: all ten assets include matching guide, image, examples, inspection and machine evidence.",
+ "implementation_complete_utc": "2026-10-03T11:24:15.435201+00:00",
+ "validation_complete_utc": "2026-10-03T11:43:29Z",
+ "publication_utc": "2026-10-03T12:03:40Z",
+ "requirements": [
+ "Product name Harness; live and installed hostname harness",
+ "Try launches bundled OpenCode; when disconnected offer network setup first; install remains usable offline",
+ "Keep terminal available, other agents installed on demand, and normal work restoration after install",
+ "USB account me and hostname harness; remove Programmer OS from visible product branding",
+ "New terminal opens a shell immediately; retain an existing agent draft without sending its task to the shell",
+ "sudo harness install is the command equivalent of the direct Install action",
+ "Installer has four aligned fields: Disk, Encryption, Password, Repeat password; no account text, password minimum length, decorative separators or navigation-hint clutter",
+ "Single-line disk choices include the device path on the same line; Install starts directly with no second confirmation; keep one inline disk-erasure disclosure",
+ "Encrypted boot should show Harness branding and a friendly masked password prompt before entering hn",
+ "Keyboard-first interface with optional mouse support; hide pointer while typing",
+ "USB welcome prioritizes Enter = Install Harness; T = Try without installing. Network setup is only required by Try, never by offline installation.",
+ "Bundle OpenCode with its upstream default setup. Do not pin any specific model or override its model selection. Verify its actual clean first launch.",
+ "Ordinary hn on macOS or other Linux must retain its regular interface. Installation UI and actions are exclusive to the live OS session; installed Harness never offers Install."
+ ],
+ "validation_plan": [
+ "Portable installer safety and first-use helper tests, shell/Python/JSON/XML syntax and workflow lint",
+ "Affected TUI tests and full native TUI suite in the exact image build; existing CLI typecheck/engine install and launch checks",
+ "Inspect actual SquashFS for bundled signed OpenCode package, live marker/account and exact runtime",
+ "Boot USB with BIOS/plain and UEFI/encrypted; physically activate Wi-Fi, Try, Install and direct terminal; verify single-form offline install, friendly encrypted unlock, and removal of live-only actions after install",
+ "Clean-profile real free-model turn with bundled OpenCode and old-CPU startup check; distinguish virtual network checks from physical Wi-Fi",
+ "Inspect screenshots; verify published assets using the existing publication receipt without duplicate full downloads",
+ "Explicit normal hn / installed OS / live USB render and action regressions, including stray live flag and modified keys"
+ ],
+ "waiting": [
+ {
+ "started_utc": "2026-10-03T11:36:33Z",
+ "ended_utc": null,
+ "reason": "Local 1.6 GB image artifact download still active; small machine evidence already downloaded. CI publication uses its own artifact transfer and is not blocked by this local download."
+ }
+ ],
+ "local_validation": {
+ "completed_utc": "2026-10-03T10:29:26.198461+00:00",
+ "toolchain": "Node 22.23.2, tmux 3.7c on macOS arm64",
+ "affected_cli": "273 passed, 1 Linux-only test skipped; 10 test files.",
+ "real_tmux": "20 passed, 9 unavailable/non-agent rows skipped; Claude Code 2.1.287, Codex 0.160.0, OpenCode 1.18.34, pi 0.85.1, Hermes 0.18.0 and Grok 1.0.44 discovered; Grok agent alias, restart and shell lifecycle passed. No model turns.",
+ "portable_os": "51 tests plus Python/JSON/XML/shell syntax and git diff --check passed. Three disposable DSH manifests generated with no --agent or model override.",
+ "initial_receipt": ".harness/validation/20261003T102725.582029Z-2586/receipt.json",
+ "initial_failure": "Typecheck rejected a possibly undefined Stats mock value; guarded it. Product runtime sources unchanged after passed affected and real tmux checks.",
+ "followup_receipt": ".harness/validation/20261003T102818.737073Z-15548/receipt.json",
+ "followup": "Typecheck and exact-inode regression passed (3 tests, 1 Linux-only skip).",
+ "limitations": "OpenCode 2 plugin startup and OverlayFS behavior still require fresh Linux image verification; full CLI CI pending."
+ },
+ "implemented_in_source": [
+ "Install-first live welcome and direct system shortcuts",
+ "Harness branding and me@harness live identity",
+ "Direct terminal action in the chooser, preserving the agent draft",
+ "Single-form installer and harness install alias",
+ "Signed snapshot OpenCode package input, with no custom OpenCode configuration",
+ "NetworkManager keyboard UI and connection check before trying OpenCode",
+ "foot hide-when-typing enabled",
+ "Five-line ASCII Harness Plymouth theme for encrypted boot; standard systemd/Plymouth password handling, awaiting boot verification",
+ "Fresh installed home offers Start OpenCode, New terminal and Wi-Fi; live-only Install action removed after installation"
+ ],
+ "remaining": [
+ "Physical ThinkPad test of preview 4 Wi-Fi, suspend, brightness and actual boot time",
+ "NVIDIA/local AI validation on real GPU hardware",
+ "Reliable Mac emulation and landing-page interactive review; current site permission still blocks the latter"
+ ],
+ "native_run_id": 37116595898,
+ "native_run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37116595898",
+ "source_commit": "67958156da30d2983daee22ddab48c43970fa244",
+ "native_validation_started_utc": "2026-10-03T10:29:41Z",
+ "validation_attempts": [
+ {
+ "run_id": 37111342650,
+ "source_commit": "11a8010acc9491356eaa3a45d295638277660627",
+ "started_utc": "2026-10-03T08:56:02Z",
+ "failed_utc": "2026-10-03T09:00:42Z",
+ "result": "failed: native New Harness fixture looked for literal Agent|Harness because field_position escaped its regular expression",
+ "passed": "45 portable tests, workflow lint, exact runtime build, CLI typecheck, 89 affected CLI tests (1 skipped), 336 Rust tests (1 ignored), 9 of 10 native fixtures",
+ "remedy": "Use the same field pattern convention in field_position and field_at; rerun affected native behavior as part of image validation"
+ },
+ {
+ "run_id": 37112220215,
+ "source_commit": "0b3073e6ad6dc5a25858b48a088bbf9c19b4770e",
+ "started_utc": "2026-10-03T09:11:39Z",
+ "failed_utc": "2026-10-03T09:20:31Z",
+ "result": "ISO generated but artifact inspection failed: symbolic-link target text was included in the ownership-map path for nmtui-connect",
+ "passed": "45 portable tests, workflow lint, exact runtime build, CLI typecheck, 89 affected CLI tests (1 skipped), 337 Rust tests (1 ignored), all 10 native fixtures",
+ "remedy": "Parse the link path separately from its target. Confirmed nmtui-connect -> nmtui in the exact snapshot NetworkManager package, whose SHA-256 matches the snapshot database. Still require root ownership and both target and alias. Includes pending hook branding and publication-guard updates in the next source."
+ },
+ {
+ "run_id": 37112874271,
+ "source_commit": "7fc8c9c2294254b608fadb7a1060f5a749f090ae",
+ "started_utc": "2026-10-03T09:23:17Z",
+ "failed_utc": "2026-10-03T09:37:17Z",
+ "result": "Both machine journeys stopped at first-use identity assertion: hostname command is absent from the minimal image. Serial prompt already shows harness, but remaining identity assertions and first-use journeys did not run.",
+ "passed": "Image job including portable checks, native CLI/TUI checks, all native fixtures, ISO build and SquashFS inspection.",
+ "remedy": "Read kernel hostname with existing coreutils uname -n; no package added. Rebuild latest source to include separately added installer completion screen, then rerun BIOS/plain and UEFI/encrypted journeys."
+ },
+ {
+ "run_id": 37113924838,
+ "source_commit": "ca24088bae5e648becabdfa3f4c150059e038c53",
+ "started_utc": "2026-10-03T09:41:57Z",
+ "failed_utc": "2026-10-03T09:57:17Z",
+ "result": "Both machine journeys stopped after Ctrl+B T / Ctrl+D: the shortcut used the generic agent launch path and left a closed-terminal card. Try never received its key, so OpenCode did not launch.",
+ "passed": "Image build and inspection; native CLI/TUI checks including all ten fixtures. Both VMs passed live identity, offline bundled OpenCode version (including Nehalem), disconnected Try/network UI, offline Install/cancel and physical input in a new terminal.",
+ "remedy": "Use the owned shell path for the New terminal shortcut, matching the chooser. Add native stream-exit regression and an actual VM pane-disappearance assertion. Also retain interactive installer errors until acknowledgement."
+ },
+ {
+ "run_id": 37115159220,
+ "source_commit": "5445fe1ff1ba178c276735a05a79046a09db1a1f",
+ "result": "Both VMs failed: model check inherited /root, which me cannot enter. Earlier first-use steps passed; screenshots also exposed an incompatible OpenCode 1 plugin.",
+ "passed": "Live identity, bundled OpenCode on Nehalem, disconnected Try/network setup, offline Install/cancel, retained installer error, direct terminal input and Ctrl+D pane removal, actual OpenCode 2 TUI with upstream default model.",
+ "remedy": "Run model acceptance from ~/Projects. Select discovery plugins by OpenCode major version and remove only Harness-owned incompatible legacy files."
+ },
+ {
+ "run_id": 37115791048,
+ "source_commit": "06e268bc38b564aa79b6800f1507d5737a3e53da",
+ "image_run_id": 37115159220,
+ "result": "Both VMs failed at the same model-check cwd error; workload acceptance did not run. Diagnostics confirmed rounded OverlayFS inode IDs map Bash/Python to OpenCode.",
+ "remedy": "Use bigint stat and unsigned 64-bit inode keys. Assert no agent appears before one has been started."
+ },
+ {
+ "run_id": 37115793973,
+ "source_commit": "06e268bc38b564aa79b6800f1507d5737a3e53da",
+ "image_run_id": 37115159220,
+ "result": "Both VMs failed at the same model-check cwd error; DSH acceptance did not run."
+ },
+ {
+ "run_id": 37116595898,
+ "source_commit": "67958156da30d2983daee22ddab48c43970fa244",
+ "result": "Both VMs failed only at first-use cleanup: the test incorrectly required OpenCode 2 shared service to exit along with the TUI.",
+ "passed": "Live executable identities no longer conflate Bash/Python with agents; actual OpenCode TUI starts without the plugin error; both default clean-profile model calls returned 42. Both screenshots show return to the USB welcome after closing the TUI.",
+ "remedy": "Verify disappearance of the exact interactive pane, not every process named opencode. Test-only correction; reuse the verified image/runtime."
+ },
+ {
+ "scope": "four programmer projects plus complete BIOS/UEFI USB journey",
+ "run_id": 37117491184,
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37117491184",
+ "started_utc": "2026-10-03T10:46:10Z",
+ "memory_mib": 4096,
+ "image_run_id": 37116595898,
+ "image_source_commit": "67958156da30d2983daee22ddab48c43970fa244",
+ "test_source_commit": "5001600ca051e07152be9000b2470512ebddb5c4",
+ "status": "failed",
+ "result": "UEFI complete journey passed. All four agents completed and project unit tests passed; independent game browser check wrongly assumes a .legend class absent from the task contract. Website and fullstack browser/API checks passed."
+ },
+ {
+ "scope": "three DSH exercises plus complete BIOS/UEFI USB journey",
+ "run_id": 37117493096,
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37117493096",
+ "started_utc": "2026-10-03T10:46:12Z",
+ "memory_mib": 4096,
+ "image_run_id": 37116595898,
+ "image_source_commit": "67958156da30d2983daee22ddab48c43970fa244",
+ "test_source_commit": "5001600ca051e07152be9000b2470512ebddb5c4",
+ "status": "passed",
+ "result": "Both complete USB installation/recovery journeys passed, plus three real default-model DSH exercises and shared viewer checks."
+ },
+ {
+ "scope": "constrained complete BIOS/UEFI USB journey and bundled default-model chat",
+ "run_id": 37117494883,
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37117494883",
+ "started_utc": "2026-10-03T10:46:14Z",
+ "memory_mib": 1024,
+ "image_run_id": 37116595898,
+ "image_source_commit": "67958156da30d2983daee22ddab48c43970fa244",
+ "test_source_commit": "5001600ca051e07152be9000b2470512ebddb5c4",
+ "status": "failed",
+ "result": "Both 1 GiB installations exhausted memory during unsquashfs extraction; kernel killed the extractor (about 384\u2013441 MiB resident plus swap). First live model conversations passed."
+ }
+ ],
+ "isolation_revision_ready_utc": "2026-10-03T09:11:28.017223+00:00",
+ "positioning": "Harness is built around agents as the primary interface: conversation directs work; terminal output, diffs and browser make results inspectable. Programmers first; broader uses later. Product name remains Harness.",
+ "post_build_source_changes": [
+ "Test-only: operate the visible default OpenCode TUI through virtual keyboard input and require its reply; publication guard now requires that evidence. Runtime and image source remain 67958156d.",
+ "Test-only cleanup uses the exact interactive pane id; preserves the real OpenCode 2 shared service lifecycle. Portable 51 tests/syntax passed."
+ ],
+ "post_build_local_checks": "31 installer tests passed; changed Python files compile and git diff --check passed. Native terminal regression and updated machine journey require the new source build.",
+ "native_validation_complete_utc": null,
+ "isolation_validation": "Normal hn (including a stray live flag), installed OS and live USB UI/action regression tests passed in run 37112220215. The native terminal lifecycle validation step, including all ten fixtures, passed on source 0b3073e6ad6dc5a25858b48a088bbf9c19b4770e.",
+ "pending_source_changes": [
+ "Cap unsquashfs extraction caches at 64 MiB instead of the packaged default 512 MiB. Both 1 GiB failures show kernel OOM killing this process. Real low-memory installation must rerun on the resulting image.",
+ "Locate generated game controls by their visible keyboard instructions, not an undocumented .legend CSS class. All previous model-built project tests remain recorded; independent browser acceptance must rerun.",
+ "Keep tty0 as the primary console when an unattended test enables serial logging; normal install kernel arguments are unchanged."
+ ],
+ "branding_review": {
+ "status": "approved and documented",
+ "sources": [
+ "https://github.com/autonomous-ai/autonomous-computer",
+ "https://github.com/autonomous-ai/autonomous-grid",
+ "docs/terminology.md",
+ "README.md#harness-device",
+ "devices/harness-device/firmware/README.md"
+ ],
+ "photos": "User supplied five square-device / monitor / compute-box concepts. Device has Harness/TUI voice and navigation, browser keyboard and pointer controls. These are design concepts, not evidence of implemented square-device integration.",
+ "confirmed": [
+ "Product name Harness; programmer OS is audience shorthand only",
+ "Bring your own computer remains supported; first-party computer/device combination is optional",
+ "Ordinary hn on macOS and other Linux does not expose OS installation actions"
+ ],
+ "open": [
+ "Final device variant names and exact integration scope",
+ "Local-model out-of-box claim requires tested drivers, inference engine and model provisioning; these are not currently bundled in the minimal ISO",
+ "Assessment file supplied under /Users/d is unavailable on this Mac; requested accessible path or GitHub link"
+ ],
+ "document": "docs/naming-system.md",
+ "approved_date": "2026-10-03",
+ "documentation": {
+ "request_received_utc": null,
+ "implementation_ready_utc": "2026-10-03T09:55:05.452913+00:00",
+ "validation_completed_utc": "2026-10-03T09:55:05.452913+00:00",
+ "validation": "Reviewed approved vocabulary, checked local Markdown links and fences in all eight touched documents, and passed git diff --check. Documentation only; no runtime suite required.",
+ "merge_utc": null,
+ "publication_utc": null
+ }
+ },
+ "next_step": "Build and inspect a fresh exact-source image with bounded extraction caches and corrected diagnostic console order; run native 4 GiB and constrained 1 GiB installation/recovery and project/DSH acceptance. Reuse passed full CLI evidence because CLI/TUI sources and dependencies are unchanged.",
+ "last_recorded_utc": "2026-10-03T11:39:35.289044+00:00",
+ "first_use_visual_review": "Inspected BIOS 01d-bundled-opencode.png and failure.png from run 37116595898: upstream-default Fledge Alpha Free is shown without a plugin warning; after Ctrl+C twice, the clean Harness Install/Try welcome is visible. Both firmware JSONL replies are 42. The retained process in each is /usr/bin/opencode serve --service.",
+ "revision_ready_utc": "2026-10-03T10:29:26.198461+00:00",
+ "development_acceptance_revision": {
+ "status": "prepared; syntax and fixture generation passed; real guest runs pending",
+ "reason": "The bundled OpenCode first-use route must also support the requested programmer and DSH workflows with upstream model defaults.",
+ "changes": [
+ "Removed hardcoded model arguments/configuration from the disposable workload and DSH fixtures; kept their task permissions and independent acceptance checks.",
+ "Prepared a preview 4 manual installation guide at os/work/preview4-INSTALL.md; current public guide remains preview 3 until publication.",
+ "Added read-only live file-identity and registry diagnostics to investigate terminal rows appearing as OpenCode before an agent is launched. No discovery change is made without evidence.",
+ "Removed the unused custom primary agent and unsupported OpenCode 2 interactive --agent flag from DSH fixtures; test permissions remain scoped to the disposable guest."
+ ],
+ "required_checks": [
+ "Bash/Python syntax and disposable DSH fixture generation",
+ "After the base image journeys pass, run four project workloads and three DSH tasks on that exact ISO using the default model; keep those scopes in separate bounded VM runs."
+ ],
+ "validation_started_utc": "2026-10-03T10:13:49.119774+00:00"
+ },
+ "native_validation": "Run 37115159220 passed CLI typecheck, 89 affected CLI tests (1 skipped), 337 Rust tests (1 ignored), all 10 native fixtures, image assembly and SquashFS inspection. Both VM journeys failed at the default chat test before installation.",
+ "last_image": {
+ "run_id": 37119543543,
+ "source_commit": "21aa5de0bd1a9a8a21cb4be06f83bf65c072a1b8",
+ "iso": {
+ "name": "harness-0.1.0-preview.4-x86_64.iso",
+ "bytes": 1612300288,
+ "sha256": "d111c2127e503818e4fccba62b8460e6160063bbf3b48e004e51516416229a92"
+ },
+ "status": "Image build and actual SquashFS inspection passed; 337 native tests passed with one ignored, ten terminal fixtures passed, affected CLI 89 passed with one skipped. Full CLI evidence reused from unchanged source. Machine validation pending.",
+ "publishable": false,
+ "manifest_from_log": "os/work/preview4-build-37119543543/manifest-from-build-log.json"
+ },
+ "current_validation_plan": [
+ "Pinned Node 22.23.2 typecheck and affected discovery, launch, hooks, plugin and version tests.",
+ "Private tmux 3.7c real discovery/restart/login-shell fixtures on this Mac; unavailable engines recorded as skipped.",
+ "Portable OS tests/syntax, workflow lint in image CI, full CLI CI including supported OS/Node matrix.",
+ "Fresh exact-source ISO and native TUI checks; both full USB machine journeys, then separate workload/DSH default-model acceptance against the same image.",
+ "Measure the constrained 1-GiB base and bundled default-agent journey after the 4-GiB RAM-copy journeys; preview 1 low-memory evidence does not cover the newly bundled OpenCode 2."
+ ],
+ "full_cli_ci": {
+ "run_id": 37116593867,
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37116593867",
+ "source_commit": "67958156da30d2983daee22ddab48c43970fa244",
+ "started_utc": "2026-10-03T10:29:38Z",
+ "status": "passed",
+ "passed_so_far": [
+ "Repository process checks",
+ "Linux and macOS native serial/login-shell matrix on Node 20.19.0 and 22.23.2"
+ ],
+ "result": "8761 full-suite tests passed, 62 skipped; 40 separately scheduled fuzz tests passed. Supported Linux/macOS Node matrix, release bundle migration and updater coverage checks passed; updater coverage reports 100%. No second full local suite required.",
+ "typecheck_test_job_completed_utc": "2026-10-03T10:35:28Z"
+ },
+ "browser_visual_review": {
+ "attempted_utc": "2026-10-03T10:38:15.965197+00:00",
+ "status": "blocked by saved site permission",
+ "tool": "cua.getTab",
+ "url": "http://127.0.0.1:18092/",
+ "reason": "Browser Use rejected the exact previously authorized URL because of a saved user permission setting. No alternate browser, raw CDP, or rendering workaround attempted.",
+ "impact": "Landing-page visual and interactive checks remain unverified; static source review and separate authorized CI guest VM work continue."
+ },
+ "low_memory_run": {
+ "run_id": 37117247900,
+ "image_run_id": 37116595898,
+ "test_source_commit": "e79f94fcb7e6a78e8250eea46da51c80017af8bf",
+ "memory_mib": 1024,
+ "started_utc": "2026-10-03T10:41:33Z",
+ "status": "failed at the known shared-service cleanup assertion; both actual keyboard conversations and independent JSONL replies passed before that assertion",
+ "visual_review": "Inspected BIOS and UEFI 01e-first-agent-reply.png: typed question and 42 reply are visible, upstream default free model, no plugin warning. This proves first-use chat at 1 GiB, not full installation or parallel project workloads."
+ },
+ "active_machine_runs": [
+ {
+ "scope": "1 GiB complete USB installation/recovery and actual first model chat",
+ "run_id": 37119543543,
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37119543543",
+ "started_utc": "2026-10-03T11:24:19Z",
+ "memory_mib": 1024,
+ "image_run_id": 37119543543,
+ "image_source_commit": "21aa5de0bd1a9a8a21cb4be06f83bf65c072a1b8",
+ "test_source_commit": "21aa5de0bd1a9a8a21cb4be06f83bf65c072a1b8",
+ "status": "passed",
+ "completed_utc": "2026-10-03T11:41:22Z"
+ },
+ {
+ "scope": "4 GiB RAM-copy install/recovery, retained four project sources and independent acceptance",
+ "run_id": 37120135497,
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37120135497",
+ "started_utc": "2026-10-03T11:35:21Z",
+ "memory_mib": 4096,
+ "image_run_id": 37119543543,
+ "image_source_commit": "21aa5de0bd1a9a8a21cb4be06f83bf65c072a1b8",
+ "test_source_commit": "ba221cbf993833f7cb6ffbacdd4fce4c0223787d",
+ "status": "passed",
+ "completed_utc": "2026-10-03T11:43:07Z"
+ },
+ {
+ "scope": "4 GiB RAM-copy install/recovery, three real DSH exercises and shared viewers",
+ "run_id": 37120138348,
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37120138348",
+ "started_utc": "2026-10-03T11:35:24Z",
+ "memory_mib": 4096,
+ "image_run_id": 37119543543,
+ "image_source_commit": "21aa5de0bd1a9a8a21cb4be06f83bf65c072a1b8",
+ "test_source_commit": "ba221cbf993833f7cb6ffbacdd4fce4c0223787d",
+ "status": "passed",
+ "completed_utc": "2026-10-03T11:43:29Z"
+ }
+ ],
+ "boot_performance_investigation": {
+ "image_run_id": 37116595898,
+ "evidence_run_id": 37117493096,
+ "uefi_initrd_seconds_including_100s_wait": 210.533,
+ "recovered_keyboard_ready_seconds": 116.847,
+ "status": "resolved in test instrumentation; exact new image passed",
+ "next_step": "No additional boot diagnostic run required. Measure the physical ThinkPad separately.",
+ "diagnostic_run_id": 37118718782,
+ "diagnostic_test_source": "6fe521be4d98a1ae1a0da0005f517632a54177ae",
+ "diagnostic_started_utc": "2026-10-03T11:08:47Z",
+ "diagnostic_status": "failed in diagnostic test pager; initial installed boot journal and timestamps retained",
+ "unlock_prompt_seconds": 97.764,
+ "password_submitted_seconds": 210.139,
+ "serial_login_seconds": 218.782,
+ "harness_ready_seconds": 220.004,
+ "finding": "Delay precedes the graphical prompt. The initrd journal shows serial-primary virtual console setup stalled around 30-second intervals. The test adds console=tty0 console=ttyS0; ordinary installation does not add a serial console. Change diagnostic argument order to keep tty0 primary and test the resulting image before attributing a physical-device regression.",
+ "diagnostic_fix": "Disable systemd-analyze paging, retain journals and boot-stage events, and enforce a sub-30-second unlock-prompt gate on native x86 VMs.",
+ "serial_console_reference": "https://www.kernel.org/doc/html/latest/admin-guide/serial-console.html",
+ "resolution": "Keep tty0 primary after the diagnostic serial console; ordinary installations never add serial output. New encrypted prompt is 4.9 seconds at 1 GiB and 4.6 seconds at 4 GiB. Password submission to Harness is 8.1/8.3 seconds including diagnostic login.",
+ "verified_run_id": 37119543543
+ },
+ "extraction_cache_reference": "https://github.com/plougher/squashfs-tools/blob/master/Documentation/4.7.5/USAGE-UNSQUASHFS",
+ "post_diagnostic_local_checks": {
+ "completed_utc": "2026-10-03T11:12:50.086227+00:00",
+ "result": "51 portable OS tests passed; Python/JSON/XML/shell checks and Node syntax for the browser acceptance script passed. Naming System relative links resolve. No new full CLI suite: CLI/runtime source is unchanged from passed run 37116593867."
+ },
+ "next_image_run": {
+ "run_id": 37119543543,
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37119543543",
+ "source_commit": "21aa5de0bd1a9a8a21cb4be06f83bf65c072a1b8",
+ "started_utc": "2026-10-03T11:24:19Z",
+ "status": "passed: image, native checks, 1 GiB BIOS/plain and UEFI/encrypted journeys",
+ "initial_machine_memory_mib": 1024,
+ "transport": "usb",
+ "required_followups": [],
+ "publishable": true
+ },
+ "previous_verified_image": {
+ "run_id": 37116595898,
+ "source_commit": "67958156da30d2983daee22ddab48c43970fa244",
+ "iso_bytes": 1612300288,
+ "iso_sha256": "52c14dd1aab5498141e260915798dd59c6f4d525115d86fd1fad8e9ffdaa328f",
+ "package_count": 405,
+ "native_validation": "337 Rust tests (1 ignored), 89 affected CLI tests (1 skipped), all 10 native TUI fixtures, portable tests, workflow lint and actual SquashFS inspection passed. Full CLI suite passed separately on the same runtime source.",
+ "manifest_from_log": "os/work/preview4-build-37116595898/manifest-from-build-log.json",
+ "publishable": false
+ },
+ "release_preparation": {
+ "at_utc": "2026-10-03T12:00:41.137169+00:00",
+ "status": "Complete; matching guide included and its public checksum matches the repository guide.",
+ "changes": [
+ "Include a version-matched INSTALL.md in the verified public asset set; reject a mismatched guide.",
+ "Use harness-examples.zip for this new preview; preserve historical artifact URLs.",
+ "Include installed/recovered boot journals with timing evidence.",
+ "New development/example test copy uses Harness."
+ ],
+ "validation": "52 portable OS tests, Python/JSON/XML/shell checks, git diff --check and static site/doc assets/links passed after final edits. Actual CI guest screenshots reviewed. Browser layout/interaction remains unverified due the saved permission block; no new full CLI/TUI suite required for these docs/packaging-only edits.",
+ "completed_utc": "2026-10-03T12:01:42.412522+00:00"
+ },
+ "final_machine_evidence": {
+ "iso_sha256": "d111c2127e503818e4fccba62b8460e6160063bbf3b48e004e51516416229a92",
+ "image_source_commit": "21aa5de0bd1a9a8a21cb4be06f83bf65c072a1b8",
+ "iso_bytes": 1612300288,
+ "package_count": 405,
+ "memory_1gib_idle_mib": [
+ 396.02,
+ 399.43
+ ],
+ "memory_4gib_idle_mib": [
+ 480.62,
+ 511.13
+ ],
+ "bios_install_seconds_1gib": 35.774,
+ "encrypted_install_seconds_1gib": 57.81,
+ "bios_install_seconds_4gib": 29.965,
+ "encrypted_install_seconds_4gib": 44.577,
+ "bios_boot_hn_seconds_4gib": 17.318,
+ "encrypted_prompt_seconds_4gib": 4.618,
+ "encrypted_password_to_hn_seconds_4gib": 8.299,
+ "project_checks": "31 unit tests and all independent keyboard/browser/API acceptance checks passed; three prior completed project sources reused, game agent ran again.",
+ "dsh_checks": "Three fresh default-OpenCode turns passed: HTML viewer edit/reload, CSV tool, game play/pause/reset/export.",
+ "visual_review": "Inspected actual welcome, installer, first typed reply, masked disk unlock, installed home, game, mobile website and DSH game-viewer screenshots.",
+ "public_receipt": "os/work/release-preview4-37119543543/publication-ci/publication.json"
+ },
+ "mac_compatibility": {
+ "verified_utc": "2026-10-03T12:00:41.137169+00:00",
+ "host_model": "Mac14,6",
+ "host_cpu": "Apple M2 Max",
+ "host_architecture": "arm64",
+ "iso_architecture": "x86_64",
+ "native_iso_install": "unsupported on this Apple Silicon Mac",
+ "native_app_and_tui": "macOS binaries available for arm64 and x64",
+ "vm_status": "Earlier emulation rendered a browser project, then reboot checks failed with guest soft-lockups. Preview 4 full Mac VM experience unverified."
+ },
+ "publication_trigger_utc": "2026-10-03T12:02:13Z",
+ "publication_run_id": 37121570059,
+ "publication_run_url": "https://github.com/autonomous-ai/openharness/actions/runs/37121570059",
+ "publication_source_commit": "1eb64ffe6e76505261f994fd2d530a8340f2a10c",
+ "merge_utc": null,
+ "publication_verified_utc": "2026-10-03T12:04:09.527570+00:00",
+ "publication_receipt": "os/work/release-preview4-37119543543/publication-ci/publication.json",
+ "publication_completion_reported_utc": "2026-10-03T12:05:00Z",
+ "publication_completion_reported_basis": "Approximate commentary time after live release and successful publication workflow were read; exact message timestamp unavailable.",
+ "elapsed_seconds": {
+ "first_recorded_work_to_verified_publication": 12944.453,
+ "implementation_and_overlapping_validation_or_diagnosis": 10550.361,
+ "final_machine_validation_after_implementation": 1153.565,
+ "evidence_review_and_docs_packaging_before_publication": 1124.0,
+ "publication_including_all_public_download_verification": 116.528,
+ "merge": null,
+ "notes": "Wall-clock intervals, not hands-on effort; earlier validation overlaps implementation. Actual user request timestamp unknown. Local optional image download and permission waiting are tracked separately, not subtracted."
+ }
+ },
+ "previous_goal_turn_classification": {
+ "status": "meaningful progress",
+ "at_utc": "2026-10-03T13:03:55.739443+00:00",
+ "progress": [
+ "Preview 4 ISO downloaded to the Mac and checksum verified",
+ "Small 7.4 MB OS update built and exercised on an encrypted installed VM, including failure, rollback and live process/project preservation",
+ "All three new public update assets downloaded and fully verified",
+ "Shared hn behavior explained; user explicitly approved immediate Terminal creation across platforms"
+ ],
+ "blocking_condition_repeated": false
+ },
+ "publication_history": [
+ {
+ "version": "0.1.0-preview.3",
+ "source_commit": "bbf6442d9c62fc8a4e9ad9acf5668159f35c99f0",
+ "release_url": "https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.3",
+ "published_at": "2026-10-03T07:53:11Z",
+ "verified_at": "2026-10-03T07:53:47.799570+00:00",
+ "verified_assets": [
+ "boot-layout.txt",
+ "inspection.json",
+ "machine-evidence.zip",
+ "manifest.json",
+ "packages.txt",
+ "programmer-os-0.1.0-preview.3-x86_64.iso",
+ "programmer-os-0.1.0-preview.3-x86_64.iso.sha256",
+ "validation.json"
+ ],
+ "receipt": "os/work/release-preview3/publication-ci/publication.json",
+ "verification_run": "https://github.com/autonomous-ai/openharness/actions/runs/37107746318"
+ }
+ ],
+ "mac_support_and_feedback_loop": {
+ "first_recorded_utc": "2026-10-03T12:08:01Z",
+ "request_received_utc": null,
+ "status": "Mac targets documented; small development update/rollback implemented, validated and publicly available for installed preview 4. Mac hardware ports remain unimplemented.",
+ "document": "os/DEVELOPMENT.md",
+ "documented_utc": "2026-10-03T12:12:18.648429+00:00",
+ "targets": [
+ "Older 64-bit Intel Macs without T2 first",
+ "Intel T2 Macs with a separate kernel/driver/firmware profile",
+ "Apple Silicon arm64 via Asahi platform integration, initially explicitly supported M1/M2 models"
+ ],
+ "recommended_feedback_loop": "One preview 4 install on the ThinkPad for daily work; native x86 KVM server VMs for repeatable installer/boot tests; Mac as development/control machine. M2 x86 emulation is not the primary feedback loop.",
+ "current_gap": "Physical ThinkPad update test and native Mac hardware integration remain unverified. Remote VM options have portable checks only.",
+ "next_implementation": [
+ "Remote interactive test VM mode with SSH-tunneled display and optional localhost guest SSH forwarding",
+ "Versioned and checksummed development deployment to a dedicated test machine with rollback and preserved projects",
+ "Stopped-VM snapshot/restore",
+ "Per-model Intel Mac hardware evidence; evaluate Asahi Minimal for the arm64 hardware port"
+ ],
+ "sources": [
+ "https://www.qemu.org/docs/master/system/introduction.html",
+ "https://wiki.t2linux.org/distributions/arch/installation/",
+ "https://wiki.t2linux.org/guides/postinstall/",
+ "https://asahilinux.org/fedora/",
+ "https://asahilinux.org/docs/platform/feature-support/m2/",
+ "https://asahilinux.org/docs/project/faq/"
+ ],
+ "validation": "Documentation local links and JSON checked; no native Mac install, server deployment, new ARM image or hardware success claimed."
+ },
+ "local_preview4_iso": {
+ "path": "/Users/ab/Downloads/harness-0.1.0-preview.4-x86_64.iso",
+ "bytes": 1612300288,
+ "sha256": "d111c2127e503818e4fccba62b8460e6160063bbf3b48e004e51516416229a92",
+ "checksum_verified": true,
+ "download_complete_utc": "2026-10-03T12:32:00Z",
+ "timestamp_basis": "Approximate completion reported by preceding download/copy sessions; local file verified present this turn."
+ },
+ "small_development_update": {
+ "request_received_utc": null,
+ "first_recorded_utc": "2026-10-03T12:12:18.648429+00:00",
+ "implementation_ready_utc": "2026-10-03T12:51:11.390514+00:00",
+ "status": "Published optional 7.4 MB update bundle on preview 4 release. Native encrypted update/failure/rollback/reboot and preserved-work checks passed; all three public assets verified.",
+ "merge_utc": null,
+ "publication_utc": "2026-10-03T13:02:00.808820+00:00",
+ "validation_plan": [
+ "Portable package identity, hash, architecture, source, archive path and rollback guards; Python/shell/JSON/XML syntax and workflow actionlint",
+ "Build exact-source Linux runtime and standalone native package; apply it offline to published preview 4 in an encrypted disposable KVM guest",
+ "Reject truncated download; exercise failed pacman transaction and retained recovery; verify apply, rollback, repeat apply, running terminal and project survival through daemon/screen restarts, encrypted reboot and physical-keyboard input",
+ "Reuse unchanged CLI/TUI source evidence from full CLI run 37116593867 and exact-image native run 37119543543; no redundant full suites"
+ ],
+ "changes": [
+ "Shared package assembly for ISO and development bundle with source/hash manifest",
+ "Explicit installed-OS update and rollback using pacman plus Btrfs checkpoint; no automatic service restart",
+ "Standalone bootstrap for existing preview 4 installations",
+ "Optional loopback-only remote VM launcher endpoints; real remote UI/SSH remains unverified"
+ ],
+ "waiting": [
+ {
+ "reason": "Local ISO transfer/copy was separate from server-side build and public publication; now complete.",
+ "started_utc": null,
+ "completed_utc": "2026-10-03T12:32:00Z"
+ }
+ ],
+ "research_page": {
+ "url": "https://chatgpt.com/space/page_d5d04ee40e348191b2b1aa9274b14e53",
+ "status": "page_read_forbidden; content not read, update implementation proceeds independently"
+ },
+ "shared_runtime_scope": "No cli/ or tui/ edits in this update. Earlier shared chooser/agent fixes remain on OS branch, not merged to main or published in a general TUI release.",
+ "source_commit": "42c22cece04cc49c1e2b6227ae5e40481072e779",
+ "validation_started_utc": "2026-10-03T12:51:36Z",
+ "native_run": {
+ "id": 37124241039,
+ "url": "https://github.com/autonomous-ai/openharness/actions/runs/37124241039",
+ "status": "passed"
+ },
+ "reused_source_trees": {
+ "cli": "d4cc9cddff97f0479b5a06a810d8535c557f44b6",
+ "tui": "ce54bd22a684d65b8433378468cfd56479612069",
+ "unchanged_since": "67958156da30d2983daee22ddab48c43970fa244"
+ },
+ "validation_complete_utc": "2026-10-03T12:56:11Z",
+ "native_result": {
+ "status": "passed",
+ "checks": [
+ "Truncated download rejected before runtime or package identity changed; running work survives",
+ "Real pacman failure records recoverable state; retry cannot replace it; rollback restores the original package",
+ "Small package installed offline and verified without restarting the existing terminal process",
+ "Repeated apply recognizes the installed build without another transaction",
+ "The same terminal process and project survive restarting both Harness daemon and screen",
+ "Rollback restores the prior package and source identity; the same process and project survive both service restarts again"
+ ],
+ "previous_package": "harness-os 0.1.0pre4-1",
+ "candidate": {
+ "name": "harness-os-0.1.0pre4.r1.g42c22cece0-1-x86_64.pkg.tar.gz",
+ "version": "0.1.0pre4.r1.g42c22cece0-1",
+ "bytes": 7364206,
+ "sha256": "99a00490fab414dc2cfc2ef1398f4b9f66714ed9b16397cbea016dfb6c1b8fab"
+ },
+ "source_commit": "42c22cece04cc49c1e2b6227ae5e40481072e779",
+ "apply_seconds": 3.089,
+ "rollback_seconds": 1.083
+ },
+ "visual_review": [
+ "Updated graphical hn received keyboard input and displayed its response",
+ "Encrypted reboot shows Harness wordmark and masked password prompt"
+ ],
+ "publication": {
+ "status": "verified",
+ "verified_at": "2026-10-03T13:02:00.808820+00:00",
+ "release": "https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.4",
+ "source_commit": "42c22cece04cc49c1e2b6227ae5e40481072e779",
+ "assets": [
+ {
+ "name": "harness-update-preview.4-42c22cece-x86_64-validation.json",
+ "bytes": 2034,
+ "sha256": "383e195799c63972721435c0ee7d34832ee5f822f172a8453d75a784d14a1262"
+ },
+ {
+ "name": "harness-update-preview.4-42c22cece-x86_64.zip",
+ "bytes": 7387295,
+ "sha256": "2f621ab2287585fd9ccb5b1b67cb5127d575d6372cd5cdb06c88d041eecabd6c"
+ },
+ {
+ "name": "harness-update-preview.4-42c22cece-x86_64.zip.sha256",
+ "bytes": 112,
+ "sha256": "ed5776b4b6d06a16c2b501a30cbad9b68fd0db65c587d315eafb37ff04dfe15f"
+ }
+ ]
+ },
+ "publication_time_basis": "Verification completion; exact upload start was not recorded.",
+ "publication_completion_reported_utc": "2026-10-03T13:03:55.739254+00:00",
+ "public_artifact": "https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.4/harness-update-preview.4-42c22cece-x86_64.zip",
+ "elapsed_seconds": {
+ "first_recorded_planning_to_verified_publication": 2982.160391,
+ "native_validation_including_runtime_build": 275,
+ "evidence_review_packaging_and_publication_after_ci": 349.80882,
+ "merge": null,
+ "notes": "Original user request timestamp unavailable. Implementation overlaps portable checks. Public packaging/transfer/verification follow native CI, not included in its duration. No main merge or general TUI publication."
+ },
+ "shared_terminal_behavior_approved": true,
+ "future_packaging_note": "Development versions include revision count and full source identity. CI shallow checkout yielded r1; before an automatic ordered update channel exists, replace the count with a source-date ordering key. Current explicit local pacman installs and rollback are validated."
+ },
+ "physical_preview4_user_report": {
+ "recorded_utc": "2026-10-03T13:29:43.451299+00:00",
+ "version": "0.1.0-preview.4",
+ "device": "ThinkPad (model not supplied)",
+ "reported": "User reported successful installation, boot and use of the new OS; described it as awesome.",
+ "timings_measured": false,
+ "limits": "No independent timing, Wi-Fi, suspend, or GPU evidence supplied."
+ },
+ "landing_narrative_and_merge": {
+ "request_received_utc": null,
+ "first_recorded_utc": "2026-10-03T13:29:43.451299+00:00",
+ "status": "Page static validation passed; visual review awaiting access or user feedback. Integrated main; native fixture expectation updated for main\u2019s shared Models picker; final CLI/TUI/OS validation next.",
+ "merge_authorized": true,
+ "base_commit": "423b47cf94b0b495d0a950ac05dbbb350281afe7",
+ "integration_commit": "dd8fb89c8a5e665153f5783d1651440d4d3321d9",
+ "narrative": "Agents are the new apps. Conversation is the interface. Terminal and optional browser are the working surfaces.",
+ "implementation_ready_utc": "2026-10-03T13:33:48.223860+00:00",
+ "validation_started_utc": "2026-10-03T13:21:52Z",
+ "validation_completed_utc": null,
+ "merge_utc": null,
+ "publication_utc": null,
+ "validation_plan": [
+ "Static HTML/CSS, local assets, headings, links and current public release asset names",
+ "Local browser visual/keyboard review; currently denied by saved permission; manual review requested",
+ "Full CLI scope including supported platform matrix after integrating main",
+ "Full TUI scope on x86_64 and aarch64 including native terminal fixtures after integrating main",
+ "Fresh exact-source OS build plus BIOS/plain and UEFI/encrypted installation/boot/agent/recovery checks; existing workload and development-update evidence remains tied to its original source"
+ ],
+ "os_integration_run": "https://github.com/autonomous-ai/openharness/actions/runs/37125918188",
+ "waiting": [
+ {
+ "kind": "visual review",
+ "reason": "Chrome rejected http://127.0.0.1:18092/ due a saved site permission despite earlier user approval. Manual review requested; no alternate route used.",
+ "started_utc": "2026-10-03T13:29:43.451299+00:00",
+ "completed_utc": null
+ }
+ ],
+ "follow_up_preserved": "Unvalidated session lock/suspend test script and workflow patch saved under ignored os/work/next-session; excluded from this merge.",
+ "hardware_priority": [
+ "Identify and validate one older Intel Mac without T2 from the user\u2019s MacBook Air/Pro collection",
+ "NVIDIA desktop 4090, then 5090",
+ "Separate T2 and Apple Silicon platform work"
+ ],
+ "integration_diagnosis": {
+ "failed_run": 37125918188,
+ "finding": "342 Rust tests and nine native fixtures passed. The e2e fixture still expected Sonnet / High, but current main intentionally replaced those engine rows with the shared subscriptions/local/Grid Models picker. Models source and stale fixture matched main.",
+ "change": "Update the existing native fixture to verify connected subscriptions, available Grid model, and shell focus guidance; no product model-picker behavior changed."
+ },
+ "static_validation": "Strict HTML5 and CSS parsing; local assets, fonts, dimensions, headings and fragments; release download names; 65 portable OS tests; Python/JSON/XML/shell checks; git diff --check passed."
+ }
+}
diff --git a/os/root/etc/NetworkManager/conf.d/10-dns.conf b/os/root/etc/NetworkManager/conf.d/10-dns.conf
new file mode 100644
index 000000000..c81a6439c
--- /dev/null
+++ b/os/root/etc/NetworkManager/conf.d/10-dns.conf
@@ -0,0 +1,2 @@
+[main]
+dns=systemd-resolved
diff --git a/os/root/etc/chromium/policies/managed/harness.json b/os/root/etc/chromium/policies/managed/harness.json
new file mode 100644
index 000000000..44f2a7dc3
--- /dev/null
+++ b/os/root/etc/chromium/policies/managed/harness.json
@@ -0,0 +1,6 @@
+{
+ "BackgroundModeEnabled": false,
+ "BrowserSignin": 0,
+ "MetricsReportingEnabled": false,
+ "DefaultBrowserSettingEnabled": false
+}
diff --git a/os/root/etc/pacman.d/hooks/10-hn-checkpoint.hook b/os/root/etc/pacman.d/hooks/10-hn-checkpoint.hook
new file mode 100644
index 000000000..8f3d5d5cf
--- /dev/null
+++ b/os/root/etc/pacman.d/hooks/10-hn-checkpoint.hook
@@ -0,0 +1,12 @@
+[Trigger]
+Operation = Install
+Operation = Upgrade
+Operation = Remove
+Type = Package
+Target = *
+
+[Action]
+Description = Saving Harness root and matching boot files
+When = PreTransaction
+Exec = /usr/bin/python3 /usr/lib/harness-os/system.py checkpoint --pacman-hook
+AbortOnFail
diff --git a/os/root/etc/profile.d/harness-os.sh b/os/root/etc/profile.d/harness-os.sh
new file mode 100644
index 000000000..099d3b0c7
--- /dev/null
+++ b/os/root/etc/profile.d/harness-os.sh
@@ -0,0 +1,7 @@
+# Login environment for the OS surface and ordinary terminal panes.
+export PATH="$HOME/.local/bin:$PATH"
+export npm_config_prefix="$HOME/.local"
+export BROWSER=hn-browser
+if [ -t 0 ] && [ "$(tty)" = /dev/tty1 ] && [ "$(id -u)" != 0 ] && [ -z "${WAYLAND_DISPLAY:-}" ]; then
+ exec /usr/lib/harness-os/session
+fi
diff --git a/os/root/etc/skel/.npmrc b/os/root/etc/skel/.npmrc
new file mode 100644
index 000000000..308c932ee
--- /dev/null
+++ b/os/root/etc/skel/.npmrc
@@ -0,0 +1,4 @@
+# These hn agent packages need their vendor installation scripts.
+# Other packages keep npm's default policy and can be approved when needed.
+prefix=${HOME}/.local
+allow-scripts=@anthropic-ai/claude-code,@openai/codex,opencode-ai
diff --git a/os/root/etc/skel/Projects/AGENTS.md b/os/root/etc/skel/Projects/AGENTS.md
new file mode 100644
index 000000000..1c39e8bec
--- /dev/null
+++ b/os/root/etc/skel/Projects/AGENTS.md
@@ -0,0 +1,5 @@
+# This computer
+
+This is Harness. Read `/usr/share/harness-os/AGENTS.md` before changing
+system packages, drivers, services or boot configuration. Keep this workspace
+focused on agents and their work; use the browser only when useful.
diff --git a/os/root/etc/systemd/journald.conf.d/10-harness-os.conf b/os/root/etc/systemd/journald.conf.d/10-harness-os.conf
new file mode 100644
index 000000000..ed79cd22f
--- /dev/null
+++ b/os/root/etc/systemd/journald.conf.d/10-harness-os.conf
@@ -0,0 +1,3 @@
+[Journal]
+Storage=volatile
+RuntimeMaxUse=32M
diff --git a/os/root/etc/systemd/zram-generator.conf b/os/root/etc/systemd/zram-generator.conf
new file mode 100644
index 000000000..6e8091fa9
--- /dev/null
+++ b/os/root/etc/systemd/zram-generator.conf
@@ -0,0 +1,3 @@
+[zram0]
+zram-size = min(ram / 2, 4096)
+compression-algorithm = zstd
diff --git a/os/root/etc/tmux.conf b/os/root/etc/tmux.conf
new file mode 100644
index 000000000..1add0ee19
--- /dev/null
+++ b/os/root/etc/tmux.conf
@@ -0,0 +1,3 @@
+# hn's agent runtime must keep pane IDs unique across closing the last shell.
+# Without this, tmux exits empty and reuses %0 before discovery drops its old row.
+set -s exit-empty off
diff --git a/os/root/etc/xdg/mimeapps.list b/os/root/etc/xdg/mimeapps.list
new file mode 100644
index 000000000..897225e7e
--- /dev/null
+++ b/os/root/etc/xdg/mimeapps.list
@@ -0,0 +1,4 @@
+[Default Applications]
+text/html=hn-browser.desktop
+x-scheme-handler/http=hn-browser.desktop
+x-scheme-handler/https=hn-browser.desktop
diff --git a/os/root/usr/bin/harness b/os/root/usr/bin/harness
new file mode 100644
index 000000000..827bbcce5
--- /dev/null
+++ b/os/root/usr/bin/harness
@@ -0,0 +1,15 @@
+#!/bin/sh
+if [ "${1:-}" = install ]; then
+ shift
+ exec /usr/bin/python3 /usr/lib/harness-os/install.py "$@"
+fi
+if [ "${1:-}" = upgrade ]; then
+ shift
+ exec /usr/bin/python3 /usr/lib/harness-os/runtime_update.py apply "$@"
+fi
+if [ "${1:-}" = rollback ]; then
+ shift
+ exec /usr/bin/python3 /usr/lib/harness-os/runtime_update.py rollback "$@"
+fi
+export ADAPTER_UPDATE_DISABLE=true
+exec /usr/bin/node /usr/lib/harness/cli.mjs "$@"
diff --git a/os/root/usr/bin/hn b/os/root/usr/bin/hn
new file mode 100644
index 000000000..484395a31
--- /dev/null
+++ b/os/root/usr/bin/hn
@@ -0,0 +1,13 @@
+#!/bin/sh
+export HARNESS_TUI_BIN=/usr/lib/harness/hn
+# The OS already supervises the daemon. Run the native client directly instead
+# of keeping a second Node process resident for the lifetime of the screen.
+export HARNESS_CLI=/usr/bin/harness
+export HARNESS_CLI_ARGS='[]'
+if [ -f /etc/harness-live ]; then
+ export HARNESS_OS_LIVE=1
+ export HARNESS_TUI_TMUX_CONF=/usr/share/harness-os/tmux-live.conf
+else
+ unset HARNESS_OS_LIVE
+fi
+exec /usr/lib/harness/hn "$@"
diff --git a/os/root/usr/bin/hn-browser b/os/root/usr/bin/hn-browser
new file mode 100644
index 000000000..fff6b5077
--- /dev/null
+++ b/os/root/usr/bin/hn-browser
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Use the current display environment even from a long-lived agent or SSH pane.
+# Chromium remains sandboxed and is started only by an explicit browser request.
+exec systemd-run --user --quiet --collect /usr/bin/chromium --ozone-platform=wayland --no-first-run --no-default-browser-check "$@"
diff --git a/os/root/usr/lib/harness-os/init-keyring b/os/root/usr/lib/harness-os/init-keyring
new file mode 100644
index 000000000..b1c865001
--- /dev/null
+++ b/os/root/usr/lib/harness-os/init-keyring
@@ -0,0 +1,13 @@
+#!/bin/sh
+# Generate a fresh local key on each installation. Never ship a shared private key.
+set -eu
+install -d /var/lib/pacman/sync
+for repo in core extra; do
+ if [ ! -s "/var/lib/pacman/sync/$repo.db" ]; then
+ cp "/usr/share/harness-os/repository-databases/$repo.db" "/var/lib/pacman/sync/$repo.db"
+ fi
+done
+pacman-key --init
+pacman-key --populate archlinux
+mkdir -p /var/lib/harness-os
+touch /var/lib/harness-os/keyring-ready
diff --git a/os/root/usr/lib/harness-os/session b/os/root/usr/lib/harness-os/session
new file mode 100644
index 000000000..75095fa7c
--- /dev/null
+++ b/os/root/usr/lib/harness-os/session
@@ -0,0 +1,35 @@
+#!/bin/sh
+set -eu
+export XDG_SESSION_TYPE=wayland
+export XDG_CURRENT_DESKTOP=labwc
+export ADAPTER_UPDATE_DISABLE=true
+export HARNESS_TUI_BIN=/usr/lib/harness/hn
+export PATH="$HOME/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/bin"
+export BROWSER=hn-browser
+export npm_config_prefix="$HOME/.local"
+export HARNESS_OS=1
+export HARNESS_TUI_NOTIFY=off
+export HARNESS_TUI_TMUX_CONF=/usr/share/harness-os/tmux.conf
+# A 2D virtio display has no GPU acceleration. Using Mesa's software GL there
+# wastes CPU and memory. Keep wlroots' normal renderer on physical/3D GPUs and
+# honor an explicit WLR_RENDERER setting.
+if [ -z "${WLR_RENDERER:-}" ] && /usr/lib/harness-os/virtio-2d; then
+ export WLR_RENDERER=pixman
+fi
+mkdir -p "$HOME/.local/bin" "$HOME/Projects" "$HOME/.local/state/harness-os"
+# Use the systemd user's existing bus so activation and the compositor share one
+# environment. A second dbus-run-session bus would split those services.
+export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus"
+if labwc -C /usr/share/harness-os/labwc > "$HOME/.local/state/harness-os/display.log" 2>&1; then
+ exit 0
+fi
+# A missing/broken GPU driver must not strand the programmer at a blank screen.
+# Stay in hn on the Linux console; an agent can install drivers and arrange a reboot.
+systemctl --user stop harness-os.target || true
+systemctl --user start harness-daemon.service || true
+printf '%s\n' 'Graphics unavailable; continuing in hn on the console.'
+cd "$HOME/Projects"
+while :; do
+ /usr/bin/hn || true
+ sleep 2
+done
diff --git a/os/root/usr/lib/harness-os/virtio-2d b/os/root/usr/lib/harness-os/virtio-2d
new file mode 100755
index 000000000..e3f792fb7
--- /dev/null
+++ b/os/root/usr/lib/harness-os/virtio-2d
@@ -0,0 +1,19 @@
+#!/bin/sh
+# Succeed only when every DRM card is a virtio GPU without VIRGL (feature 0).
+# The card's device can be the virtio device itself or its PCI parent.
+set -eu
+found=false
+for card in /sys/class/drm/card[0-9] /sys/class/drm/card[0-9][0-9]; do
+ [ -e "$card/device" ] || continue
+ matched=false
+ for features in "$card/device/features" "$card"/device/virtio*/features; do
+ [ -r "$features" ] || continue
+ driver=$(readlink -f "${features%/features}/driver")
+ [ "${driver##*/}" = virtio_gpu ] || continue
+ IFS= read -r bits < "$features"
+ case "$bits" in 0*) matched=true ;; *) exit 1 ;; esac
+ done
+ "$matched" || exit 1
+ found=true
+done
+"$found"
diff --git a/os/root/usr/lib/harness-os/wait-runtime b/os/root/usr/lib/harness-os/wait-runtime
new file mode 100755
index 000000000..be1e89460
--- /dev/null
+++ b/os/root/usr/lib/harness-os/wait-runtime
@@ -0,0 +1,13 @@
+#!/bin/sh
+# Type=exec establishes a process, not an agent runtime ready to accept hn.
+# Keep startup ordering honest without a second persistent supervisor.
+set -eu
+for attempt in $(seq 1 120); do
+ if curl --fail --silent --max-time 1 http://127.0.0.1:18473/api/status |
+ jq -e '.discoveryReady == true and .safeMode != true' >/dev/null 2>&1; then
+ exit 0
+ fi
+ sleep 0.25
+done
+printf '%s\n' 'Harness runtime did not become ready; see journalctl --user -u harness-daemon.' >&2
+exit 1
diff --git a/os/root/usr/lib/systemd/system/harness-keyring.service b/os/root/usr/lib/systemd/system/harness-keyring.service
new file mode 100644
index 000000000..7350300a3
--- /dev/null
+++ b/os/root/usr/lib/systemd/system/harness-keyring.service
@@ -0,0 +1,13 @@
+[Unit]
+Description=Initialize this machine's package verification keyring
+After=systemd-random-seed.service time-sync.target
+Before=archlinux-keyring-wkd-sync.service
+ConditionPathExists=!/var/lib/harness-os/keyring-ready
+
+[Service]
+Type=oneshot
+ExecStart=/usr/lib/harness-os/init-keyring
+RemainAfterExit=yes
+
+[Install]
+WantedBy=multi-user.target
diff --git a/os/root/usr/lib/systemd/user/harness-daemon.service b/os/root/usr/lib/systemd/user/harness-daemon.service
new file mode 100644
index 000000000..df457f6f8
--- /dev/null
+++ b/os/root/usr/lib/systemd/user/harness-daemon.service
@@ -0,0 +1,20 @@
+[Unit]
+Description=Harness agent runtime
+
+[Service]
+Type=exec
+Environment=ADAPTER_UPDATE_DISABLE=true
+Environment=HARNESS_OS=1
+Environment=HARNESS_TUI_BIN=/usr/lib/harness/hn
+Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin
+Environment=npm_config_prefix=%h/.local
+Environment=BROWSER=hn-browser
+ExecStart=/usr/bin/harness start --foreground
+ExecStartPost=/usr/lib/harness-os/wait-runtime
+TimeoutStartSec=150
+Restart=on-failure
+RestartSec=2
+KillMode=process
+
+[Install]
+WantedBy=default.target
diff --git a/os/root/usr/lib/systemd/user/harness-idle.service b/os/root/usr/lib/systemd/user/harness-idle.service
new file mode 100644
index 000000000..d2e2639f4
--- /dev/null
+++ b/os/root/usr/lib/systemd/user/harness-idle.service
@@ -0,0 +1,7 @@
+[Unit]
+Description=Lock before suspend
+PartOf=harness-os.target
+
+[Service]
+ExecStart=/usr/bin/swayidle -w timeout 600 'swaylock -f -c 000000' before-sleep 'swaylock -f -c 000000'
+Restart=on-failure
diff --git a/os/root/usr/lib/systemd/user/harness-os.target b/os/root/usr/lib/systemd/user/harness-os.target
new file mode 100644
index 000000000..a50598f1c
--- /dev/null
+++ b/os/root/usr/lib/systemd/user/harness-os.target
@@ -0,0 +1,4 @@
+[Unit]
+Description=The hn screen
+Wants=hn-screen.service harness-idle.service
+After=graphical-session-pre.target
diff --git a/os/root/usr/lib/systemd/user/hn-screen.service b/os/root/usr/lib/systemd/user/hn-screen.service
new file mode 100644
index 000000000..d4c3ae472
--- /dev/null
+++ b/os/root/usr/lib/systemd/user/hn-screen.service
@@ -0,0 +1,29 @@
+[Unit]
+Description=Persistent hn terminal surface
+PartOf=harness-os.target
+Wants=harness-daemon.service
+After=harness-daemon.service
+StartLimitIntervalSec=0
+
+[Service]
+Type=exec
+Environment=ADAPTER_UPDATE_DISABLE=true
+Environment=HARNESS_TUI_BIN=/usr/lib/harness/hn
+Environment=HARNESS_TUI_NOTIFY=off
+Environment=HARNESS_TUI_TMUX_CONF=/usr/share/harness-os/tmux.conf
+Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin
+Environment=npm_config_prefix=%h/.local
+Environment=HARNESS_OS=1
+Environment=BROWSER=hn-browser
+WorkingDirectory=%h/Projects
+ExecStart=/usr/bin/foot --config=/usr/share/harness-os/foot.ini /usr/bin/hn
+Restart=always
+RestartSec=1
+RestartSteps=5
+RestartMaxDelaySec=30
+KillMode=process
+# Agent daemons and PTY owners must be outside this service. The launcher starts
+# the daemon through its own service; reconnect never kills the work.
+
+[Install]
+WantedBy=harness-os.target
diff --git a/os/root/usr/share/applications/hn-browser.desktop b/os/root/usr/share/applications/hn-browser.desktop
new file mode 100644
index 000000000..1eb75401d
--- /dev/null
+++ b/os/root/usr/share/applications/hn-browser.desktop
@@ -0,0 +1,7 @@
+[Desktop Entry]
+Name=Browser
+Type=Application
+Exec=hn-browser %U
+Terminal=false
+MimeType=text/html;x-scheme-handler/http;x-scheme-handler/https;
+NoDisplay=true
diff --git a/os/root/usr/share/harness-os/AGENTS.md b/os/root/usr/share/harness-os/AGENTS.md
new file mode 100644
index 000000000..c01eae762
--- /dev/null
+++ b/os/root/usr/share/harness-os/AGENTS.md
@@ -0,0 +1,71 @@
+# Harness
+
+The user works in hn agent panes. Keep the system small. Install the tools needed
+for the current task, and use terminal output, diffs and tests to review the work.
+Open `hn-browser URL` only when a browser helps. Add tools and services when the
+current task needs them; run extra services on demand unless the task needs them
+persistently. Keep the desktop shell, launcher and panels absent unless the user
+requests that interface. Open a new terminal immediately with Ctrl+B, then T. No agent or project setup
+is required.
+
+## System operations
+
+- This is Arch Linux with systemd, the LTS kernel, labwc, foot and Chromium.
+- Use the ordinary package manager; no private package ecosystem is required.
+ On the live USB, `sudo systemctl start harness-keyring` waits for its one-time
+ key setup before the first package installation. Installed systems finish that
+ setup during installation. The hn screen does not wait for it at live boot.
+ `sudo pacman -S --needed PACKAGE` installs from the system's complete dated
+ repository snapshot. Never run `pacman -Sy` followed by individual installs.
+- `sudo hn-os update` makes a checkpoint, advances all Arch repositories to
+ yesterday's complete snapshot, and performs a full upgrade. It asks through
+ pacman before the package transaction. Reboot after kernel/driver upgrades.
+ If it fails or is interrupted, resolve the reported cause and rerun
+ `sudo hn-os update` before changing individual packages. Ordinary package
+ transactions are blocked until that full update succeeds; retry preserves
+ the original recovery checkpoint. Use the live USB to recover if needed.
+- Package transactions also create checkpoints automatically. A checkpoint
+ includes the root filesystem, package database, kernel, initramfs and bootloader
+ files. `/home` and its projects are separate and are not rolled back.
+- `sudo hn-os checkpoint` explicitly saves the current system. Checkpoints use
+ disk space; list them with `sudo ls /.snapshots`. Do not delete them blindly.
+- Recovery runs from the live USB against an unmounted installed root device:
+ `sudo hn-os recover /dev/sda3` lists checkpoints;
+ `sudo hn-os recover /dev/sda3 CHECKPOINT` restores one. For encrypted installs,
+ first use `sudo cryptsetup open /dev/sda3 hn-recovery`, then use
+ `/dev/mapper/hn-recovery` in the recovery command. Device names vary; inspect
+ `lsblk -f` first. Recovery changes the installed system, not user projects.
+- The user's account has password-protected sudo. Do not disable authentication,
+ browser sandboxing, disk encryption or the session lock to make a task easier.
+
+## Network and hardware
+
+- Ethernet uses NetworkManager automatically. For Wi-Fi, use
+ `hn-os wifi`, which opens NetworkManager’s keyboard interface.
+ Keep passwords out of shell arguments and transcripts.
+- Audio uses PipeWire. Clipboard uses `wl-copy` and `wl-paste`.
+- npm installs into `~/.local`. The initial npm configuration permits the vendor
+ install scripts for Claude Code, Codex and OpenCode. When another package needs
+ an install script, approve that package explicitly; keep npm's other defaults.
+- `Super+B` opens/focuses Chromium or returns to hn; `Super+Enter` focuses hn;
+ `Super+L` locks the screen. `sudo systemctl poweroff` shuts down cleanly.
+- On supported NVIDIA Turing and newer GPUs, including RTX 4090/5090 and RTX 6000
+ generations, the LTS-kernel packages are `nvidia-open-lts nvidia-utils`.
+ Install both from the same repository snapshot, regenerate initramfs with
+ `sudo mkinitcpio -P`, reboot, and verify `nvidia-smi` before claiming GPU compute
+ works. Older NVIDIA GPUs need a different driver assessment.
+- CUDA SDKs, model weights and model servers are installed only when a task needs
+ them. A driver working is not evidence that a particular AI framework supports
+ the GPU; test the actual framework and workload.
+
+## Diagnosis
+
+`hn-os status`, `hn-os measure`, `systemctl --user status hn-screen harness-daemon`
+and `journalctl --user -u hn-screen -u harness-daemon` show the session state.
+Restarting `hn-screen` should reconnect to existing work. Do not restart or kill
+the agent runtime as the first response to a display problem.
+
+Source: https://github.com/autonomous-ai/openharness (exact source commit in
+`/usr/share/harness-os/runtime.json`).
+NVIDIA package: https://archlinux.org/packages/extra/x86_64/nvidia-open-lts/
+NVIDIA support: https://github.com/NVIDIA/open-gpu-kernel-modules
diff --git a/os/root/usr/share/harness-os/foot.ini b/os/root/usr/share/harness-os/foot.ini
new file mode 100644
index 000000000..5a616e542
--- /dev/null
+++ b/os/root/usr/share/harness-os/foot.ini
@@ -0,0 +1,20 @@
+[main]
+term=foot
+font=DejaVu Sans Mono:size=11,Symbols Nerd Font Mono:size=11
+pad=0x0
+initial-window-mode=fullscreen
+app-id=hn
+title=hn
+
+[colors-dark]
+background=101010
+foreground=dddddd
+
+[scrollback]
+lines=0
+
+[mouse]
+hide-when-typing=yes
+
+[key-bindings]
+spawn-terminal=none
diff --git a/os/root/usr/share/harness-os/labwc/autostart b/os/root/usr/share/harness-os/labwc/autostart
new file mode 100644
index 000000000..290a3a25d
--- /dev/null
+++ b/os/root/usr/share/harness-os/labwc/autostart
@@ -0,0 +1,4 @@
+#!/bin/sh
+dbus-update-activation-environment --systemd WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE BROWSER
+systemctl --user import-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE BROWSER
+systemctl --user start harness-os.target
diff --git a/os/root/usr/share/harness-os/labwc/rc.xml b/os/root/usr/share/harness-os/labwc/rc.xml
new file mode 100644
index 000000000..f3f9700d4
--- /dev/null
+++ b/os/root/usr/share/harness-os/labwc/rc.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0"?>
+<labwc_config>
+ <core><decoration>server</decoration><gap>0</gap></core>
+ <theme><name>harness</name><cornerRadius>0</cornerRadius><keepBorder>no</keepBorder></theme>
+ <focus><followMouse>no</followMouse></focus>
+ <desktops><number>1</number><popupTime>0</popupTime></desktops>
+ <keyboard>
+ <repeatRate>35</repeatRate><repeatDelay>250</repeatDelay>
+ <!-- No default desktop shortcuts. Super+B is run-or-raise, then back to hn. -->
+ <keybind key="W-b">
+ <action name="If">
+ <query identifier="chromium*" />
+ <then><action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action></then>
+ <else><action name="ForEach"><query identifier="chromium*" /><then><action name="Raise" /><action name="Focus" /></then><none><action name="Execute" command="hn-browser" /></none></action></else>
+ </action>
+ </keybind>
+ <keybind key="W-Return"><action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action></keybind>
+ <keybind key="A-Tab"><action name="NextWindowImmediate" /></keybind>
+ <keybind key="W-l"><action name="Execute" command="swaylock -f -c 000000" /></keybind>
+ <keybind key="XF86MonBrightnessUp"><action name="Execute" command="brightnessctl set +5%" /></keybind>
+ <keybind key="XF86MonBrightnessDown"><action name="Execute" command="brightnessctl set 5%-" /></keybind>
+ <keybind key="XF86AudioRaiseVolume"><action name="Execute" command="wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%+ -l 1" /></keybind>
+ <keybind key="XF86AudioLowerVolume"><action name="Execute" command="wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%-" /></keybind>
+ <keybind key="XF86AudioMute"><action name="Execute" command="wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle" /></keybind>
+ </keyboard>
+ <mouse><context name="Root"><mousebind button="Right" action="Press"><action name="None" /></mousebind></context></mouse>
+ <windowRules>
+ <windowRule identifier="hn" serverDecoration="no" />
+ <windowRule identifier="chromium*" type="normal" serverDecoration="no"><action name="Maximize" /></windowRule>
+ </windowRules>
+</labwc_config>
diff --git a/os/root/usr/share/harness-os/labwc/shutdown b/os/root/usr/share/harness-os/labwc/shutdown
new file mode 100644
index 000000000..51904561f
--- /dev/null
+++ b/os/root/usr/share/harness-os/labwc/shutdown
@@ -0,0 +1,3 @@
+#!/bin/sh
+# Keep the agent runtime independent of the graphical session.
+systemctl --user stop harness-os.target
diff --git a/os/root/usr/share/harness-os/tmux-live.conf b/os/root/usr/share/harness-os/tmux-live.conf
new file mode 100644
index 000000000..6ea5f2822
--- /dev/null
+++ b/os/root/usr/share/harness-os/tmux-live.conf
@@ -0,0 +1,3 @@
+# Direct system actions remain available while trying an agent from USB.
+source-file /usr/share/harness-os/tmux.conf
+bind I new-window -n Install 'sudo /usr/bin/harness install'
diff --git a/os/root/usr/share/harness-os/tmux.conf b/os/root/usr/share/harness-os/tmux.conf
new file mode 100644
index 000000000..db68a5514
--- /dev/null
+++ b/os/root/usr/share/harness-os/tmux.conf
@@ -0,0 +1,10 @@
+# OS session keys: ordinary shells live in hn panes.
+unbind d
+unbind D
+unbind C-z
+bind W new-window -n Wi-Fi '/usr/bin/hn-os wifi'
+set -g @hn-animations off
+set -g exit-empty off
+set -g exit-unattached off
+set -g destroy-unattached off
+set -g detach-on-destroy off
diff --git a/os/root/usr/share/plymouth/themes/harness/harness.plymouth b/os/root/usr/share/plymouth/themes/harness/harness.plymouth
new file mode 100644
index 000000000..d6ed74426
--- /dev/null
+++ b/os/root/usr/share/plymouth/themes/harness/harness.plymouth
@@ -0,0 +1,10 @@
+[Plymouth Theme]
+Name=Harness
+Description=Static Harness disk unlock screen
+ModuleName=script
+
+[script]
+ImageDir=/usr/share/plymouth/themes/harness
+ScriptFile=/usr/share/plymouth/themes/harness/harness.script
+Font=DejaVu Sans Mono 16
+MonospaceFont=DejaVu Sans Mono 16
diff --git a/os/root/usr/share/plymouth/themes/harness/harness.script b/os/root/usr/share/plymouth/themes/harness/harness.script
new file mode 100644
index 000000000..8ae946067
--- /dev/null
+++ b/os/root/usr/share/plymouth/themes/harness/harness.script
@@ -0,0 +1,36 @@
+# The standard Plymouth/systemd agent handles the password. This theme receives
+# only its length, never the secret. No animation, images or background work.
+Window.SetBackgroundTopColor(0.063, 0.063, 0.063);
+Window.SetBackgroundBottomColor(0.063, 0.063, 0.063);
+
+logo_text = " _ \n| |__ __ _ _ __ _ __ ___ ___ ___\n| '_ \\ / _` | '__| '_ \\ / _ \\/ __/ __|\n| | | | (_| | | | | | | __/\\__ \\__ \\\n|_| |_|\\__,_|_| |_| |_|\\___||___/___/";
+logo_image = Image.Text(logo_text, 0.85, 0.78, 0.1, 1, "monospace 16", "left");
+logo = Sprite(logo_image);
+logo.SetPosition(Window.GetX() + (Window.GetWidth() - logo_image.GetWidth()) / 2,
+ Window.GetY() + Window.GetHeight() / 2 - logo_image.GetHeight() - 24, 1);
+label = Sprite();
+entry = Sprite();
+
+fun display_password(prompt, bullets) {
+ label_image = Image.Text("Enter your password", 0.86, 0.86, 0.86, 1, "monospace 16", "center");
+ label.SetImage(label_image);
+ label.SetPosition(Window.GetX() + (Window.GetWidth() - label_image.GetWidth()) / 2,
+ Window.GetY() + Window.GetHeight() / 2 + 16, 1);
+ text = "";
+ for (i = 0; i < bullets && i < 40; i++) text += "*";
+ if (bullets == 0) text = "_";
+ entry_image = Image.Text(text, 0.86, 0.86, 0.86, 1, "monospace 16", "center");
+ entry.SetImage(entry_image);
+ entry.SetPosition(Window.GetX() + (Window.GetWidth() - entry_image.GetWidth()) / 2,
+ Window.GetY() + Window.GetHeight() / 2 + 56, 1);
+ label.SetOpacity(1);
+ entry.SetOpacity(1);
+}
+
+fun display_normal() {
+ label.SetOpacity(0);
+ entry.SetOpacity(0);
+}
+
+Plymouth.SetDisplayPasswordFunction(display_password);
+Plymouth.SetDisplayNormalFunction(display_normal);
diff --git a/os/runtime_update.py b/os/runtime_update.py
new file mode 100644
index 000000000..a68cf5590
--- /dev/null
+++ b/os/runtime_update.py
@@ -0,0 +1,298 @@
+#!/usr/bin/env python3
+"""Apply a local Harness development bundle, retaining an offline rollback package."""
+from __future__ import annotations
+import argparse
+from datetime import datetime, timezone
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path, PurePosixPath
+import platform
+import re
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+import uuid
+
+STATE = Path('/var/lib/harness-os/runtime-updates')
+RUNTIME = Path('/usr/share/harness-os/runtime.json')
+LOCK = Path('/usr/share/harness-os/lock.json')
+PACKAGE_DB = Path('/var/lib/pacman/local')
+
+
+def digest(path):
+ with path.open('rb') as handle:
+ return hashlib.file_digest(handle, 'sha256').hexdigest()
+
+
+def read_json(path):
+ return json.loads(path.read_text())
+
+
+def now():
+ return datetime.now(timezone.utc).isoformat()
+
+
+def system_module():
+ # The standalone bootstrap runs on preview 4 before this module is installed.
+ path = Path('/usr/lib/harness-os/system.py')
+ spec = importlib.util.spec_from_file_location('harness_os_system', path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def relative_path(value):
+ path = PurePosixPath(value)
+ if path.is_absolute() or '..' in path.parts or not path.parts or str(path) != value.rstrip('/'):
+ raise ValueError('Invalid package path: ' + value)
+ return path
+
+
+def inspect_package(path, version, runtime=None):
+ """Check package identity and contents without extracting or running anything."""
+ with tarfile.open(path, 'r:gz') as archive:
+ members = {}
+ for member in archive:
+ name = str(relative_path(member.name))
+ if name in members:
+ raise ValueError('Duplicate package path: ' + name)
+ if not (member.isfile() or member.isdir() or member.issym()):
+ raise ValueError('Unsupported package entry: ' + name)
+ if name != '.PKGINFO' and PurePosixPath(name).parts[0] not in ('etc', 'usr'):
+ raise ValueError('Package may only change Harness system files: ' + name)
+ if member.issym():
+ target = PurePosixPath(member.linkname)
+ if target.is_absolute() or '..' in target.parts:
+ raise ValueError('Unsafe package link: ' + name)
+ if member.uid != 0 or member.gid != 0:
+ raise ValueError('Package files must belong to root.')
+ members[name] = member
+ # A link must never redirect a later member during pacman's extraction.
+ for name in members:
+ for parent in PurePosixPath(name).parents:
+ if str(parent) in members and members[str(parent)].issym():
+ raise ValueError('Package path traverses a link: ' + name)
+ metadata = members.get('.PKGINFO')
+ if metadata is None or not metadata.isfile() or metadata.size > 65536:
+ raise ValueError('Missing or invalid package metadata.')
+ fields = {}
+ for line in archive.extractfile(metadata).read().decode().splitlines():
+ if ' = ' in line:
+ key, value = line.split(' = ', 1)
+ fields.setdefault(key, []).append(value)
+ if any(fields.get(key) != [value] for key, value in
+ [('pkgname', 'harness-os'), ('pkgver', version), ('arch', 'x86_64')]):
+ raise ValueError('Package identity does not match its manifest.')
+ if runtime is not None:
+ member = members.get('usr/share/harness-os/runtime.json')
+ if member is None or not member.isfile() or member.size > 65536:
+ raise ValueError('Missing runtime identity.')
+ if json.load(archive.extractfile(member)) != runtime:
+ raise ValueError('Runtime identity does not match its manifest.')
+ for name, info in runtime['files'].items():
+ if str(relative_path(name)) != Path(name).name:
+ raise ValueError('Invalid runtime filename.')
+ member = members.get('usr/lib/harness/' + name)
+ if member is None or not member.isfile() or member.size != info['bytes']:
+ raise ValueError('Missing or truncated runtime: ' + name)
+ if hashlib.file_digest(archive.extractfile(member), 'sha256').hexdigest() != info['sha256']:
+ raise ValueError('Runtime checksum mismatch: ' + name)
+
+
+def validate_bundle(folder, base):
+ manifest = read_json(folder / 'package-manifest.json')
+ if not isinstance(manifest, dict) or manifest.get('schema') != 1 or manifest.get('kind') != 'harness-os-package':
+ raise ValueError('Not a Harness package bundle.')
+ if manifest.get('architecture') != 'x86_64' or manifest.get('requires_os_version') != base['version'] or manifest.get('arch_snapshot') != base['arch_snapshot']:
+ raise ValueError('This package requires a different Harness base image or architecture.')
+ commit = manifest.get('source_commit', '')
+ runtime = manifest.get('runtime', {})
+ if not re.fullmatch(r'[0-9a-f]{40}', commit) or runtime.get('source_commit') != commit or runtime.get('dirty') is not False or runtime.get('target') != 'x86_64-unknown-linux-musl':
+ raise ValueError('The bundle must identify a clean Linux x86-64 source build.')
+ if set(runtime.get('files', {})) != {'harness-tui', 'cli.mjs', 'notify.mjs'}:
+ raise ValueError('The bundle must include the complete Harness runtime.')
+ package = manifest.get('package', {})
+ name = package.get('name', '')
+ version = package.get('version', '')
+ if not re.fullmatch(r'[0-9A-Za-z.+_-]+', version) or name != f'harness-os-{version}-x86_64.pkg.tar.gz':
+ raise ValueError('Invalid package name or version.')
+ path = folder / name
+ if path.is_symlink() or not path.is_file() or package.get('bytes') != path.stat().st_size or digest(path) != package.get('sha256'):
+ raise ValueError('Package checksum or size mismatch; download the complete bundle again.')
+ inspect_package(path, version, runtime)
+ return manifest, path
+
+
+def installed_version():
+ value = subprocess.check_output(['pacman', '-Q', 'harness-os'], text=True).strip().split()
+ if len(value) != 2 or value[0] != 'harness-os' or not re.fullmatch(r'[0-9A-Za-z.+_-]+', value[1]):
+ raise ValueError('Cannot identify the installed Harness package.')
+ return value[1]
+
+
+def verify_runtime(expected):
+ if read_json(RUNTIME) != expected:
+ raise ValueError('Installed runtime identity differs from the expected package.')
+ for name, info in expected['files'].items():
+ path = Path('/usr/lib/harness') / name
+ if path.stat().st_size != info['bytes'] or digest(path) != info['sha256']:
+ raise ValueError('Installed runtime verification failed: ' + name)
+
+
+def package_backup(snapshot_root, version, output):
+ """Rebuild this one installed package from the pre-update read-only snapshot."""
+ db = snapshot_root / str(PACKAGE_DB).lstrip('/') / ('harness-os-' + version)
+ fields = {}
+ for block in (db / 'desc').read_text().strip().split('\n\n'):
+ lines = block.splitlines()
+ fields[lines[0].strip('%')] = lines[1:]
+ if fields.get('NAME') != ['harness-os'] or fields.get('VERSION') != [version] or (db / 'install').exists():
+ raise ValueError('Unexpected installed package metadata; use checkpoint recovery instead.')
+ mapping = {'NAME': 'pkgname', 'BASE': 'pkgbase', 'VERSION': 'pkgver', 'DESC': 'pkgdesc',
+ 'URL': 'url', 'ARCH': 'arch', 'BUILDDATE': 'builddate', 'PACKAGER': 'packager',
+ 'SIZE': 'size', 'LICENSE': 'license', 'DEPENDS': 'depend',
+ 'OPTDEPENDS': 'optdepend', 'PROVIDES': 'provides', 'CONFLICTS': 'conflict',
+ 'REPLACES': 'replaces', 'GROUPS': 'group', 'XDATA': 'xdata'}
+ metadata = ''.join(f'{target} = {value}\n' for key, target in mapping.items() for value in fields.get(key, []))
+ blocks = {}
+ for block in (db / 'files').read_text().strip().split('\n\n'):
+ lines = block.splitlines()
+ blocks[lines[0].strip('%')] = lines[1:]
+ for backup in blocks.get('BACKUP', []):
+ metadata += 'backup = ' + backup.split('\t')[0] + '\n'
+ with tarfile.open(output, 'w:gz', dereference=False, compresslevel=6) as archive:
+ info = tarfile.TarInfo('.PKGINFO')
+ data = metadata.encode()
+ info.size, info.mode = len(data), 0o644
+ archive.addfile(info, io.BytesIO(data))
+ for name in blocks['FILES']:
+ path = relative_path(name)
+ if path.parts[0] not in ('etc', 'usr'):
+ raise ValueError('Unexpected installed package path: ' + name)
+ # recursive=False is essential: shared directories contain other packages.
+ archive.add(snapshot_root / str(path), arcname=str(path), recursive=False)
+ inspect_package(output, version)
+
+
+def latest():
+ pointer = STATE / 'latest.json'
+ if not pointer.exists():
+ return None
+ identity = read_json(pointer)['id']
+ if not isinstance(identity, str) or not re.fullmatch(r'[0-9TZ-]+-[a-f0-9]{8}', identity):
+ raise ValueError('Invalid update receipt identifier.')
+ receipt = read_json(STATE / identity / 'receipt.json')
+ if receipt.get('id') != identity:
+ raise ValueError('Update receipt identity mismatch.')
+ return receipt
+
+
+def install_package(package, version, runtime):
+ # The caller already holds the system-operation lock and made its checkpoint.
+ # Keep pacman's own lock and other hooks; suppress only our duplicate checkpoint.
+ subprocess.run(['pacman', '--noconfirm', '-U', str(package)], check=True,
+ env=dict(os.environ, HN_OS_UPDATE_CHECKPOINT='1'))
+ if installed_version() != version:
+ raise ValueError('The installed package version did not change as expected.')
+ verify_runtime(runtime)
+
+
+def apply(folder, system, base, installation):
+ previous = latest()
+ if previous and previous['status'] not in ('applied', 'rolled-back'):
+ raise ValueError('The previous Harness update did not finish. Run rollback first; its checkpoint is retained.')
+ manifest, source_package = validate_bundle(folder, base)
+ old_version, old_runtime = installed_version(), read_json(RUNTIME)
+ if old_version == manifest['package']['version']:
+ verify_runtime(manifest['runtime'])
+ print('This Harness build is already installed.')
+ return
+ STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
+ STATE.chmod(0o700)
+ # Copy before mutation; a user-owned download may change while it is being read.
+ with tempfile.TemporaryDirectory(prefix='.incoming-', dir=STATE) as temp:
+ incoming = Path(temp)
+ shutil.copyfile(source_package, incoming / source_package.name)
+ system.write_json(incoming / 'package-manifest.json', manifest)
+ validate_bundle(incoming, base)
+ checkpoint = system.checkpoint('before-harness-update')
+ identity = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ-') + uuid.uuid4().hex[:8]
+ saved = STATE / identity
+ saved.mkdir(mode=0o700)
+ backup = saved / 'previous.pkg.tar.gz'
+ package_backup(system.CHECKPOINTS / checkpoint / 'root', old_version, backup)
+ receipt = {'id': identity, 'status': 'applying', 'started_at': now(),
+ 'root_uuid': installation['root_uuid'], 'checkpoint': checkpoint,
+ 'previous_version': old_version, 'previous_runtime': old_runtime,
+ 'backup_sha256': digest(backup), 'candidate': manifest}
+ system.write_json(saved / 'receipt.json', receipt)
+ system.write_json(STATE / 'latest.json', {'id': identity})
+ try:
+ install_package(incoming / source_package.name, manifest['package']['version'], manifest['runtime'])
+ except BaseException:
+ receipt.update(status='failed', finished_at=now())
+ system.write_json(saved / 'receipt.json', receipt)
+ print('Update did not complete. Roll back with this same updater; the original checkpoint is retained.', file=sys.stderr)
+ raise
+ receipt.update(status='applied', finished_at=now())
+ system.write_json(saved / 'receipt.json', receipt)
+ print('Harness updated. Reboot when ready to use the new session. Your running work has not been restarted.')
+
+
+def rollback(system, installation):
+ receipt = latest()
+ if not receipt:
+ raise ValueError('No Harness update is available to roll back.')
+ if receipt['root_uuid'] != installation['root_uuid']:
+ raise ValueError('This update belongs to a different installation.')
+ if receipt['status'] == 'rolled-back':
+ print('The previous Harness build is already restored.')
+ return
+ folder = STATE / receipt['id']
+ backup = folder / 'previous.pkg.tar.gz'
+ if digest(backup) != receipt['backup_sha256']:
+ raise ValueError('Rollback package checksum mismatch. Recover the recorded checkpoint from the live USB.')
+ inspect_package(backup, receipt['previous_version'], receipt['previous_runtime'])
+ receipt.update(status='rolling-back', rollback_started_at=now())
+ system.write_json(folder / 'receipt.json', receipt)
+ install_package(backup, receipt['previous_version'], receipt['previous_runtime'])
+ receipt.update(status='rolled-back', rollback_finished_at=now())
+ system.write_json(folder / 'receipt.json', receipt)
+ print('Previous Harness build restored. Reboot when ready to use it.')
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest='command', required=True)
+ commands.add_parser('apply').add_argument('bundle', type=Path)
+ commands.add_parser('rollback')
+ commands.add_parser('status')
+ args = parser.parse_args(argv)
+ if os.geteuid() != 0:
+ parser.error('Run with sudo on the installed Harness machine.')
+ if platform.system() != 'Linux' or platform.machine() != 'x86_64' or Path('/etc/harness-live').exists():
+ parser.error('Use an installed x86-64 Harness system, not the live USB.')
+ system = system_module()
+ with system.operation_lock():
+ installation = system.installed()
+ if args.command == 'status':
+ print(json.dumps({'version': installed_version(), 'runtime': read_json(RUNTIME), 'last_update': latest()}, indent=2))
+ return
+ if system.pending_update():
+ raise ValueError('Complete the pending Arch system update before changing the Harness package.')
+ if args.command == 'apply':
+ apply(args.bundle.resolve(), system, read_json(LOCK), installation)
+ else:
+ rollback(system, installation)
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except (ValueError, OSError, KeyError, TypeError, subprocess.CalledProcessError, tarfile.TarError) as error:
+ raise SystemExit('Harness update stopped: ' + str(error))
diff --git a/os/site/README.md b/os/site/README.md
new file mode 100644
index 000000000..685162165
--- /dev/null
+++ b/os/site/README.md
@@ -0,0 +1,62 @@
+# Harness landing page
+
+A standalone page: HTML, CSS, local fonts, and four real screenshots. No JavaScript,
+framework, package installation, analytics, or build step. This directory is not
+part of the OS image.
+
+From the repository root:
+
+```sh
+python3 -m http.server 18092 --bind 127.0.0.1 --directory os/site
+```
+
+Open `http://127.0.0.1:18092/`. Deploy the contents of this directory unchanged to
+any static host. Asset paths are relative so a subdirectory works too.
+
+## Content and assets
+
+- The central narrative is **“Agents are the new apps.”** Conversation directs the
+ work; terminal output, diffs, tests, and an optional browser make it inspectable.
+ Follow the [Naming System](../../docs/naming-system.md): Harness is the product,
+ programmers are the first audience, and owning Autonomous hardware is optional.
+- The page walks through installation, encrypted boot, and working with agents.
+ Keep shipped behavior and future hardware support distinct. Ordinary Harness
+ on macOS or another Linux distribution does not show the OS installation UI.
+- Download links target `os-v0.1.0-preview.4`. Update the
+ version, measurements, evidence links, and screenshots together for a release.
+- `assets/hn.png` is the actual hn screen from image validation run
+ [37120135497](https://github.com/autonomous-ai/openharness/actions/runs/37120135497).
+- `assets/install.png` and `assets/unlock.png` are unmodified screenshots from the
+ encrypted UEFI journey in that run: `01b-direct-install-offline.png` and
+ `disk-unlock-2-masked.png`. Passwords are masked. Images link to their full size.
+- `assets/signal-run.png` is actual project output from the successful workload run
+ [37120135497](https://github.com/autonomous-ai/openharness/actions/runs/37120135497).
+ It covers preview 4 and loads lazily inside a native HTML disclosure.
+- Footprint, installation and boot measurements cover preview 4 USB tests at
+ 4 GiB RAM. The separate 1 GiB measurements link to the same image’s test run
+ through the OS README. All project acceptance checks reran on this image;
+ three completed project sources were retained and the game agent ran again.
+ [Three fresh DSH exercises](https://github.com/autonomous-ai/openharness/actions/runs/37120138348)
+ cover this image and its shared viewers too.
+- The preview 4 ThinkPad install/boot/use success is a user report from October 3,
+ 2026, not a measured hardware benchmark. Wi-Fi, suspend, Mac, and NVIDIA claims
+ require their own hardware evidence.
+- The optional 7.4 MB development update links to the same release. It was tested
+ separately in [37124241039](https://github.com/autonomous-ai/openharness/actions/runs/37124241039).
+ The update bundle is for installed systems, not USB flashing.
+- Geist and Geist Mono are the repository's existing fonts, converted to WOFF.
+ Their SIL Open Font License is included in `assets/OFL.txt`.
+- The prompt mark is a small local SVG. There are no remote asset requests.
+
+## Validation
+
+Check local asset paths, image dimensions, heading/fragment targets, font loading,
+and the release's download names. Visually inspect desktop and narrow screens;
+use the keyboard to reach every link and toggle the disclosures. Confirm that
+no content overflows at 320 px, 390 px, 768 px, and desktop widths.
+
+The updated page passed HTML5/CSS parsing, asset, font, image-dimension, local
+anchor, and current release-download-name checks on October 3. The user approved visual review, but
+Chrome still rejected the exact local URL on October 3 because of a saved site
+permission. Visual layout and interactive browser checks remain unverified until
+that review succeeds. Do not replace it with an alternate browser or control path.
diff --git a/os/site/assets/OFL.txt b/os/site/assets/OFL.txt
new file mode 100644
index 000000000..04e95fc55
--- /dev/null
+++ b/os/site/assets/OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
\ No newline at end of file
diff --git a/os/site/assets/geist-mono.woff b/os/site/assets/geist-mono.woff
new file mode 100644
index 000000000..b926c11c2
Binary files /dev/null and b/os/site/assets/geist-mono.woff differ
diff --git a/os/site/assets/geist-regular.woff b/os/site/assets/geist-regular.woff
new file mode 100644
index 000000000..99fd7f1a3
Binary files /dev/null and b/os/site/assets/geist-regular.woff differ
diff --git a/os/site/assets/geist-semibold.woff b/os/site/assets/geist-semibold.woff
new file mode 100644
index 000000000..4d517d227
Binary files /dev/null and b/os/site/assets/geist-semibold.woff differ
diff --git a/os/site/assets/hn.png b/os/site/assets/hn.png
new file mode 100644
index 000000000..07e1b2bcd
Binary files /dev/null and b/os/site/assets/hn.png differ
diff --git a/os/site/assets/install.png b/os/site/assets/install.png
new file mode 100644
index 000000000..53936ddcc
Binary files /dev/null and b/os/site/assets/install.png differ
diff --git a/os/site/assets/mark.svg b/os/site/assets/mark.svg
new file mode 100644
index 000000000..a3e13d345
--- /dev/null
+++ b/os/site/assets/mark.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" fill="#1b1d18"/><path d="m14 20 13 12-13 12" fill="none" stroke="#f7f7f2" stroke-width="5"/><path d="M34 44h17" stroke="#dde900" stroke-width="5"/></svg>
diff --git a/os/site/assets/signal-run.png b/os/site/assets/signal-run.png
new file mode 100644
index 000000000..056289e66
Binary files /dev/null and b/os/site/assets/signal-run.png differ
diff --git a/os/site/assets/unlock.png b/os/site/assets/unlock.png
new file mode 100644
index 000000000..e255e144d
Binary files /dev/null and b/os/site/assets/unlock.png differ
diff --git a/os/site/index.html b/os/site/index.html
new file mode 100644
index 000000000..e1966259f
--- /dev/null
+++ b/os/site/index.html
@@ -0,0 +1,173 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="theme-color" content="#f7f7f2">
+ <meta name="description" content="Agents are the new apps. Harness is an operating system built around agents: chat in the terminal, review the work, open a browser when you need it. Built for programmers first.">
+ <meta property="og:title" content="Harness — Agents are the new apps.">
+ <meta property="og:description" content="An operating system built around agents. Your terminal. Your agents. A browser when you need it. Built for programmers first.">
+ <meta property="og:type" content="website">
+ <title>Harness — Agents are the new apps.</title>
+ <link rel="icon" href="assets/mark.svg" type="image/svg+xml">
+ <link rel="preload" href="assets/geist-semibold.woff" as="font" type="font/woff" crossorigin>
+ <link rel="stylesheet" href="style.css">
+</head>
+<body>
+ <a class="skip" href="#main">Skip to content</a>
+ <div class="page">
+ <header class="header">
+ <a class="wordmark" href="#" aria-label="Harness home"><span class="mark" aria-hidden="true">hn<span>_</span></span>harness</a>
+ <nav aria-label="Main navigation">
+ <a href="#how">How it works</a>
+ <a href="https://github.com/autonomous-ai/openharness/tree/main/os">Source <span aria-hidden="true">↗</span></a>
+ <a href="#install">Install <span aria-hidden="true">↓</span></a>
+ </nav>
+ </header>
+
+ <main id="main">
+ <section class="hero" aria-labelledby="headline">
+ <p class="eyebrow">An operating system built around agents <span class="edition">Preview 4</span></p>
+ <div class="hero-grid">
+ <h1 id="headline">Agents are<br>the new apps<span class="period">.</span></h1>
+ <div class="hero-copy">
+ <p class="lead">Turn on your computer.<br>Tell it what to build.</p>
+ <p>Harness boots into a place to work with agents. Describe the task. Let them use the tools. Review what they make, right in the terminal.</p>
+ <p>A browser when the work needs one.<br>Built for programmers first.</p>
+ </div>
+ </div>
+ <div class="hero-actions">
+ <a class="button" href="https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.4/harness-0.1.0-preview.4-x86_64.iso">Download the ISO <span aria-hidden="true">↓</span></a>
+ <a class="text-link" href="https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.4">Release notes <span aria-hidden="true">↗</span></a>
+ <span class="download-meta">x86-64 · 1.50 GiB · Open source</span>
+ </div>
+ </section>
+
+ <figure class="screen">
+ <a href="assets/hn.png" aria-label="Open the Harness home screenshot at full size">
+ <img src="assets/hn.png" width="1280" height="800" alt="Harness running fullscreen, with a recent terminal and keyboard shortcuts for starting an agent and opening the browser." fetchpriority="high">
+ </a>
+ <figcaption><span>The whole desktop.</span><span>Actual preview 4 screenshot. Keyboard first.</span></figcaption>
+ </figure>
+
+ <section id="how" class="section workflow" aria-labelledby="workflow-title">
+ <div class="section-intro">
+ <p class="eyebrow">Conversation is the interface</p>
+ <h2 id="workflow-title">There’s an agent<br>for that.</h2>
+ <p>Build a backend. Fix a bug. Make a game. The starting point is a conversation. Code, commands, diffs, and tests make the work visible.</p>
+ </div>
+ <ol class="steps">
+ <li><span class="step-number">01</span><div><h3>Your agents, in their own panes.</h3><p>Claude Code, Codex, OpenCode, or pi. Press <kbd>Ctrl</kbd> + <kbd>B</kbd>, then <kbd>Shift</kbd> + <kbd>N</kbd> to start one. Keep several conversations going and move between them from the keyboard.</p></div></li>
+ <li><span class="step-number">02</span><div><h3>Ask. Build. Review.</h3><p>Have the agent set up the tools your project needs. Read the changes. Run the tests. Keep going. Want to enter a command yourself? New terminal opens a shell immediately.</p></div></li>
+ <li><span class="step-number">03</span><div><h3>A browser, when it helps.</h3><p>Most work can be reviewed in the terminal. For a website, a game, or a visual viewer, <kbd>Super</kbd> + <kbd>B</kbd> opens Chromium or switches back to Harness. The browser stays closed until you ask.</p></div></li>
+ </ol>
+ </section>
+
+ <section class="section first-boot" aria-labelledby="first-boot-title">
+ <div class="section-heading">
+ <div><p class="eyebrow">The whole OS experience</p><h2 id="first-boot-title">Install. Boot. Work.</h2></div>
+ <p class="section-caption">A few choices up front.<br>Then straight into Harness.</p>
+ </div>
+ <div class="journey">
+ <figure>
+ <a href="assets/install.png" aria-label="Open the actual Harness installer screenshot at full size"><img src="assets/install.png" width="1280" height="800" loading="lazy" alt="Install Harness with four fields: Disk, Encryption, Password, Repeat password. An Install button and a notice that all data on the selected disk will be erased."></a>
+ <figcaption><h3><span class="step-number">01</span> Install from USB.</h3><p>Press Enter on the welcome screen. Choose a disk, keep encryption on or turn it off, enter your password twice, and install. It works offline.</p><p class="caption-note">Want to try first? Press T. Connect to Wi-Fi if needed, then start the bundled OpenCode with its default settings.</p></figcaption>
+ </figure>
+ <figure>
+ <a href="assets/unlock.png" aria-label="Open the actual Harness disk unlock screenshot at full size"><img src="assets/unlock.png" width="1280" height="800" loading="lazy" alt="A yellow ASCII Harness wordmark above Enter your password, with the entered password masked."></a>
+ <figcaption><h3><span class="step-number">02</span> Unlock. Start making.</h3><p>Remove the USB and boot your computer. On an encrypted install, enter your password to open Harness. Your account is already <code>me@harness</code>.</p><p class="caption-note">Start OpenCode, choose another agent, or open a terminal. OpenCode is included; other agents install when selected. Their accounts and model usage are yours.</p></figcaption>
+ </figure>
+ </div>
+ <p class="journey-note">Real screens from preview 4. Installation erases the entire selected disk. <a href="#install">Read the installation guide below.</a></p>
+ </section>
+
+ <section class="section philosophy" aria-labelledby="philosophy-title">
+ <p class="eyebrow">Built by subtraction</p>
+ <div class="philosophy-grid">
+ <h2 id="philosophy-title">No panels.<br>No wallpaper.<br>No ceremony.</h2>
+ <div class="prose">
+ <p>A terminal for the conversation. A browser for work that needs a visual surface. The rest starts with what you ask an agent to do.</p>
+ <p>Underneath is ordinary Arch Linux: the LTS kernel, a package manager, your files, and administrator access. Compilers, databases, containers—install what the project calls for. Your agents can handle the setup.</p>
+ <p>Wi-Fi, audio, clipboard, screen locking, and recovery are included. Minimal still has to be a working computer.</p>
+ </div>
+ </div>
+ <p class="stack"><span>Under the surface</span> Arch Linux <span aria-hidden="true">/</span> labwc <span aria-hidden="true">/</span> foot <span aria-hidden="true">/</span> hn <span aria-hidden="true">/</span> Chromium</p>
+ </section>
+
+ <section class="section measurements" aria-labelledby="measurements-title">
+ <div class="section-heading"><h2 id="measurements-title">Small. Measured.</h2><a class="text-link" href="https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.4/validation.json">Read the evidence <span aria-hidden="true">↗</span></a></div>
+ <dl class="numbers">
+ <div><dt>ISO download</dt><dd>1.50<span>GiB</span></dd></div>
+ <div><dt>Settled idle memory</dt><dd>~500<span>MiB</span></dd></div>
+ <div><dt>Offline VM installation</dt><dd>30–45<span>sec</span></dd></div>
+ </dl>
+ <p class="measurement-note">Preview 4 measurements in 2-vCPU, 4-GiB x86 VMs installed from virtual USB. Idle memory is with agents and browser closed. Installation excludes downloading the image and answering prompts. Physical hardware will differ.</p>
+ <details>
+ <summary>What has actually been tested? <span aria-hidden="true">+</span></summary>
+ <div class="details-content">
+ <p>The keyboard installer, BIOS and UEFI USB boot, automatic RAM-image detection, offline installation, encrypted disks, wrong-password retry, clipboard, browser switching, update retry, and recovery that preserves projects. This exact image passed at 1 GiB and 4 GiB RAM, including a real first agent conversation typed through the keyboard.</p>
+ <p>In the 4-GiB checks, installed BIOS boot reached Harness readiness in 17.3 seconds, including automated login. Encrypted boot showed the password prompt in 4.6 seconds and reached Harness 8.3 seconds after password submission. Settled idle memory was 481–511 MiB. Separate <a href="https://github.com/autonomous-ai/openharness/blob/main/os/README.md#measured-preview-footprint">1-GiB checks measured 396–399 MiB</a>. These are VM observations, not physical power-on benchmarks.</p>
+ <p>OpenCode agents built a Python CLI, a website, a keyboard game, and a Fastify/SQLite app. Three completed projects were retained; the game agent ran again. All 31 unit tests and independent browser/API checks passed on this image. Three fresh domain-specific harness exercises also passed with the shared HTML and game viewers.</p>
+ <p>A user has now reported a successful preview 4 installation, boot, and use on their ThinkPad. This is a user report, without measured hardware timings. Physical Wi-Fi, suspend, Intel Mac support, and NVIDIA workloads still need model-specific validation.</p>
+ <a class="text-link" href="https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.4/harness-examples.zip">Download the projects and harness examples <span aria-hidden="true">↓</span></a>
+ </div>
+ </details>
+ <details class="project-example">
+ <summary>See a game built inside the OS. <span aria-hidden="true">+</span></summary>
+ <div class="details-content">
+ <img src="assets/signal-run.png" width="1280" height="800" loading="lazy" alt="Signal Run, a keyboard-controlled canvas game built by a real OpenCode agent inside Harness. The complete board and control legend fit on screen.">
+ <p>Signal Run. Built with HTML, CSS, and JavaScript by OpenCode in the installed OS. This is project output, separate from the system image.</p>
+ </div>
+ </details>
+ </section>
+
+ <section id="install" class="section install" aria-labelledby="install-title">
+ <div class="section-intro">
+ <p class="eyebrow">0.1.0-preview.4</p>
+ <h2 id="install-title">Give it a machine.<br>Make something.</h2>
+ <p>An x86-64 Intel or AMD PC. Start with 2 GiB RAM and a spare disk of at least 12 GiB. Secure Boot off. A disposable x86 VM works too.</p>
+ <a class="text-link" href="https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.4/INSTALL.md">USB installation guide <span aria-hidden="true">↗</span></a>
+ </div>
+ <div class="install-copy">
+ <ol>
+ <li>Download the ISO and <a href="https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.4/harness-0.1.0-preview.4-x86_64.iso.sha256">verify its checksum</a>.</li>
+ <li>Write the whole image to a USB stick and boot it.</li>
+ <li>Press <kbd>Enter</kbd> on the welcome screen to install.</li>
+ </ol>
+ <p class="install-notice"><strong>The installer erases the entire selected disk.</strong> It does not resize an existing OS. Back up that disk first. Encryption is on by default.</p>
+ <p class="install-note">Choose your disk, set encryption, and enter your password twice. Choose Install to erase that disk and begin. There is no second confirmation. Your account is <code>me@harness</code>.</p>
+ <a class="button" href="https://github.com/autonomous-ai/openharness/releases/download/os-v0.1.0-preview.4/harness-0.1.0-preview.4-x86_64.iso">Download the ISO <span aria-hidden="true">↓</span></a>
+ </div>
+ </section>
+
+ <section class="practical" aria-label="Hardware and updates">
+ <details>
+ <summary>Can I install it on a Mac or an NVIDIA machine? <span aria-hidden="true">+</span></summary>
+ <div class="details-content">
+ <p>The current image targets x86-64 PCs. Our next hardware targets are older Intel Macs without T2, then NVIDIA desktops with RTX 4090 and 5090 cards. Those configurations are not yet validated. Apple Silicon needs a separate ARM image and hardware integration.</p>
+ <p>Local AI is part of the direction. GPU drivers, an inference runtime, a model, and the agent connection all need to work together before we call a configuration supported. This preview does not promise local models out of the box.</p>
+ <a class="text-link" href="https://github.com/autonomous-ai/openharness/blob/main/os/DEVELOPMENT.md#mac-support-targets">Hardware roadmap <span aria-hidden="true">↗</span></a>
+ </div>
+ </details>
+ <details>
+ <summary>Already installed? Update without flashing again. <span aria-hidden="true">+</span></summary>
+ <div class="details-content">
+ <p>Preview 4 has an optional development update bundle of about 7.4 MB. Apply it to an installed system and keep your projects; rollback restores the previous Harness package. Apply, failure recovery, rollback, and encrypted reboot were tested in a VM with a running terminal and project preserved.</p>
+ <p>This is a manual update for an existing installation. Use the ISO above for a USB installer.</p>
+ <a class="text-link" href="https://github.com/autonomous-ai/openharness/releases/tag/os-v0.1.0-preview.4">Update instructions and verified download <span aria-hidden="true">↗</span></a>
+ </div>
+ </details>
+ <details>
+ <summary>Do I need an Autonomous Computer? <span aria-hidden="true">+</span></summary>
+ <div class="details-content">
+ <p>Use your own compatible computer. The longer-term plan also brings Harness to the <a href="https://github.com/autonomous-ai/autonomous-computer">Autonomous Computer</a>, with an optional Harness device for input and status. Those hardware integrations are a roadmap, not a requirement for using the OS.</p>
+ <p>You can also <a href="https://github.com/autonomous-ai/openharness#readme">run Harness in your existing Mac or Linux terminal</a>. The USB installer and OS welcome belong only to the operating system.</p>
+ </div>
+ </details>
+ </section>
+ </main>
+
+ <footer class="footer"><a class="wordmark" href="#">harness<span class="cursor" aria-hidden="true">_</span></a><p>Your computer. Your agents.</p><a href="https://github.com/autonomous-ai/openharness">Open source, by Autonomous <span aria-hidden="true">↗</span></a></footer>
+ </div>
+</body>
+</html>
diff --git a/os/site/style.css b/os/site/style.css
new file mode 100644
index 000000000..8764a0894
--- /dev/null
+++ b/os/site/style.css
@@ -0,0 +1,114 @@
+@font-face{font-family:Geist;src:url('assets/geist-regular.woff') format('woff');font-style:normal;font-weight:400;font-display:swap}
+@font-face{font-family:Geist;src:url('assets/geist-semibold.woff') format('woff');font-style:normal;font-weight:600;font-display:swap}
+@font-face{font-family:'Geist Mono';src:url('assets/geist-mono.woff') format('woff');font-style:normal;font-weight:400;font-display:swap}
+:root{color-scheme:light;--paper:#f7f7f2;--ink:#1b1d18;--muted:#62665b;--line:#d5d8cc;--accent:#dde900;--mono:'Geist Mono',monospace}
+*{box-sizing:border-box}
+html{scroll-padding-top:32px}
+body{margin:0;background:var(--paper);color:var(--ink);font-family:Geist,Arial,sans-serif;font-size:17px;line-height:1.65;-webkit-font-smoothing:antialiased}
+::selection{background:var(--accent);color:var(--ink)}
+a{color:inherit;text-underline-offset:5px;text-decoration-thickness:1px}
+a:hover{text-decoration-color:var(--ink)}
+a:focus-visible,summary:focus-visible{outline:2px solid var(--ink);outline-offset:6px}
+img{display:block;max-width:100%;height:auto}
+p,h1,h2,h3,figure,dl{margin:0}
+p+p{margin-top:22px}
+strong{font-weight:600}
+.page{max-width:1248px;margin:auto;padding:0 48px}
+.skip{position:absolute;left:24px;top:-100px;z-index:2;padding:8px 16px;background:var(--accent)}
+.skip:focus{top:16px}
+.header{height:106px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}
+.wordmark{display:inline-flex;align-items:center;gap:12px;font-size:17px;font-weight:600;letter-spacing:-.035em;text-decoration:none;white-space:nowrap}
+.mark{font-family:var(--mono);font-size:21px;line-height:1;background:var(--ink);color:var(--paper);padding:9px 8px;letter-spacing:-.12em}
+.mark span{color:var(--accent)}
+nav{display:flex;gap:32px;font-size:13px;font-family:var(--mono)}
+nav a{text-decoration:none}
+nav a:hover{text-decoration:underline}
+.hero{padding:72px 0 48px}
+.eyebrow{font-family:var(--mono);font-size:11px;line-height:1.6;letter-spacing:.065em;text-transform:uppercase;color:var(--muted)}
+.edition{display:inline-block;margin-left:14px;padding:2px 7px;border:1px solid var(--line);color:var(--ink);font-size:10px}
+.hero-grid{display:grid;grid-template-columns:1.65fr 1fr;gap:48px;align-items:end;margin-top:30px}
+h1{font-size:clamp(60px,7.5vw,98px);font-weight:600;line-height:1.02;letter-spacing:-.065em}
+.period{color:#8a9300}
+.hero-copy{max-width:350px;padding-bottom:4px;color:var(--muted);font-size:16px;line-height:1.65}
+.hero-copy .lead{font-size:23px;line-height:1.45;letter-spacing:-.035em;color:var(--ink)}
+.hero-copy p+p{margin-top:20px}
+.hero-actions{display:flex;align-items:center;flex-wrap:wrap;gap:28px;margin-top:36px}
+.button{display:inline-flex;gap:40px;align-items:center;justify-content:space-between;min-height:50px;padding:12px 20px;background:var(--accent);color:var(--ink);font-size:14px;font-weight:600;text-decoration:none}
+.button:hover{background:#cbd600}
+.button span{font-size:20px;font-weight:400;line-height:1}
+.text-link{font-size:13px;font-family:var(--mono);text-decoration:underline;text-decoration-color:#a6ab9a}
+.text-link span{margin-left:4px}
+.download-meta{margin-left:auto;font-family:var(--mono);font-size:11px;color:var(--muted)}
+.screen>a{display:block;background:#101010;border:1px solid #24251f}
+.screen img{width:100%}
+.screen figcaption{display:flex;justify-content:space-between;gap:20px;margin-top:16px;font-family:var(--mono);font-size:11px;color:var(--muted)}
+.section{padding:104px 0;border-bottom:1px solid var(--line)}
+.workflow,.install{display:grid;grid-template-columns:1fr 1fr;gap:100px}
+h2{font-size:40px;font-weight:600;line-height:1.12;letter-spacing:-.045em}
+.section-intro h2{margin:24px 0}
+.section-intro>p:not(.eyebrow){max-width:350px;color:var(--muted);font-size:16px}
+.section-intro>.text-link{display:inline-block;margin-top:28px}
+.steps{list-style:none;padding:0;margin:0}
+.steps li{display:flex;gap:24px;padding:25px 0;border-top:1px solid var(--line)}
+.steps li:first-child{padding-top:0;border-top:0}
+.steps li:last-child{padding-bottom:0}
+.step-number{padding-top:4px;font-family:var(--mono);font-size:11px;color:var(--muted)}
+h3{font-size:19px;font-weight:600;line-height:1.5;letter-spacing:-.025em}
+.steps p{margin-top:8px;font-size:15px;color:var(--muted);line-height:1.7}
+.first-boot .section-heading{align-items:end}
+.first-boot h2{margin-top:22px}
+.section-caption{font-size:15px;line-height:1.65;color:var(--muted)}
+.journey{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:40px;margin-top:40px}
+.journey figure>a{display:block;background:#101010;border:1px solid #24251f}
+.journey img{width:100%}
+.journey figcaption{margin-top:24px}
+.journey h3{display:flex;align-items:baseline;gap:14px}
+.journey p{margin-top:12px;font-size:15px;color:var(--muted)}
+.journey .caption-note{font-size:13px}
+.journey-note{margin-top:32px;font-size:12px;color:var(--muted)}
+kbd{font-family:var(--mono);font-size:.8em;border:1px solid var(--line);padding:1px 4px;white-space:nowrap;color:var(--ink)}
+.philosophy-grid{display:grid;grid-template-columns:1fr 1fr;gap:100px;margin-top:30px}
+.philosophy h2{font-size:56px;line-height:1.12;letter-spacing:-.05em}
+.prose{font-size:16px;color:var(--muted)}
+.stack{display:flex;flex-wrap:wrap;align-items:center;gap:14px;margin-top:64px;font-family:var(--mono);font-size:12px}
+.stack>span{color:var(--muted)}
+.stack>span:first-child{margin-right:auto;font-size:11px}
+.section-heading{display:flex;align-items:center;justify-content:space-between;gap:20px}
+.numbers{display:grid;grid-template-columns:repeat(3,1fr);gap:32px;margin:48px 0 24px}
+.numbers>div{border-left:1px solid var(--line);padding-left:28px}
+.numbers>div:first-child{padding-left:0;border:0}
+.numbers dt{font-family:var(--mono);font-size:11px;color:var(--muted)}
+.numbers dd{margin:10px 0 0;font-size:56px;line-height:1.15;letter-spacing:-.06em;font-weight:600;font-variant-numeric:tabular-nums}
+.numbers dd span{margin-left:9px;font-family:var(--mono);font-size:15px;font-weight:400;letter-spacing:-.04em}
+.measurement-note{max-width:750px;font-size:12px;line-height:1.7;color:var(--muted)}
+details{border-top:1px solid var(--line);margin-top:32px}
+details+details{margin-top:0}
+summary{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:18px 0;cursor:pointer;font-size:14px;list-style:none}
+summary::-webkit-details-marker{display:none}
+summary>span{font-family:var(--mono);font-size:20px}
+details[open] summary>span{transform:rotate(45deg)}
+.details-content{max-width:800px;padding:4px 0 28px;color:var(--muted);font-size:14px}
+.details-content>.text-link{display:inline-block;margin-top:22px}
+.project-example .details-content{max-width:none}
+.project-example p{margin-top:16px;font-size:12px}
+.install{border-bottom:0}
+.install-copy ol{margin:0;padding-left:20px;color:var(--muted);font-size:15px}
+.install-copy li{padding-left:4px;margin-bottom:14px}
+pre{margin:26px 0 22px;padding:20px 22px;background:#eceedf;border:1px solid var(--line);overflow:auto;line-height:1.5;font-size:15px}
+code{font-family:var(--mono)}
+code>span{color:#626b44}
+.install-notice,.install-note{font-size:13px;line-height:1.65;color:var(--muted)}
+.install-notice strong{color:var(--ink)}
+.install-note{margin-top:16px}
+.install-copy>.button{margin-top:28px}
+.practical{padding-bottom:72px}
+.practical details:first-child{margin-top:0}
+.footer{display:flex;justify-content:space-between;align-items:center;gap:24px;border-top:1px solid var(--line);padding:30px 0 40px;font-family:var(--mono);font-size:11px;color:var(--muted)}
+.footer .wordmark{font-family:Geist,Arial,sans-serif;color:var(--ink);font-size:16px;gap:0}
+.cursor{color:#7d8500}
+.footer>a:last-child{text-decoration:none}
+@media(min-width:1600px){.page{max-width:1360px;padding:0 64px}.hero{padding-top:90px}.hero-grid{gap:80px}.hero-copy{max-width:380px}.hero-copy .lead{font-size:26px}}
+@media(max-width:900px){.page{padding:0 30px}.hero-grid{gap:32px;grid-template-columns:1.4fr 1fr}h1{font-size:clamp(52px,7.4vw,68px)}.hero-copy .lead{font-size:20px}.hero-copy{font-size:14px}.workflow,.install,.philosophy-grid{gap:48px}.download-meta{flex-basis:100%;margin-left:0}.hero-actions{row-gap:18px}.philosophy h2{font-size:47px}.numbers dd{font-size:43px}.numbers dd span{display:block;margin:6px 0 0;font-size:13px}.stack{gap:10px}.journey{gap:28px}}
+@media(max-width:640px){.page{padding:0 22px}.header{height:84px}.wordmark{font-size:15px}.mark{font-size:19px;padding:8px 7px}nav{gap:20px;font-size:12px}nav>a:first-child{display:none}.hero{padding:48px 0 32px}.hero>.eyebrow{max-width:300px;font-size:10px}.edition{margin-left:0;margin-top:10px;display:table}.hero-grid{display:block;margin-top:26px}h1{font-size:clamp(49px,13.2vw,78px)}.hero-copy{max-width:420px;margin-top:28px;font-size:15px}.hero-copy .lead{font-size:21px}.hero-copy p+p{margin-top:12px}.hero-actions{gap:20px;margin-top:26px}.button{min-height:48px;padding:12px 16px;gap:28px;font-size:13px}.text-link{font-size:12px}.download-meta{font-size:10px}.screen figcaption{display:block;font-size:10px}.screen figcaption>span+span{display:block;margin-top:6px}.section{padding:64px 0}.workflow,.install,.philosophy-grid,.journey{grid-template-columns:1fr;gap:32px}h2{font-size:35px}.section-intro h2{margin:18px 0}.section-intro>p:not(.eyebrow){max-width:none}.philosophy h2{font-size:48px}.philosophy-grid{margin-top:22px}.stack{margin-top:34px;font-size:10px;gap:9px}.stack>span:first-child{flex-basis:100%;margin-bottom:4px}.section-heading,.first-boot .section-heading{align-items:start;flex-direction:column;gap:16px}.journey{margin-top:28px;gap:36px}.journey figcaption{margin-top:18px}.journey-note{font-size:11px}.numbers{gap:12px;margin-top:32px;margin-bottom:22px}.numbers>div{padding-left:12px}.numbers dt{font-size:9px;line-height:1.6;max-width:90px;min-height:30px}.numbers dd{font-size:clamp(24px,7vw,34px);letter-spacing:-.065em}.numbers dd span{display:block;margin:6px 0 0;font-size:12px;letter-spacing:0}.measurement-note{font-size:11px}summary{font-size:13px}.details-content{font-size:13px}.install-copy>.button{width:100%}.practical{padding-bottom:48px}.footer{flex-wrap:wrap;gap:16px;padding:26px 0 32px}.footer .wordmark{flex-basis:40%}.footer p{margin-left:auto}.footer>a:last-child{flex-basis:100%}}
+@media(max-width:380px){nav>a:nth-child(2){display:none}.hero-actions{column-gap:16px}}
+@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}}
diff --git a/os/system.py b/os/system.py
new file mode 100644
index 000000000..f459a5111
--- /dev/null
+++ b/os/system.py
@@ -0,0 +1,336 @@
+#!/usr/bin/env python3
+"""Explicit OS updates and offline recovery. No updater daemon or scheduled downloads."""
+from __future__ import annotations
+import argparse
+from contextlib import contextmanager
+from datetime import datetime, timedelta, timezone
+import fcntl
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import stat
+import subprocess
+import tempfile
+import uuid
+
+PACMAN_CONFIG = Path('/etc/pacman.conf')
+UPDATE_RECEIPT = Path('/var/lib/harness-os/update.json')
+CHECKPOINTS = Path('/.snapshots')
+
+
+def run(*args, capture=False):
+ return subprocess.run([str(a) for a in args], check=True, text=True,
+ stdout=subprocess.PIPE if capture else None).stdout
+
+
+def read_json(path):
+ return json.loads(path.read_text())
+
+
+def write_json(path, data):
+ temporary = path.with_suffix(path.suffix + '.new')
+ with temporary.open('w') as handle:
+ handle.write(json.dumps(data, indent=2) + '\n')
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.replace(path)
+ directory = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+
+
+def pending_update():
+ if not UPDATE_RECEIPT.exists():
+ return None
+ receipt = read_json(UPDATE_RECEIPT)
+ if not isinstance(receipt, dict):
+ raise ValueError('Invalid system-update receipt; inspect it before changing packages.')
+ if receipt.get('exit_status') == 0:
+ return None
+ if not isinstance(receipt.get('snapshot'), str) or not isinstance(receipt.get('checkpoint'), str):
+ raise ValueError('Incomplete system-update receipt; use the live USB to inspect recovery checkpoints.')
+ checkpoint_name(receipt['checkpoint'])
+ return receipt
+
+
+def snapshot_date(value):
+ try:
+ date = datetime.strptime(value, '%Y/%m/%d').date()
+ except ValueError as error:
+ raise argparse.ArgumentTypeError('Use an Arch snapshot date in YYYY/MM/DD form.') from error
+ if value != date.strftime('%Y/%m/%d') or date >= datetime.now(timezone.utc).date():
+ raise argparse.ArgumentTypeError('Use a complete dated repository snapshot before today.')
+ return value
+
+
+def checkpoint_name(value):
+ if not re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}', value):
+ raise ValueError('Invalid checkpoint name.')
+ return value
+
+
+def validate_checkpoint(meta, root_uuid):
+ if meta.get('root_uuid') != root_uuid:
+ raise ValueError('Checkpoint belongs to a different root filesystem.')
+ if not re.fullmatch(r'[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}', meta.get('boot_uuid', '')):
+ raise ValueError('Checkpoint has an invalid boot partition identifier.')
+ required = {'vmlinuz-linux-lts', 'initramfs-linux-lts.img', 'grub/grub.cfg'}
+ if not required.issubset(meta.get('boot_sha256', {})):
+ raise ValueError('Checkpoint is missing the kernel, initramfs or boot configuration.')
+
+
+def physical_disks(device):
+ data = json.loads(run('lsblk', '--inverse', '--json', '--paths', '--output', 'NAME,TYPE', device, capture=True))
+ def collect(node):
+ result = {node['name']} if node['type'] == 'disk' else set()
+ for child in node.get('children', []):
+ result.update(collect(child))
+ return result
+ result = set()
+ for node in data['blockdevices']:
+ result.update(collect(node))
+ return result
+
+
+@contextmanager
+def operation_lock():
+ with open('/run/lock/hn-os.lock', 'w') as handle:
+ try:
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError as error:
+ raise ValueError('Another hn-os system operation is running.') from error
+ yield
+
+
+def boot_hashes(folder):
+ result = {}
+ for path in sorted(folder.rglob('*')):
+ if path.is_file():
+ with path.open('rb') as handle:
+ result[str(path.relative_to(folder))] = hashlib.file_digest(handle, 'sha256').hexdigest()
+ return result
+
+
+def installed():
+ receipt = Path('/var/lib/harness-os/install.json')
+ if not receipt.is_file() or run('findmnt', '-n', '-o', 'FSTYPE', '/', capture=True).strip() != 'btrfs':
+ raise ValueError('This operation requires an installed Harness system.')
+ info = read_json(receipt)
+ for mount in ['/', '/.snapshots']:
+ actual = run('findmnt', '-n', '-o', 'UUID', '--mountpoint', mount, capture=True).strip()
+ if actual != info['root_uuid']:
+ raise ValueError(f'{mount} is not on the installed system filesystem.')
+ if run('findmnt', '-n', '-o', 'UUID', '--mountpoint', '/boot', capture=True).strip() != info['boot_uuid']:
+ raise ValueError('The matching boot partition must be mounted before making a checkpoint.')
+ return info
+
+
+def checkpoint(reason='manual', pacman_hook=False):
+ if pacman_hook and pending_update():
+ raise ValueError('A full system update did not finish. Run sudo hn-os update to complete it before changing packages, or recover its checkpoint from the live USB.')
+ info = installed()
+ if Path('/var/lib/pacman/db.lck').exists() and not pacman_hook:
+ raise ValueError('Wait for the active package transaction before making a checkpoint.')
+ name = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ-') + uuid.uuid4().hex[:8]
+ base = CHECKPOINTS
+ pending = base / ('.' + name + '.pending')
+ pending.mkdir(mode=0o700)
+ try:
+ run('sync')
+ run('btrfs', 'subvolume', 'snapshot', '-r', '/', pending / 'root')
+ shutil.copytree('/boot', pending / 'boot')
+ metadata = {'name': name, 'created_at': datetime.now(timezone.utc).isoformat(),
+ 'reason': reason, 'root_uuid': info['root_uuid'], 'boot_uuid': info['boot_uuid'],
+ 'boot_sha256': boot_hashes(pending / 'boot')}
+ validate_checkpoint(metadata, info['root_uuid'])
+ write_json(pending / 'checkpoint.json', metadata)
+ run('sync')
+ pending.rename(base / name)
+ except BaseException:
+ if (pending / 'root').exists():
+ run('btrfs', 'subvolume', 'delete', pending / 'root')
+ shutil.rmtree(pending)
+ raise
+ print(f'Checkpoint {name}', flush=True)
+ return name
+
+
+def advance_snapshot(config, date):
+ pattern = re.compile(r'(https://archive\.archlinux\.org/repos/)(\d{4}/\d{2}/\d{2})(/\$repo/os/\$arch)')
+ dates = {match.group(2) for match in pattern.finditer(config)}
+ if len(dates) != 1:
+ raise ValueError('Expected one managed Arch snapshot. Custom mirror setups should use their normal full-upgrade procedure.')
+ if date < next(iter(dates)):
+ raise ValueError('Use offline checkpoint recovery to go back. Updates must not move the repository date backward.')
+ # Preserve user-added repositories, Includes, signature policy and options.
+ return pattern.sub(lambda match: match.group(1) + date + match.group(3), config)
+
+
+def update(date):
+ # Pin every repository to the same date, and perform a full upgrade. Never mix
+ # a newly synced package database with an intentionally old installed base.
+ config = PACMAN_CONFIG
+ advanced = advance_snapshot(config.read_text(), date)
+ pending = pending_update()
+ if pending:
+ # A retry must retain the original good system, not replace its recovery
+ # point with a snapshot of a potentially half-upgraded root.
+ previous = pending['checkpoint']
+ saved = CHECKPOINTS / previous
+ validate_checkpoint(read_json(saved / 'checkpoint.json'), installed()['root_uuid'])
+ if not (saved / 'root').is_dir():
+ raise ValueError('The original update checkpoint is missing; use the live USB for recovery.')
+ else:
+ previous = checkpoint('before-update')
+ receipt = {'snapshot': date, 'checkpoint': previous,
+ 'started_at': datetime.now(timezone.utc).isoformat(), 'exit_status': None}
+ # Persist before changing repositories or invoking pacman. A crash or Ctrl-C
+ # leaves this guard in place until a complete upgrade succeeds.
+ write_json(UPDATE_RECEIPT, receipt)
+ temporary = config.with_suffix('.hn-next')
+ temporary.write_text(advanced)
+ temporary.chmod(stat.S_IMODE(config.stat().st_mode))
+ temporary.replace(config)
+ result = subprocess.run(['pacman', '-Syyu'])
+ receipt.update(finished_at=datetime.now(timezone.utc).isoformat(), exit_status=result.returncode)
+ write_json(UPDATE_RECEIPT, receipt)
+ if result.returncode:
+ raise ValueError(f'Update did not complete. Run sudo hn-os update to retry before changing packages. Checkpoint {previous} is available from the live USB; see hn-os help.')
+ print('Update completed. Reboot to use the updated kernel. The previous system is retained in ' + previous)
+
+
+def mounted_device(device, mountinfo=Path('/proc/self/mountinfo')):
+ dev = os.stat(device)
+ if not stat.S_ISBLK(dev.st_mode):
+ raise ValueError('Select a block device, such as /dev/sda3 or an unlocked /dev/mapper device.')
+ identity = f'{os.major(dev.st_rdev)}:{os.minor(dev.st_rdev)}'
+ return any(line.split()[2] == identity for line in mountinfo.read_text().splitlines())
+
+
+def copy_contents(source, destination):
+ # These paths are our whole-disk install's boot partition and its checkpoint.
+ # FAT has no Unix owners/modes, so restore contents without copying metadata.
+ for path in destination.iterdir():
+ if path.is_dir():
+ shutil.rmtree(path)
+ else:
+ path.unlink()
+ for path in source.rglob('*'):
+ target = destination / path.relative_to(source)
+ if path.is_dir():
+ target.mkdir(parents=True, exist_ok=True)
+ elif path.is_file():
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(path, target)
+
+
+def recover(device, name=None):
+ device = Path(device).resolve(strict=True)
+ if not str(device).startswith('/dev/') or mounted_device(device):
+ raise ValueError('Recovery requires an unmounted root device. Boot the live USB first.')
+ with tempfile.TemporaryDirectory(prefix='hn-recovery-', dir='/mnt') as temp:
+ top = Path(temp)
+ boot = top / '.hn-recovery-boot'
+ run('mount', '-t', 'btrfs', '-o', 'subvolid=5', device, top)
+ boot_mounted = False
+ try:
+ checkpoints = top / '@snapshots'
+ if name is None:
+ for meta in sorted(checkpoints.glob('*/checkpoint.json')):
+ item = read_json(meta)
+ print(f'{item["name"]} {item["created_at"]} {item["reason"]}')
+ return
+ chosen = checkpoints / checkpoint_name(name)
+ meta = read_json(chosen / 'checkpoint.json')
+ actual_uuid = run('blkid', '-s', 'UUID', '-o', 'value', device, capture=True).strip()
+ validate_checkpoint(meta, actual_uuid)
+ if boot_hashes(chosen / 'boot') != meta['boot_sha256']:
+ raise ValueError('Checkpoint boot-file checksums do not match. Nothing restored.')
+ boot_device = Path('/dev/disk/by-uuid') / meta['boot_uuid']
+ roots = physical_disks(device)
+ if len(roots) != 1 or roots != physical_disks(boot_device):
+ raise ValueError('Root and boot partitions must belong to the same installed disk.')
+ if mounted_device(boot_device):
+ raise ValueError('The installed boot partition is mounted. Unmount it before recovery.')
+ boot.mkdir()
+ run('mount', '-t', 'vfat', boot_device, boot)
+ boot_mounted = True
+ suffix = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ-') + uuid.uuid4().hex[:8]
+ saved = checkpoints / ('before-recovery-' + suffix)
+ restoring = top / ('@restoring-' + suffix)
+ saved.mkdir(mode=0o700)
+ shutil.copytree(boot, saved / 'boot')
+ run('btrfs', 'subvolume', 'snapshot', chosen / 'root', restoring)
+ # PreTransaction snapshots contain pacman's active transaction lock.
+ # No package manager owns it in this offline recovery candidate.
+ (restoring / 'var/lib/pacman/db.lck').unlink(missing_ok=True)
+ try:
+ copy_contents(chosen / 'boot', boot)
+ run('sync')
+ if boot_hashes(boot) != meta['boot_sha256']:
+ raise ValueError('Restored boot files failed verification.')
+ # A previous interrupted recovery can have moved @ already.
+ # A fresh candidate also avoids colliding with its staging subvolume.
+ if (top / '@').exists():
+ (top / '@').rename(saved / 'root')
+ restoring.rename(top / '@')
+ except BaseException:
+ copy_contents(saved / 'boot', boot)
+ if (saved / 'root').exists() and not (top / '@').exists():
+ (saved / 'root').rename(top / '@')
+ if restoring.exists():
+ run('btrfs', 'subvolume', 'delete', restoring)
+ raise
+ run('sync')
+ print(f'Restored {name}; projects in @home were preserved. Remove the USB and reboot.')
+ print(f'The replaced system is retained in @snapshots/{saved.name}.')
+ finally:
+ if boot_mounted:
+ run('umount', boot)
+ if boot.exists():
+ boot.rmdir()
+ run('umount', top)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ sub = parser.add_subparsers(dest='command', required=True)
+ cp = sub.add_parser('checkpoint', help='Save root and matching boot files before a system change')
+ cp.add_argument('--pacman-hook', action='store_true', help=argparse.SUPPRESS)
+ up = sub.add_parser('update', help='Checkpoint, then upgrade the whole system to a dated Arch snapshot')
+ up.add_argument('--snapshot', type=snapshot_date,
+ default=(datetime.now(timezone.utc).date() - timedelta(days=1)).strftime('%Y/%m/%d'))
+ re = sub.add_parser('recover', help='From the live USB, list or restore an offline system checkpoint')
+ re.add_argument('device', help='Unmounted root filesystem; unlock LUKS with cryptsetup first if encrypted')
+ re.add_argument('checkpoint', nargs='?', help='Omit to list available checkpoints without restoring')
+ args = parser.parse_args()
+ if os.geteuid() != 0:
+ parser.error('Run with sudo.')
+ # The image builder and initial installer are not installed systems. The hook
+ # is inert there; normal users cannot bypass it through a missing mount.
+ if args.command == 'checkpoint' and args.pacman_hook:
+ if not Path('/var/lib/harness-os/install.json').is_file():
+ return
+ # hn-os update already holds this lock and made the same checkpoint.
+ if os.environ.get('HN_OS_UPDATE_CHECKPOINT') == '1':
+ return
+ with operation_lock():
+ if args.command == 'checkpoint':
+ checkpoint('before-packages' if args.pacman_hook else 'manual', args.pacman_hook)
+ elif args.command == 'update':
+ os.environ['HN_OS_UPDATE_CHECKPOINT'] = '1'
+ update(args.snapshot)
+ else:
+ recover(args.device, args.checkpoint)
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except (ValueError, subprocess.CalledProcessError, OSError, KeyboardInterrupt) as error:
+ raise SystemExit(f'System operation stopped: {error}')
diff --git a/os/tests/agents.sh b/os/tests/agents.sh
new file mode 100644
index 000000000..3c8245280
--- /dev/null
+++ b/os/tests/agents.sh
@@ -0,0 +1,18 @@
+#!/usr/bin/env bash
+# Run only in the disposable installed VM as its ordinary user. No accounts or
+# API calls: this checks that real vendor executables install and start here.
+set -euo pipefail
+REPORT_DIR="$HOME/.local/state/harness-os/agent-check"
+mkdir -p "$REPORT_DIR"
+trap 'printf "%s\n" "$?" > "$REPORT_DIR/status"' EXIT
+test "$(npm prefix -g)" = "$HOME/.local"
+for row in 'claude @anthropic-ai/claude-code' 'codex @openai/codex'; do
+ read -r executable package <<< "$row"
+ npm install --global --no-audit --no-fund "$package"
+ "$executable" --version | tee "$REPORT_DIR/$executable.txt"
+done
+/usr/bin/opencode --version | tee "$REPORT_DIR/opencode.txt"
+npm install --global --ignore-scripts --no-audit --no-fund @earendil-works/pi-coding-agent
+pi --version | tee "$REPORT_DIR/pi.txt"
+npm ls --global --depth=0 --json > "$REPORT_DIR/packages.json"
+printf '%s\n' 'Vendor installation and startup passed. Authenticated agent turns are a separate, unverified check.'
diff --git a/os/tests/development.sh b/os/tests/development.sh
new file mode 100644
index 000000000..110d29aba
--- /dev/null
+++ b/os/tests/development.sh
@@ -0,0 +1,25 @@
+#!/usr/bin/env bash
+# Run in a fresh installed VM's hn pane after installing gcc/make on demand.
+set -euo pipefail
+REPORT_DIR="$HOME/.local/state/harness-os/development-check"
+mkdir -p "$REPORT_DIR" "$HOME/Projects/os-validation"
+trap 'printf "%s\n" "$?" > "$REPORT_DIR/status"' EXIT
+cd "$HOME/Projects/os-validation"
+git init -q
+cat > main.c <<'C'
+#include <stdio.h>
+int main(void) { puts("harness-compiled-ok"); return 0; }
+C
+printf 'hello: main.c\n\t$(CC) -Wall -Wextra -Werror -O2 main.c -o hello\n' > Makefile
+make
+test "$(./hello)" = harness-compiled-ok
+git add main.c Makefile
+git diff --cached --check
+cat > server.mjs <<'JS'
+import http from 'node:http';
+http.createServer((request, response) => {
+ response.writeHead(200, {'content-type': 'text/html'});
+ response.end('<!doctype html><title>Harness preview</title><h1>Local development works.</h1><p>Served by Node from an hn terminal pane.</p>');
+}).listen(18781, '127.0.0.1');
+JS
+printf '%s\n' 'Compiled and ran C, checked a Git diff, and prepared a local Node preview.'
diff --git a/os/tests/dsh/exercise.mjs b/os/tests/dsh/exercise.mjs
new file mode 100644
index 000000000..68c2b8e69
--- /dev/null
+++ b/os/tests/dsh/exercise.mjs
@@ -0,0 +1,140 @@
+// Real managed agents, materialized DSHs and shared viewers inside the guest.
+import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
+import { join } from 'node:path';
+import { chromium } from 'playwright';
+
+const [root, report] = process.argv.slice(2);
+const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
+const read = path => { try { return readFileSync(path, 'utf8'); } catch { return ''; } };
+async function until(label, test, timeout = 120_000) {
+ const deadline = Date.now() + timeout;
+ while (Date.now() < deadline) {
+ const value = await test();
+ if (value) return value;
+ await delay(500);
+ }
+ throw new Error(`Timed out: ${label}`);
+}
+const status = await (await fetch('http://127.0.0.1:18473/api/status')).json();
+assert.ok(status.machineId);
+const agents = new Map(), pending = new Map(), frames = [];
+const ws = new WebSocket('ws://127.0.0.1:18473/api/local-ws');
+let connected = false;
+ws.addEventListener('message', event => {
+ const frame = JSON.parse(event.data);
+ const { type, payload } = frame;
+ if (type === 'connected') connected = true;
+ if (type === 'agent_synced' && payload?.agent) agents.set(payload.agent.id, payload.agent);
+ if (type?.endsWith('_result') && payload?.requestId && pending.has(payload.requestId)) {
+ pending.get(payload.requestId)(payload); pending.delete(payload.requestId);
+ }
+ if (type === 'agent_synced' || type?.endsWith('_result')) frames.push(frame);
+});
+function request(type, payload, timeout = 180_000) {
+ const requestId = randomUUID();
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => { pending.delete(requestId); reject(new Error(`${type} timed out`)); }, timeout);
+ pending.set(requestId, value => { clearTimeout(timer); resolve(value); });
+ ws.send(JSON.stringify({ type, payload: { ...payload, requestId } }));
+ });
+}
+await until('WebSocket open', () => ws.readyState === WebSocket.OPEN, 15_000);
+ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId: status.machineId, localProtocolVersion: 1 } }));
+await until('local machine handshake', () => connected, 15_000);
+const list = await request('dsh_list', {});
+for (const name of ['hello', 'logs', 'game']) assert.ok(list.dsh?.some(d => d.id === `os-lab/${name}` && d.installed));
+
+const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', chromiumSandbox: true, headless: true });
+const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
+const results = [];
+try {
+ for (const name of ['hello', 'logs', 'game']) {
+ let agent;
+ const cwd = join(root, 'projects', name), started = Date.now();
+ mkdirSync(cwd, { recursive: true });
+ const page = await context.newPage();
+ try {
+ const created = await request('agent_create', { engine: 'opencode', cwd, dsh: `os-lab/${name}`,
+ creationId: randomUUID(), bypassPermission: true,
+ prompt: 'Read TASK.txt and perform the complete task now. Run the tests, fix failures, and report the result. No questions or subagents.' });
+ assert.equal(created.state, 'created', JSON.stringify(created));
+ agent = created.agent;
+ agents.set(agent.id, agent);
+ assert.equal(agent.dsh, `os-lab/${name}`);
+ await until('materialized instructions and task', () => existsSync(join(cwd, 'AGENTS.md')) && existsSync(join(cwd, 'TASK.txt')));
+ execFileSync('hn', ['open-harness', '-s', agent.id], { timeout: 30_000 });
+ if (name === 'hello') {
+ await until('agent writes Ada greeting', () => /Hello,\s*Ada!/.test(read(join(cwd, 'index.html'))), 12 * 60_000);
+ const viewer = await until('web viewer URL', () => agents.get(agent.id)?.viewerUrl);
+ await page.goto(viewer);
+ const heading = page.frameLocator('iframe').locator('h1');
+ await heading.waitFor();
+ assert.match(await heading.innerText(), /Hello,\s*Ada!/);
+ // A real edit must reload the shared viewer without restarting its agent.
+ writeFileSync(join(cwd, 'index.html'), read(join(cwd, 'index.html')).replace('Hello, Ada!', 'Hello, Grace!'));
+ await until('live viewer reload', async () => /Hello,\s*Grace!/.test(await heading.innerText().catch(() => '')));
+ } else if (name === 'logs') {
+ await until('agent generates CSV tool and result', () => existsSync(join(cwd, 'count.py')) && existsSync(join(cwd, 'result.json')), 12 * 60_000);
+ const output = execFileSync('python3', ['count.py', 'sample.csv'], { cwd, timeout: 30_000 }).toString();
+ assert.deepEqual(JSON.parse(output), { bug: 2, feature: 1 });
+ const input = execFileSync('python3', ['count.py', '-'], { cwd, input: 'kind,title\nchore,Probe\n', timeout: 30_000 }).toString();
+ assert.deepEqual(JSON.parse(input), { chore: 1 });
+ assert.ok(!agents.get(agent.id)?.viewerUrl, 'Terminal DSH must not create a viewer');
+ writeFileSync(join(report, 'logs-output.json'), output);
+ execFileSync('python3', ['-m', 'unittest', 'discover', '-v'], { cwd, timeout: 30_000 });
+ } else {
+ await until('agent implements game change and tests', () => existsSync(join(cwd, 'state.mjs')) && existsSync(join(cwd, 'test.mjs')) && existsSync(join(cwd, 'agent-result.txt')), 12 * 60_000);
+ writeFileSync(join(report, 'game-unit-tests.txt'), execFileSync('node', ['--test', 'test.mjs'], { cwd, timeout: 30_000 }));
+ const viewer = await until('game viewer URL', () => agents.get(agent.id)?.viewerUrl);
+ await page.goto(viewer);
+ await until('game truly rendered', async () => {
+ const state = await (await fetch(new URL('/api/state', viewer))).json();
+ return state.status === 'ready';
+ });
+ assert.equal(JSON.parse(read(join(cwd, '.harness/verdict.json'))).ready, true);
+ await page.locator('#play').focus(); await page.keyboard.press('Enter');
+ const frame = await until('playable frame', () => page.frames().find(f => f !== page.mainFrame() && !f.isDetached()));
+ assert.ok(await frame.evaluate(() => {
+ const board = document.querySelector('canvas').getBoundingClientRect();
+ const score = document.querySelector('#score').getBoundingClientRect();
+ return board.top >= 0 && board.height > 100 && board.bottom <= innerHeight &&
+ score.bottom <= innerHeight && document.documentElement.scrollHeight <= innerHeight + 1;
+ }), 'The entire board and score fit inside the shared viewer');
+ await frame.locator('canvas').focus();
+ await page.keyboard.press('ArrowRight'); await page.keyboard.press('ArrowRight');
+ assert.equal(await frame.evaluate(() => window.harnessGame.stats().score), 1);
+ await page.keyboard.press('r');
+ assert.equal(await frame.evaluate(() => window.harnessGame.stats().score), 0);
+ assert.deepEqual(await frame.evaluate(() => window.harnessGame.stats().player), { x: 1, y: 1 });
+ await page.locator('#pause').focus(); await page.keyboard.press('Enter');
+ // The toolbar sends a postMessage to the game. Input delivery and the
+ // iframe's receipt are separate browser tasks.
+ await until('pause reaches game frame', () => frame.evaluate(() => window.harnessGame.stats().paused), 10_000);
+ await page.locator('#details').focus(); await page.keyboard.press('Enter');
+ await page.locator('#export').focus(); await page.keyboard.press('Enter');
+ await until('standalone game export', () => existsSync(join(cwd, 'out')) && readdirSync(join(cwd, 'out')).some(name => name.startsWith('game-') && existsSync(join(cwd, 'out', name, 'index.html'))));
+ }
+ if (name !== 'logs') await page.screenshot({ path: join(report, `${name}-viewer.png`), fullPage: true });
+ results.push({ name, status: 'passed', agentId: agent.id, seconds: (Date.now() - started) / 1000 });
+ } catch (error) {
+ results.push({ name, status: 'failed', error: error.stack || String(error), seconds: (Date.now() - started) / 1000 });
+ await page.screenshot({ path: join(report, `${name}-failure.png`) }).catch(() => {});
+ } finally {
+ if (agent?.tmuxPane) {
+ try { writeFileSync(join(report, `${name}-terminal.txt`), execFileSync('tmux', ['capture-pane', '-p', '-S', '-200', '-t', agent.tmuxPane], { timeout: 10_000 })); } catch {}
+ }
+ if (agent) await request('agent_delete', { agentId: agent.id }, 30_000).catch(error => console.error(String(error)));
+ await page.close();
+ writeFileSync(join(report, 'results.json'), JSON.stringify(results, null, 2));
+ console.log(JSON.stringify(results.at(-1)));
+ }
+ }
+} finally {
+ writeFileSync(join(report, 'frames.json'), JSON.stringify(frames, null, 2));
+ await browser.close();
+ ws.close();
+}
+if (results.some(row => row.status !== 'passed')) process.exitCode = 1;
diff --git a/os/tests/dsh/prepare.py b/os/tests/dsh/prepare.py
new file mode 100644
index 000000000..0d8a2020e
--- /dev/null
+++ b/os/tests/dsh/prepare.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+"""Create disposable DSHs from the repository's real shared components."""
+import json
+from pathlib import Path
+import shutil
+import sys
+
+components, root = map(Path, sys.argv[1:])
+packages = root / 'packages'
+packages.mkdir(parents=True, exist_ok=True)
+
+
+def write(folder, name, text):
+ path = folder / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+
+
+def manifest(name, title, viewer=None):
+ # A disposable guest has no provider credentials. Leave model selection to
+ # upstream defaults. OpenCode 2's interactive command rejects --agent;
+ # these tasks need no custom primary agent, only bounded test permissions.
+ config = {'permission': {'question': 'deny', 'task': 'deny'}}
+ result = {'spec': 1, 'id': f'os-lab/{name}', 'name': title, 'category': 'OS acceptance',
+ 'author': 'Harness OS test', 'engine': 'opencode',
+ 'workspace': {'template': 'template', 'marker': 'TASK.txt'},
+ 'agent': {'instructions': 'AGENTS.md',
+ 'env': {'DSH_PERMISSION_MODE': 'auto', 'OPENCODE_CONFIG_CONTENT': json.dumps(config)}}}
+ if viewer:
+ result['viewer'] = {'use': viewer}
+ return result
+
+
+hello = packages / 'hello'
+shutil.copytree(components / 'examples/hello-world', hello, dirs_exist_ok=True)
+write(hello, 'harness.json', json.dumps(manifest('hello', 'Hello Harness', 'autonomous/web-viewer')))
+write(hello, 'template/TASK.txt', 'Change the existing heading in index.html to Hello, Ada! Preserve the rest of the page. Read the saved file back. Do not ask questions or use subagents.\n')
+
+logs = packages / 'logs'
+write(logs, 'harness.json', json.dumps(manifest('logs', 'Terminal Log Counter')))
+write(logs, 'AGENTS.md', 'Build small Python command-line tools. Use the standard library, run tests, and report real results. Read TASK.txt and work inside this project. No questions or subagents.\n')
+write(logs, 'template/TASK.txt', 'Create count.py accepting a CSV path (or - for stdin). Count rows by the kind column and print a JSON object. Write unittest tests for empty input and aggregation and run them. Run count.py sample.csv and save the output to result.json. Do not modify sample.csv.\n')
+write(logs, 'template/sample.csv', 'kind,title\nbug,Missing focus\nfeature,Keyboard shortcut\nbug,Wrong count\n')
+
+game = packages / 'game'
+spec = manifest('game', 'Packet Step', 'autonomous/game-viewer')
+spec['verdict'] = '.harness/verdict.json'
+spec['toolchain'] = {'setup': 'npm install --no-audit --no-fund',
+ 'doctor': 'node -e "require.resolve(\'vite\')"'}
+write(game, 'harness.json', json.dumps(spec))
+write(game, 'package.json', json.dumps({'private': True, 'type': 'module', 'dependencies': {'vite': '6.4.3'}}))
+write(game, 'AGENTS.md', 'You maintain a small keyboard game. Preserve the harnessGame bridge and its state schema. Test changes with node --test. Work only inside the project; no questions or subagents.\n')
+write(game, 'template/TASK.txt', 'Extend the starter game: pressing R must call the existing restart() function and reset score and position. Add exported resetState() in state.mjs returning {x:1,y:1,score:0}, use it in game.mjs, and add meaningful node:test tests in test.mjs. Run node --test test.mjs and save a short result in agent-result.txt. Keep the viewer bridge, readiness event and existing arrow keys working.\n')
+write(game, 'template/index.html', '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Packet Step</title>
+<style>*{box-sizing:border-box}body{height:100dvh;margin:0;padding:8px;background:#111821;color:#d3e8ed;font:18px monospace;text-align:center;display:flex;flex-direction:column;align-items:center;gap:6px}canvas{min-height:0;flex:1;width:100%;max-width:600px;object-fit:contain;background:#18232e}h1{font-size:24px;margin:0}p{font-size:15px;margin:0}</style>
+<h1>Packet Step</h1><p>Arrow keys move · R restarts · collect the green packet</p><canvas width="600" height="400" tabindex="0" aria-label="Packet Step game"></canvas><p id="score">Score 0</p><script type="module" src="./game.mjs"></script></html>''')
+write(game, 'template/studio.json', json.dumps({'title': 'Packet Step', 'description': 'A tiny keyboard game built inside Harness.', 'controls': 'Arrow keys move · R restarts'}))
+write(game, 'template/game.mjs', '''const canvas=document.querySelector('canvas'), ctx=canvas.getContext('2d');
+let state={x:1,y:1,score:0}, paused=false, mode='explore';
+function draw(){ctx.fillStyle='#18232e';ctx.fillRect(0,0,600,400);ctx.strokeStyle='#263746';for(let x=0;x<15;x++)for(let y=0;y<10;y++)ctx.strokeRect(x*40,y*40,40,40);ctx.fillStyle='#73e0a8';ctx.fillRect(3*40+10,50,20,20);ctx.fillStyle='#70bdff';ctx.fillRect(state.x*40+6,state.y*40+6,28,28);document.querySelector('#score').textContent='Score '+state.score;}
+function restart(){state={x:1,y:1,score:0};draw();window.dispatchEvent(new CustomEvent('harness:timeline-reset'));}
+window.addEventListener('keydown',event=>{if(paused||mode!=='play')return;const delta={ArrowRight:[1,0],ArrowLeft:[-1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[event.key];if(!delta)return;event.preventDefault();state.x=Math.max(0,Math.min(14,state.x+delta[0]));state.y=Math.max(0,Math.min(9,state.y+delta[1]));if(state.x===3&&state.y===1)state.score++;draw();});
+window.harnessGame={setMode(value){mode=value;canvas.focus();},setPaused(value){paused=value;},restart,stats(){return{score:state.score,player:{x:state.x,y:state.y},paused,objects:2,running:true};},captureState(){return{schema:'packet-step/1',...state};},restoreState(value){if(value.schema!=='packet-step/1'||![value.x,value.y,value.score].every(Number.isFinite))throw Error('Invalid snapshot');state={x:value.x,y:value.y,score:value.score};draw();}};
+draw();requestAnimationFrame(()=>window.dispatchEvent(new CustomEvent('harness:ready')));
+''')
+print(packages)
diff --git a/os/tests/dsh/run.sh b/os/tests/dsh/run.sh
new file mode 100644
index 000000000..34aa8d6d6
--- /dev/null
+++ b/os/tests/dsh/run.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+set -euo pipefail
+INPUTS=$(cd -- "$(dirname -- "$0")" && pwd)
+ROOT="$HOME/Projects/os-dsh"
+REPORT="$HOME/.local/state/harness-os/dsh-check"
+mkdir -p "$REPORT" "$ROOT/qa"
+trap 'printf "%s\n" "$?" > "$REPORT/status"' EXIT
+python3 "$INPUTS/prepare.py" "$INPUTS/components" "$ROOT"
+for viewer in web-viewer game-viewer; do
+ harness dsh check "$INPUTS/components/viewers/$viewer"
+ harness dsh install "$INPUTS/components/viewers/$viewer" --link
+done
+for package in hello logs game; do
+ harness dsh check "$ROOT/packages/$package"
+ harness dsh install "$ROOT/packages/$package" --link
+ harness dsh doctor "os-lab/$package"
+done
+PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install --prefix "$ROOT/qa" --no-audit --no-fund playwright
+cp "$INPUTS/exercise.mjs" "$ROOT/qa/exercise.mjs"
+node "$ROOT/qa/exercise.mjs" "$ROOT" "$REPORT"
diff --git a/os/tests/test_first_use.py b/os/tests/test_first_use.py
new file mode 100644
index 000000000..c94298895
--- /dev/null
+++ b/os/tests/test_first_use.py
@@ -0,0 +1,55 @@
+import importlib.machinery
+import importlib.util
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+loader = importlib.machinery.SourceFileLoader('hn_os', str(Path(__file__).resolve().parents[1] / 'tools/hn-os'))
+spec = importlib.util.spec_from_loader(loader.name, loader)
+hn_os = importlib.util.module_from_spec(spec)
+loader.exec_module(hn_os)
+
+
+class FirstUse(unittest.TestCase):
+ def test_connected_machine_starts_bundled_agent_without_model_or_config_override(self):
+ with tempfile.TemporaryDirectory() as temp, patch.object(hn_os.Path, 'home', return_value=Path(temp)), \
+ patch.object(hn_os, 'connected', return_value=True), patch.object(hn_os, 'wifi') as wifi, \
+ patch.object(hn_os.os, 'chdir') as cwd, patch.object(hn_os.os, 'execv') as execute:
+ hn_os.try_harness()
+ wifi.assert_not_called()
+ cwd.assert_called_once_with(Path(temp) / 'Projects')
+ execute.assert_called_once_with('/usr/bin/opencode', ['opencode'])
+
+ def test_disconnected_or_cancelled_network_setup_never_launches_agent(self):
+ for outcome in [0, 1]:
+ with self.subTest(outcome=outcome), patch.object(hn_os, 'connected', return_value=False), \
+ patch.object(hn_os, 'wifi', return_value=outcome) as wifi, \
+ patch.object(hn_os.sys.stdin, 'isatty', return_value=False), \
+ patch.object(hn_os.os, 'execv') as execute:
+ hn_os.try_harness()
+ wifi.assert_called_once()
+ execute.assert_not_called()
+
+ def test_network_setup_flows_into_agent_when_connection_succeeds(self):
+ with tempfile.TemporaryDirectory() as temp, patch.object(hn_os.Path, 'home', return_value=Path(temp)), \
+ patch.object(hn_os, 'connected', side_effect=[False, True]), \
+ patch.object(hn_os, 'wifi', return_value=0), patch.object(hn_os.os, 'chdir'), \
+ patch.object(hn_os.os, 'execv') as execute:
+ hn_os.try_harness()
+ execute.assert_called_once_with('/usr/bin/opencode', ['opencode'])
+
+ def test_install_never_requires_network_setup(self):
+ with patch.object(hn_os.sys, 'argv', ['hn-os', 'install']), \
+ patch.object(hn_os.os, 'execv', side_effect=SystemExit) as execute, \
+ patch.object(hn_os, 'connected') as connected:
+ with self.assertRaises(SystemExit):
+ hn_os.main()
+ self.assertEqual(execute.call_args.args[1], ['python3', '/usr/lib/harness-os/install.py'])
+ connected.assert_not_called()
+
+ def test_local_only_and_disconnected_states_require_network_setup(self):
+ for state, expected in [('connected', True), ('connected (local only)', False), ('disconnected', False)]:
+ with self.subTest(state=state), patch.object(hn_os.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0, state + '\n')):
+ self.assertEqual(hn_os.connected(), expected)
diff --git a/os/tests/test_installer.py b/os/tests/test_installer.py
new file mode 100644
index 000000000..6b8ac93f8
--- /dev/null
+++ b/os/tests/test_installer.py
@@ -0,0 +1,387 @@
+import importlib.util
+from contextlib import ExitStack, redirect_stdout
+import hashlib
+import io
+import json
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location('installer', Path(__file__).resolve().parents[1] / 'installer.py')
+installer = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(installer)
+
+
+class DiskSafety(unittest.TestCase):
+ def disk(self, **changes):
+ return dict({'type': 'disk', 'ro': False, 'size': 32 * 1024**3,
+ 'mountpoints': [None], 'serial': 'HN_TEST', 'children': []}, **changes)
+
+ def test_partition_device_names(self):
+ self.assertEqual(installer.partitions('/dev/nvme0n1')[-1], '/dev/nvme0n1p3')
+ self.assertEqual(installer.partitions('/dev/mmcblk0')[-1], '/dev/mmcblk0p3')
+ self.assertEqual(installer.partitions('/dev/sda')[-1], '/dev/sda3')
+
+ def test_live_usb_and_mounted_nested_mapper_are_rejected(self):
+ for mount in ['/run/archiso/bootmnt', '/', '/home']:
+ disk = self.disk(children=[{'mountpoints': [None], 'children': [{'mountpoints': [mount]}]}])
+ with self.assertRaises(ValueError):
+ installer.validate_disk(disk)
+
+ def test_unmounted_programmer_usb_is_rejected_after_copy_to_ram(self):
+ image = dict(fstype='iso9660', label='HN_OS', mountpoints=[None])
+ for changes in [image, dict(children=[image])]:
+ with self.subTest(changes=changes), self.assertRaisesRegex(ValueError, 'booted into RAM'):
+ installer.validate_disk(self.disk(**changes))
+ installer.validate_disk(self.disk(fstype='btrfs', label='HNROOT'))
+
+ def test_requires_writable_whole_disk_with_space(self):
+ for changes in [{'ro': True}, {'type': 'part'}, {'type': 'loop'}, {'size': 1024}]:
+ with self.subTest(changes=changes), self.assertRaises(ValueError):
+ installer.validate_disk(self.disk(**changes))
+
+ def test_unattended_serial_must_match(self):
+ installer.validate_disk(self.disk(), 'HN_TEST')
+ with self.assertRaises(ValueError):
+ installer.validate_disk(self.disk(), 'ANOTHER_DISK')
+ with self.assertRaises(ValueError):
+ installer.validate_disk(self.disk(serial=None), 'HN_TEST')
+
+ def test_reserved_image_account_is_rejected_before_any_disk_write(self):
+ config = dict(username='daemon', hostname='test', password='test-password', encrypt=True,
+ disk='/dev/vda', confirm_erase='/dev/vda')
+ with tempfile.TemporaryDirectory() as temp:
+ source = Path(temp) / 'payload.sfs'
+ source.touch()
+ with patch.object(installer, 'selected_disk', return_value=self.disk()), \
+ patch.object(installer.shutil, 'which', return_value='/usr/bin/tool'), \
+ patch.object(installer, 'run', return_value='root:x:0:0::/root:/bin/bash\ndaemon:x:2:2::/:/usr/bin/nologin\n') as commands:
+ with self.assertRaisesRegex(ValueError, 'reserves the username'):
+ installer.install(config, source, Path(temp) / 'target')
+ self.assertEqual([call.args[0] for call in commands.call_args_list], ['unsquashfs'])
+ self.assertFalse((Path(temp) / 'target').exists())
+
+ def test_corrupt_offline_kernel_is_rejected_before_any_disk_write(self):
+ config = dict(username='programmer', hostname='test', password='test-password', encrypt=True,
+ disk='/dev/vda', confirm_erase='/dev/vda')
+ kernel = {'path': 'usr/lib/modules/6.12.1-lts/vmlinuz', 'sha256': hashlib.sha256(b'valid-kernel').hexdigest()}
+ with tempfile.TemporaryDirectory() as temp:
+ source = Path(temp) / 'payload.sfs'
+ source.touch()
+ with patch.object(installer, 'selected_disk', return_value=self.disk()), \
+ patch.object(installer.shutil, 'which', return_value='/usr/bin/tool'), \
+ patch.object(installer, 'run', side_effect=['root:x:0:0::/root:/bin/bash\n', json.dumps({'architecture': 'x86_64', 'version': 'preview'}), json.dumps(kernel)]) as commands, \
+ patch.object(installer.subprocess, 'check_output', return_value=b'corrupt-kernel'):
+ with self.assertRaisesRegex(ValueError, 'kernel failed verification'):
+ installer.install(config, source, Path(temp) / 'target')
+ self.assertTrue(all(call.args[0] == 'unsquashfs' for call in commands.call_args_list))
+ self.assertFalse((Path(temp) / 'target').exists())
+
+ def test_config_cannot_inject_commands_or_password_lines(self):
+ good = dict(username='programmer', hostname='thinkpad', password='test-password', encrypt=True, disk='/dev/sda')
+ installer.validate_config(good)
+ for change in [dict(username='root'), dict(username='x;reboot'), dict(hostname='bad name'),
+ dict(password='password\nroot:injected'), dict(disk='/dev/sda;reboot'), dict(encrypt='yes'),
+ dict(username=None), dict(password=123456789), dict(hostname='bad-')]:
+ with self.subTest(change=change), self.assertRaises(ValueError):
+ installer.validate_config(dict(good, **change))
+
+
+class LivePayload(unittest.TestCase):
+ def test_usb_ram_copy_and_mounted_media_are_both_supported(self):
+ with tempfile.TemporaryDirectory() as temp:
+ ram, media = Path(temp) / 'copytoram.sfs', Path(temp) / 'bootmnt.sfs'
+ with patch.object(installer, 'LIVE_PAYLOADS', (ram, media)):
+ with self.assertRaisesRegex(ValueError, 'Live system payload is missing'):
+ installer.live_payload()
+ media.touch()
+ self.assertEqual(installer.live_payload(), media)
+ ram.touch()
+ self.assertEqual(installer.live_payload(), ram)
+ media.unlink()
+ self.assertEqual(installer.live_payload(), ram)
+
+ def test_explicit_source_is_honored_and_never_silently_replaced(self):
+ with tempfile.TemporaryDirectory() as temp:
+ available, explicit = Path(temp) / 'available.sfs', Path(temp) / 'explicit.sfs'
+ available.touch()
+ with patch.object(installer, 'LIVE_PAYLOADS', (available,)):
+ with self.assertRaisesRegex(ValueError, 'explicit.sfs'):
+ installer.live_payload(explicit)
+ explicit.touch()
+ self.assertEqual(installer.live_payload(explicit), explicit)
+
+
+class Screen:
+ """Capture drawn text and supply keys; never expose a real disk or terminal."""
+ def __init__(self):
+ self.keys, self.frames, self.drawn = [], [], []
+ self.size = (24, 80)
+
+ def getmaxyx(self):
+ return self.size
+
+ def erase(self):
+ self.drawn = []
+
+ clear = erase
+
+ def addnstr(self, row, column, text, length, attr):
+ self.drawn.append(text[:length])
+
+ def addstr(self, row, column, text, attr):
+ self.drawn.append(text)
+
+ def refresh(self):
+ self.frames.append('\n'.join(self.drawn))
+
+ def keypad(self, enabled):
+ pass
+
+ def move(self, row, column):
+ assert 0 <= row < self.size[0] and 0 <= column < self.size[1]
+
+ def get_wch(self):
+ if not self.keys:
+ raise AssertionError('The form requested another key after the test finished.')
+ return self.keys.pop(0)
+
+
+class InstallationCompletion(unittest.TestCase):
+ def test_success_stays_visible_until_shutdown_or_return_is_chosen(self):
+ for keys, shutdown in [(['\n'], True), (['\t', '\n'], False), (['\x1b'], False)]:
+ screen = Screen()
+ screen.keys = keys
+ with self.subTest(keys=keys), patch.object(installer.curses, 'curs_set'), patch.object(installer.curses, 'flushinp') as flush:
+ self.assertEqual(installer.completion(screen), shutdown)
+ flush.assert_called_once()
+ self.assertIn('Harness is installed.', screen.frames[0])
+ self.assertIn('Remove the USB after shutdown.', screen.frames[0])
+
+
+class InteractiveInstall(unittest.TestCase):
+ def setUp(self):
+ context = ExitStack()
+ self.addCleanup(context.close)
+ self.output = io.StringIO()
+ context.enter_context(redirect_stdout(self.output))
+ self.argv = ['install.py']
+ context.enter_context(patch.object(installer.sys, 'argv', self.argv))
+ context.enter_context(patch.object(installer.os, 'geteuid', return_value=0))
+ self.disk = dict(name='/dev/vda', type='disk', ro=False, size=32 * 1024**3,
+ model='Test SSD', mountpoints=[None], serial='HN_TEST', children=[])
+ self.inventory = context.enter_context(patch.object(installer, 'inventory', return_value=[self.disk]))
+ self.screen = Screen()
+ context.enter_context(patch.object(installer.curses, 'flushinp'))
+ self.completion = context.enter_context(patch.object(installer, 'completion', return_value=False))
+ self.wrapper = context.enter_context(patch.object(installer.curses, 'wrapper', side_effect=lambda fn: fn(self.screen)))
+ context.enter_context(patch.object(installer.curses, 'curs_set'))
+ context.enter_context(patch.object(installer.curses, 'set_escdelay'))
+ context.enter_context(patch.object(installer.sys.stdin, 'isatty', return_value=True))
+ context.enter_context(patch.object(self.output, 'isatty', return_value=True))
+ self.install = context.enter_context(patch.object(installer, 'install'))
+ self.payload = context.enter_context(patch.object(installer, 'live_payload', return_value=Path('/test-live.sfs')))
+ self.secret = 'test-password-123'
+
+ def fill_passwords(self):
+ # Disk -> encryption -> password -> repeat -> Install button via Enter.
+ self.screen.keys.extend(['\t', '\t', *self.secret, '\n', *self.secret, '\n'])
+
+ def confirm(self):
+ self.screen.keys.append('\n') # Activate Install; no second confirmation screen.
+
+ def test_install_button_masks_password_and_installs_selected_disk(self):
+ self.fill_passwords()
+ self.confirm()
+ installer.main()
+ config = self.install.call_args.args[0]
+ self.assertEqual((config['username'], config['hostname'], config['encrypt']), ('me', 'harness', True))
+ self.assertEqual(config['confirm_erase'], '/dev/vda')
+ self.assertEqual(config['expected_serial'], 'HN_TEST')
+ self.assertEqual(config['password'], self.secret)
+ self.assertIn('Encryption [x]', self.screen.frames[0])
+ first = self.screen.frames[0]
+ for clutter in ('me@', '/dev/', 'HN_TEST', 'Tab move', 'Space toggle', 'eight characters'):
+ self.assertNotIn(clutter, first)
+ for label in ('Disk', 'Encryption', 'Password', 'Repeat password'):
+ self.assertTrue(any(row.startswith(f'{label:18}') for row in first.splitlines()))
+ for frame in self.screen.frames:
+ self.assertNotIn(self.secret, frame)
+
+ def test_short_password_is_accepted_but_empty_password_is_not(self):
+ self.secret = 'a'
+ self.fill_passwords()
+ self.confirm()
+ installer.main()
+ self.assertEqual(self.install.call_args.args[0]['password'], 'a')
+ config = dict(self.install.call_args.args[0], password='')
+ with self.assertRaisesRegex(ValueError, 'Enter a password'):
+ installer.validate_config(config)
+
+ def test_shutdown_is_offered_only_after_a_successful_install(self):
+ self.fill_passwords()
+ self.confirm()
+ self.completion.return_value = True
+ with patch.object(installer, 'run') as command:
+ command.side_effect = lambda *args: self.install.assert_called_once()
+ installer.main()
+ command.assert_called_once_with('systemctl', 'poweroff')
+ self.screen.keys = []
+ self.fill_passwords()
+ self.confirm()
+ self.completion.reset_mock()
+ self.install.side_effect = ValueError('fixture disk failure')
+ with patch.object(installer, 'run') as command, self.assertRaisesRegex(ValueError, 'fixture disk failure'):
+ installer.main()
+ self.completion.assert_not_called()
+ command.assert_not_called()
+
+ def test_command_line_keeps_explicit_unencrypted_and_custom_account_installation(self):
+ self.argv.extend(['--no-encryption', '--username', 'sam', '--hostname', 'workbox'])
+ self.fill_passwords()
+ self.confirm()
+ installer.main()
+ config = self.install.call_args.args[0]
+ self.assertEqual((config['username'], config['hostname'], config['encrypt']), ('sam', 'workbox', False))
+ self.assertIn('Encryption [ ]', self.screen.frames[0])
+
+ def test_main_form_checkbox_can_disable_encryption(self):
+ self.screen.keys.extend(['\t', ' ', '\t', *self.secret, '\n', *self.secret, '\n'])
+ self.confirm()
+ installer.main()
+ self.assertFalse(self.install.call_args.args[0]['encrypt'])
+
+ def test_finishing_passwords_only_focuses_install_and_escape_cancels(self):
+ self.fill_passwords()
+ self.screen.keys.append('\x1b')
+ with self.assertRaises(KeyboardInterrupt):
+ installer.main()
+ self.install.assert_not_called()
+ self.assertTrue(all('Install Harness on this disk?' not in f for f in self.screen.frames))
+
+ def test_selecting_another_disk_does_not_start_installation(self):
+ self.inventory.return_value.append(dict(self.disk, name='/dev/vdb', serial='SECOND_DISK'))
+ self.screen.keys.extend(['\n', installer.curses.KEY_DOWN, '\n'])
+ self.fill_passwords()
+ self.confirm()
+ installer.main()
+ config = self.install.call_args.args[0]
+ self.assertEqual((config['disk'], config['confirm_erase'], config['expected_serial']),
+ ('/dev/vdb', '/dev/vdb', 'SECOND_DISK'))
+ picker = next(f for f in self.screen.frames if f.startswith('Select disk'))
+ disk_rows = [r for r in picker.splitlines() if '/dev/' in r]
+ self.assertEqual(len(disk_rows), 2)
+ self.assertTrue(all('Test SSD' in r and 'GB' in r for r in disk_rows))
+
+ def test_escaping_disk_picker_preserves_original_selection(self):
+ self.inventory.return_value.append(dict(self.disk, name='/dev/vdb', serial='SECOND_DISK'))
+ self.screen.keys.extend(['\n', installer.curses.KEY_DOWN, '\x1b'])
+ self.fill_passwords()
+ self.confirm()
+ installer.main()
+ self.assertEqual(self.install.call_args.args[0]['disk'], '/dev/vda')
+
+ def test_password_mismatch_can_be_corrected_without_restarting(self):
+ self.screen.keys.extend(['\t', '\t', *self.secret, '\n', *'different', '\n', '\n', installer.curses.KEY_BTAB, '\x15', *self.secret, '\n'])
+ self.confirm()
+ installer.main()
+ self.assertTrue(any('Passwords do not match.' in frame for frame in self.screen.frames))
+ self.assertEqual(self.install.call_args.args[0]['password'], self.secret)
+
+ def test_live_usb_is_excluded_from_picker(self):
+ self.inventory.return_value.insert(0, dict(self.disk, name='/dev/sda', mountpoints=['/run/archiso/bootmnt']))
+ self.screen.keys.extend(['\n', '\n'])
+ self.fill_passwords()
+ self.confirm()
+ installer.main()
+ self.assertEqual(self.install.call_args.args[0]['disk'], '/dev/vda')
+ self.assertFalse(any('/dev/sda' in frame for frame in self.screen.frames))
+
+ def test_ram_boot_usb_is_excluded_from_picker(self):
+ self.inventory.return_value.insert(0, dict(self.disk, name='/dev/sda',
+ fstype='iso9660', label='HN_OS'))
+ self.fill_passwords()
+ self.confirm()
+ installer.main()
+ self.assertEqual(self.install.call_args.args[0]['disk'], '/dev/vda')
+
+ def test_missing_live_payload_stops_before_password_entry(self):
+ self.payload.side_effect = ValueError('Live system payload is missing')
+ with self.assertRaisesRegex(ValueError, 'Live system payload is missing'):
+ installer.main()
+ self.install.assert_not_called()
+ self.wrapper.assert_not_called()
+
+ def test_disk_replacement_is_rejected_when_install_is_pressed(self):
+ self.inventory.side_effect = [[self.disk], [dict(self.disk, serial='REPLACED')]]
+ self.fill_passwords()
+ self.confirm()
+ self.screen.keys.append('\x1b')
+ with self.assertRaises(KeyboardInterrupt):
+ installer.main()
+ self.install.assert_not_called()
+ self.assertTrue(any('Disk serial does not match' in frame for frame in self.screen.frames))
+
+ def test_small_terminal_can_cancel_without_starting_installation(self):
+ self.screen.size = (12, 40)
+ self.screen.keys.append('\x1b')
+ with self.assertRaises(KeyboardInterrupt):
+ installer.main()
+ self.install.assert_not_called()
+
+ def test_no_eligible_disk_stops_before_password_entry(self):
+ self.inventory.return_value = [dict(self.disk, ro=True)]
+ with self.assertRaisesRegex(ValueError, 'No unmounted'):
+ installer.main()
+ self.install.assert_not_called()
+ self.wrapper.assert_not_called()
+
+ def test_configuration_file_cannot_silently_conflict_with_command_line_overrides(self):
+ self.argv.extend(['--config', '/unused.json', '--no-encryption', '--yes-erase-disk'])
+ with self.assertRaisesRegex(ValueError, 'set account names and encryption in that file'):
+ installer.main()
+ self.install.assert_not_called()
+ self.wrapper.assert_not_called()
+
+
+class InstallerExit(unittest.TestCase):
+ def exercise(self, failure, config=None, tty=True):
+ with patch.object(installer, 'arguments', return_value=installer.argparse.Namespace(config=config)), \
+ patch.object(installer, 'main', side_effect=failure), \
+ patch.object(installer.sys.stdin, 'isatty', return_value=tty), \
+ patch.object(installer.sys, 'stderr') as stderr, \
+ patch('builtins.input') as acknowledge:
+ stderr.isatty.return_value = tty
+ status = installer.entrypoint()
+ return status, acknowledge, ''.join(str(call.args[0]) for call in stderr.write.call_args_list)
+
+ def test_interactive_failure_waits_for_acknowledgement_before_pane_closes(self):
+ status, acknowledge, error = self.exercise(ValueError('Target disk was not found.'))
+ self.assertEqual(status, 1)
+ self.assertIn('Installation stopped: Target disk was not found.', error)
+ acknowledge.assert_called_once_with('Press Enter to return to Harness.')
+
+ def test_unattended_and_piped_failures_never_wait(self):
+ for config, tty in [(Path('/tmp/install.json'), True), (None, False)]:
+ with self.subTest(config=config, tty=tty):
+ status, acknowledge, error = self.exercise(OSError('fixture read failure'), config, tty)
+ self.assertEqual(status, 1)
+ self.assertIn('fixture read failure', error)
+ acknowledge.assert_not_called()
+
+ def test_deliberate_cancel_does_not_open_an_error_prompt(self):
+ status, acknowledge, error = self.exercise(KeyboardInterrupt())
+ self.assertEqual(status, 130)
+ self.assertEqual(error, '')
+ acknowledge.assert_not_called()
+
+ def test_success_keeps_zero_status_without_an_extra_prompt(self):
+ status, acknowledge, error = self.exercise(None)
+ self.assertEqual(status, 0)
+ self.assertEqual(error, '')
+ acknowledge.assert_not_called()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_package.py b/os/tests/test_package.py
new file mode 100644
index 000000000..fa1446415
--- /dev/null
+++ b/os/tests/test_package.py
@@ -0,0 +1,61 @@
+import importlib.util
+import json
+from pathlib import Path
+import tarfile
+import tempfile
+import unittest
+
+
+spec = importlib.util.spec_from_file_location('os_package', Path(__file__).parents[1] / 'tools/build-package.py')
+package = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(package)
+
+
+class PackageIdentity(unittest.TestCase):
+ def test_macos_wrong_architecture_dirty_or_different_source_cannot_be_packaged(self):
+ with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ good = {'source_commit': 'a' * 40, 'dirty': False, 'target': 'x86_64-unknown-linux-musl'}
+ header = bytearray(20)
+ header[:6] = b'\x7fELF\x02\x01'
+ header[18:20] = (62).to_bytes(2, 'little')
+ (root / 'harness-tui').write_bytes(header)
+ for name in ['cli.js', 'notify.mjs']:
+ (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'}]:
+ (root / 'source.json').write_text(json.dumps(dict(good, **changes)))
+ with self.subTest(changes=changes), self.assertRaises(ValueError):
+ package.validate_runtime(root, 'a' * 40)
+ (root / 'source.json').write_text(json.dumps(good))
+ for bad_header in [b'\xcf\xfa\xed\xfe', header[:18] + (183).to_bytes(2, 'little')]:
+ (root / 'harness-tui').write_bytes(bad_header)
+ with self.assertRaises(ValueError):
+ package.validate_runtime(root, 'a' * 40)
+
+ def test_archive_preserves_executable_and_symlink_with_root_ownership(self):
+ with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp) / 'stage'
+ binary = root / 'usr/lib/harness/harness-tui'
+ binary.parent.mkdir(parents=True)
+ binary.write_bytes(b'executable fixture')
+ binary.chmod(0o755)
+ (binary.parent / 'hn').symlink_to('harness-tui')
+ output = Path(temp) / 'harness-os.pkg.tar.gz'
+ package.archive_package(root, output, 'pkgname = harness-os\npkgver = 1-1\n', 123456)
+ with tarfile.open(output) as archive:
+ executable = archive.getmember('usr/lib/harness/harness-tui')
+ self.assertEqual(executable.mode, 0o755)
+ self.assertEqual(archive.extractfile(executable).read(), b'executable fixture')
+ link = archive.getmember('usr/lib/harness/hn')
+ self.assertTrue(link.issym())
+ self.assertEqual(link.linkname, 'harness-tui')
+ for member in archive.getmembers():
+ self.assertEqual((member.uid, member.gid, member.mtime), (0, 0, 123456))
+ self.assertIn(b'pkgname = harness-os', archive.extractfile('.PKGINFO').read())
+ self.assertFalse(output.with_name(output.name + '.partial').exists())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_publication.py b/os/tests/test_publication.py
new file mode 100644
index 000000000..803e30d0e
--- /dev/null
+++ b/os/tests/test_publication.py
@@ -0,0 +1,94 @@
+import copy
+import importlib.util
+import json
+from pathlib import Path
+import tempfile
+import unittest
+
+spec = importlib.util.spec_from_file_location('hn_publish', Path(__file__).parents[1] / 'tools/publish.py')
+publish = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(publish)
+
+
+class PublicationGuards(unittest.TestCase):
+ def test_installation_guide_cannot_name_an_older_release_or_image(self):
+ manifest = {'version': '0.1.0-preview.4', 'iso': {'name': 'harness-0.1.0-preview.4-x86_64.iso'}}
+ guide = 'These instructions are for **0.1.0-preview.4**. Download harness-0.1.0-preview.4-x86_64.iso.'
+ publish.validate_install_guide(manifest, guide)
+ for old in [guide.replace('**0.1.0-preview.4**', '**0.1.0-preview.3**'),
+ guide.replace('harness-0.1.0-preview.4-x86_64.iso', 'programmer-os-0.1.0-preview.3-x86_64.iso')]:
+ with self.subTest(guide=old), self.assertRaises(ValueError):
+ publish.validate_install_guide(manifest, old)
+
+ def test_failed_or_incomplete_project_work_cannot_be_published_as_passed(self):
+ with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ report = root / 'bios/workloads/reports'
+ report.mkdir(parents=True)
+ for name in ['terminal-tool', 'website', 'game', 'fullstack']:
+ for stage in ['agent', 'checks']:
+ (report / f'{name}-{stage}.status').write_text('0\n')
+ rows = [{'name': name, 'status': 'passed'} for name in [
+ 'website keyboard filtering and help', 'game movement pause restart and state restoration',
+ 'fullstack browser CRUD validation and persistence']]
+ browser = report / 'browser-receipt.json'
+ browser.write_text(json.dumps({'results': rows}))
+ publish.validate_examples(root, 'workloads')
+ (report / 'game-agent.status').write_text('124\n')
+ with self.assertRaises(ValueError):
+ publish.validate_examples(root, 'workloads')
+ (report / 'game-agent.status').write_text('0\n')
+ browser.write_text(json.dumps({'results': [rows[0]] * 3}))
+ with self.assertRaises(ValueError):
+ publish.validate_examples(root, 'workloads')
+ browser.write_text(json.dumps({'results': rows[:2]}))
+ with self.assertRaises(ValueError):
+ publish.validate_examples(root, 'workloads')
+
+ def test_all_three_dsh_results_are_required(self):
+ with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ report = root / 'bios/dsh/reports'
+ report.mkdir(parents=True)
+ rows = [{'name': name, 'status': 'passed'} for name in ['hello', 'logs', 'game']]
+ results = report / 'results.json'
+ results.write_text(json.dumps(rows))
+ publish.validate_examples(root, 'dsh')
+ rows[-1]['status'] = 'failed'
+ results.write_text(json.dumps(rows))
+ with self.assertRaises(ValueError):
+ publish.validate_examples(root, 'dsh')
+ results.write_text(json.dumps(rows[:2]))
+ with self.assertRaises(ValueError):
+ publish.validate_examples(root, 'dsh')
+
+ def test_only_complete_matching_machine_evidence_can_publish(self):
+ manifest = {'source_commit': 'source-one', 'iso': {'sha256': 'image-one'}}
+ receipts = [dict(firmware=fw, encrypted=encrypted, status='passed', iso_sha256='image-one',
+ image_source_commit='source-one', checks=publish.REQUIRED_CHECKS +
+ ['Harness unlock screen renders, masks input, accepts a retry after a wrong password',
+ 'Claude Code, Codex and pi install on demand; bundled OpenCode and all four agents report versions',
+ 'On-demand gcc/make installation and local preview passed'])
+ for fw, encrypted in [('bios', False), ('uefi', True)]]
+ publish.validate_receipts(manifest, receipts)
+ for change in [dict(status='failed'), dict(scope='live session only'), dict(iso_sha256='another-image'),
+ dict(image_source_commit='another-source'), dict(checks=['Live hn ready;']), dict(encrypted=False)]:
+ bad = copy.deepcopy(receipts)
+ bad[1].update(change)
+ with self.subTest(change=change), self.assertRaises(ValueError):
+ publish.validate_receipts(manifest, bad)
+ with self.assertRaises(ValueError):
+ publish.validate_receipts(manifest, receipts[:1])
+ incomplete = copy.deepcopy(receipts)
+ incomplete[0]['checks'] = [row for row in incomplete[0]['checks'] if not row.startswith('On-demand')]
+ with self.assertRaises(ValueError):
+ publish.validate_receipts(manifest, incomplete)
+ for prefix, index in [('USB Enter', 0), ('USB first agent', 0), ('Bundled OpenCode', 0), ('Harness unlock', 1), ('Claude Code', 0)]:
+ incomplete = copy.deepcopy(receipts)
+ incomplete[index]['checks'] = [row for row in incomplete[index]['checks'] if not row.startswith(prefix)]
+ with self.subTest(missing=prefix), self.assertRaises(ValueError):
+ publish.validate_receipts(manifest, incomplete)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_runtime_update.py b/os/tests/test_runtime_update.py
new file mode 100644
index 000000000..09b14d259
--- /dev/null
+++ b/os/tests/test_runtime_update.py
@@ -0,0 +1,132 @@
+import copy
+import hashlib
+import importlib.util
+import io
+import json
+from pathlib import Path
+import tarfile
+import tempfile
+import unittest
+from unittest.mock import patch
+
+
+spec = importlib.util.spec_from_file_location('runtime_update', Path(__file__).parents[1] / 'runtime_update.py')
+update = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(update)
+
+
+class BundleGuards(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.version = '0.1.0pre4.r123.gabcdef1234-1'
+ self.base = {'version': '0.1.0-preview.4', 'arch_snapshot': '2026/10/01'}
+ self.runtime = {'dirty': False, 'source_commit': 'a' * 40, 'target': 'x86_64-unknown-linux-musl',
+ 'files': {name: {'bytes': 7, 'sha256': hashlib.sha256(b'fixture').hexdigest()}
+ for name in ['harness-tui', 'cli.mjs', 'notify.mjs']}}
+ self.package = self.root / f'harness-os-{self.version}-x86_64.pkg.tar.gz'
+ self.manifest = dict(schema=1, kind='harness-os-package', architecture='x86_64',
+ requires_os_version=self.base['version'], arch_snapshot=self.base['arch_snapshot'],
+ source_commit='a' * 40, runtime=self.runtime,
+ package={'name': self.package.name, 'version': self.version})
+ self.make_package()
+
+ def make_package(self, extra=None, pkgname='harness-os', bad_runtime=False):
+ with tarfile.open(self.package, 'w:gz') as archive:
+ files = {'.PKGINFO': f'pkgname = {pkgname}\npkgver = {self.version}\narch = x86_64\n'.encode(),
+ 'usr/share/harness-os/runtime.json': json.dumps(self.runtime).encode()}
+ files.update({'usr/lib/harness/' + name: b'changed' if bad_runtime else b'fixture' for name in self.runtime['files']})
+ for name, data in files.items():
+ member = tarfile.TarInfo(name)
+ member.size = len(data)
+ archive.addfile(member, io.BytesIO(data))
+ if extra:
+ archive.addfile(extra)
+ self.manifest['package'].update(bytes=self.package.stat().st_size, sha256=update.digest(self.package))
+ self.write_manifest()
+
+ def write_manifest(self):
+ (self.root / 'package-manifest.json').write_text(json.dumps(self.manifest))
+
+ def test_complete_bundle_is_verified_without_installing(self):
+ with patch.object(update.subprocess, 'run', side_effect=AssertionError('No install during validation')):
+ manifest, package = update.validate_bundle(self.root, self.base)
+ self.assertEqual(manifest, self.manifest)
+ self.assertEqual(package, self.package)
+
+ def test_incomplete_download_is_rejected_before_a_checkpoint_or_transaction(self):
+ self.package.write_bytes(self.package.read_bytes()[:-10])
+ with self.assertRaisesRegex(ValueError, 'checksum or size'):
+ update.validate_bundle(self.root, self.base)
+
+ def test_wrong_source_architecture_and_base_are_rejected(self):
+ good = copy.deepcopy(self.manifest)
+ for key, value in [('architecture', 'aarch64'), ('source_commit', 'b' * 40),
+ ('requires_os_version', '0.1.0-preview.2'), ('arch_snapshot', '2026/09/01')]:
+ self.manifest = dict(good, **{key: value})
+ self.write_manifest()
+ with self.subTest(key=key), self.assertRaises(ValueError):
+ update.validate_bundle(self.root, self.base)
+
+ def test_package_identity_and_actual_runtime_must_match_manifest(self):
+ for args in [{'pkgname': 'another-package'}, {'bad_runtime': True}]:
+ self.make_package(**args)
+ with self.subTest(args=args), self.assertRaises(ValueError):
+ update.validate_bundle(self.root, self.base)
+
+ def test_archive_cannot_escape_system_paths_or_execute_install_script(self):
+ for name in ['../escape', '/etc/escape', 'home/me/project', '.INSTALL', 'usr/../escape', 'usr/lib/harness/cli.mjs']:
+ member = tarfile.TarInfo(name)
+ self.make_package(extra=member)
+ with self.subTest(name=name), self.assertRaises(ValueError):
+ update.validate_bundle(self.root, self.base)
+ for name, target in [('usr/bad', '/home/me'), ('usr/bad', '../../home/me'), ('usr/lib/harness', 'somewhere')]:
+ member = tarfile.TarInfo(name)
+ member.type, member.linkname = tarfile.SYMTYPE, target
+ self.make_package(extra=member)
+ with self.subTest(link=(name, target)), self.assertRaises(ValueError):
+ update.validate_bundle(self.root, self.base)
+
+ def test_backup_only_includes_package_owned_paths_and_preserves_symlink(self):
+ snapshot = self.root / 'snapshot'
+ db = snapshot / 'var/lib/pacman/local/harness-os-1-1'
+ db.mkdir(parents=True)
+ (db / 'desc').write_text('%NAME%\nharness-os\n\n%VERSION%\n1-1\n\n%ARCH%\nx86_64\n\n%DEPENDS%\nnodejs-lts-jod\n')
+ (db / 'files').write_text('%FILES%\nusr/\nusr/lib/\nusr/lib/harness/\nusr/lib/harness/harness-tui\nusr/lib/harness/hn\n')
+ library = snapshot / 'usr/lib/harness'
+ library.mkdir(parents=True)
+ (library / 'harness-tui').write_bytes(b'previous executable')
+ (library / 'harness-tui').chmod(0o755)
+ (library / 'hn').symlink_to('harness-tui')
+ (library / 'unowned-user-file').write_text('do not package')
+ backup = self.root / 'backup.pkg.tar.gz'
+ # Fixture files belong to the test runner, unlike the real root snapshot.
+ original = tarfile.TarFile.add
+ def root_owned(archive, name, *args, **kwargs):
+ def ownership(info):
+ info.uid = info.gid = 0
+ return info
+ return original(archive, name, *args, filter=ownership, **kwargs)
+ with patch.object(tarfile.TarFile, 'add', root_owned):
+ update.package_backup(snapshot, '1-1', backup)
+ with tarfile.open(backup) as archive:
+ self.assertNotIn('usr/lib/harness/unowned-user-file', archive.getnames())
+ self.assertEqual(archive.getmember('usr/lib/harness/hn').linkname, 'harness-tui')
+ self.assertEqual(archive.getmember('usr/lib/harness/harness-tui').mode, 0o755)
+ self.assertIn(b'depend = nodejs-lts-jod', archive.extractfile('.PKGINFO').read())
+
+ def test_rollback_rejects_corrupt_backup_without_touching_package_database(self):
+ receipt = {'id': '20261003T120000Z-12345678', 'status': 'applied', 'root_uuid': 'test-root',
+ 'backup_sha256': '0' * 64}
+ folder = self.root / receipt['id']
+ folder.mkdir()
+ (folder / 'previous.pkg.tar.gz').write_bytes(b'bad backup')
+ with patch.object(update, 'STATE', self.root), patch.object(update, 'latest', return_value=receipt), \
+ patch.object(update, 'install_package', side_effect=AssertionError('No transaction')):
+ with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
+ update.rollback(None, {'root_uuid': 'test-root'})
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_system.py b/os/tests/test_system.py
new file mode 100644
index 000000000..462a7b24a
--- /dev/null
+++ b/os/tests/test_system.py
@@ -0,0 +1,145 @@
+import importlib.util
+from contextlib import ExitStack
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location('hn_system', Path(__file__).parents[1] / 'system.py')
+system = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(system)
+
+
+class RecoveryGuards(unittest.TestCase):
+ def test_recovery_rejects_wrong_filesystem_unsafe_boot_id_and_incomplete_checkpoint(self):
+ good = {'root_uuid': 'root-identity', 'boot_uuid': 'ABCD-1234',
+ 'boot_sha256': {name: 'digest' for name in ['vmlinuz-linux-lts', 'initramfs-linux-lts.img', 'grub/grub.cfg']}}
+ system.validate_checkpoint(good, 'root-identity')
+ for bad in [dict(good, root_uuid='another-root'), dict(good, boot_uuid='../../sda1'), dict(good, boot_sha256={})]:
+ with self.assertRaises(ValueError):
+ system.validate_checkpoint(bad, 'root-identity')
+
+ def test_snapshot_is_a_complete_real_date(self):
+ self.assertEqual(system.snapshot_date('2026/10/01'), '2026/10/01')
+ for date in ['2026/2/1', '2026/02/30', '2099/01/01', '../2026/01/01']:
+ with self.assertRaises(Exception):
+ system.snapshot_date(date)
+
+ def test_checkpoint_cannot_escape_its_directory(self):
+ self.assertEqual(system.checkpoint_name('20261002T000000Z-12345678'), '20261002T000000Z-12345678')
+ for name in ['../@home', '/etc', '.', '', '-flag', 'a/b', 'a\n']:
+ with self.assertRaises(ValueError):
+ system.checkpoint_name(name)
+
+ def test_boot_verification_detects_changed_added_and_removed_files(self):
+ with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ kernel = root / 'vmlinuz-linux-lts'
+ kernel.write_bytes(b'kernel-one')
+ before = system.boot_hashes(root)
+ kernel.write_bytes(b'kernel-two')
+ self.assertNotEqual(before, system.boot_hashes(root))
+ kernel.write_bytes(b'kernel-one')
+ (root / 'initramfs-linux-lts.img').write_bytes(b'initramfs')
+ self.assertNotEqual(before, system.boot_hashes(root))
+ kernel.unlink()
+ self.assertNotEqual(before, system.boot_hashes(root))
+
+ def test_update_preserves_custom_configuration_and_advances_both_repositories(self):
+ config = ('[options]\nSigLevel = Required DatabaseOptional\nParallelDownloads = 5\n' +
+ ''.join(f'[{repo}]\nServer = https://archive.archlinux.org/repos/2026/09/01/$repo/os/$arch\n' for repo in ['core', 'extra']) +
+ '[work]\nInclude = /etc/pacman.d/work.conf\n')
+ advanced = system.advance_snapshot(config, '2026/10/01')
+ self.assertEqual(advanced, config.replace('/2026/09/01/', '/2026/10/01/'))
+ with self.assertRaises(ValueError):
+ system.advance_snapshot(config, '2026/08/01')
+ with self.assertRaises(ValueError):
+ system.advance_snapshot('[core]\nInclude = /etc/pacman.d/mirrorlist\n', '2026/10/01')
+
+
+class InterruptedUpdates(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.config = self.root / 'pacman.conf'
+ self.config.write_text('[core]\nServer = https://archive.archlinux.org/repos/2026/09/01/$repo/os/$arch\n')
+ self.receipt = self.root / 'update.json'
+ self.snapshots = self.root / 'snapshots'
+ self.context = ExitStack()
+ self.addCleanup(self.context.close)
+ for key, value in [('PACMAN_CONFIG', self.config), ('UPDATE_RECEIPT', self.receipt), ('CHECKPOINTS', self.snapshots)]:
+ self.context.enter_context(patch.object(system, key, value))
+ self.installed = self.context.enter_context(patch.object(system, 'installed', return_value={'root_uuid': 'this-system'}))
+ self.pacman = self.context.enter_context(patch.object(system.subprocess, 'run'))
+
+ def save_checkpoint(self, reason):
+ name = 'before-update-123'
+ folder = self.snapshots / name
+ (folder / 'root').mkdir(parents=True)
+ (folder / 'checkpoint.json').write_text(json.dumps({
+ 'root_uuid': 'this-system', 'boot_uuid': 'ABCD-1234',
+ 'boot_sha256': {name: 'digest' for name in ['vmlinuz-linux-lts', 'initramfs-linux-lts.img', 'grub/grub.cfg']}}))
+ return name
+
+ def test_failed_update_blocks_packages_and_retry_retains_original_checkpoint(self):
+ with patch.object(system, 'checkpoint', side_effect=self.save_checkpoint) as save:
+ def failed_pacman(argv):
+ self.assertEqual(argv, ['pacman', '-Syyu'])
+ pending = system.pending_update()
+ self.assertIsNone(pending['exit_status'])
+ self.assertEqual(pending['checkpoint'], 'before-update-123')
+ self.assertIn('/2026/10/01/', self.config.read_text())
+ return subprocess.CompletedProcess(argv, 1)
+ self.pacman.side_effect = failed_pacman
+ with self.assertRaisesRegex(ValueError, 'retry before changing packages'):
+ system.update('2026/10/01')
+ self.assertEqual(system.pending_update()['exit_status'], 1)
+ self.pacman.side_effect = None
+ self.pacman.return_value = subprocess.CompletedProcess(['pacman'], 0)
+ system.update('2026/10/01')
+ save.assert_called_once_with('before-update')
+ self.assertIsNone(system.pending_update())
+ self.assertEqual(json.loads(self.receipt.read_text())['checkpoint'], 'before-update-123')
+
+ def test_keyboard_interrupt_leaves_a_persistent_package_guard(self):
+ with patch.object(system, 'checkpoint', side_effect=self.save_checkpoint):
+ self.pacman.side_effect = KeyboardInterrupt
+ with self.assertRaises(KeyboardInterrupt):
+ system.update('2026/10/01')
+ self.assertIsNone(system.pending_update()['exit_status'])
+ self.installed.reset_mock()
+ with self.assertRaisesRegex(ValueError, 'full system update did not finish'):
+ system.checkpoint(pacman_hook=True)
+ self.installed.assert_not_called()
+
+ def test_failed_preview_receipt_also_blocks_package_transactions(self):
+ self.receipt.write_text(json.dumps({'snapshot': '2026/10/01', 'checkpoint': 'before-update-123', 'exit_status': 1}))
+ with self.assertRaisesRegex(ValueError, 'full system update did not finish'):
+ system.checkpoint(pacman_hook=True)
+ self.installed.assert_not_called()
+
+ def test_retry_refuses_a_missing_or_unrelated_recovery_checkpoint(self):
+ name = self.save_checkpoint('before-update')
+ self.receipt.write_text(json.dumps({'snapshot': '2026/10/01', 'checkpoint': name, 'exit_status': None}))
+ (self.snapshots / name / 'root').rmdir()
+ with self.assertRaisesRegex(ValueError, 'checkpoint is missing'):
+ system.update('2026/10/01')
+ (self.snapshots / name / 'root').mkdir()
+ self.installed.return_value = {'root_uuid': 'another-system'}
+ with self.assertRaisesRegex(ValueError, 'different root filesystem'):
+ system.update('2026/10/01')
+ self.pacman.assert_not_called()
+
+ def test_corrupt_update_receipt_does_not_allow_a_package_transaction(self):
+ for value in ['{broken', '[]', '{}', '{"snapshot":"2026/10/01","checkpoint":"../outside"}']:
+ self.receipt.write_text(value)
+ with self.assertRaises(ValueError):
+ system.checkpoint(pacman_hook=True)
+ self.installed.assert_not_called()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_vm_launcher.py b/os/tests/test_vm_launcher.py
new file mode 100644
index 000000000..11443220e
--- /dev/null
+++ b/os/tests/test_vm_launcher.py
@@ -0,0 +1,56 @@
+import contextlib
+import importlib.util
+import io
+from pathlib import Path
+import shlex
+import tempfile
+import unittest
+from unittest.mock import patch
+
+
+spec = importlib.util.spec_from_file_location('vm_launcher', Path(__file__).parents[1] / 'tools/run-vm.py')
+launcher = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(launcher)
+
+
+class RemoteLauncher(unittest.TestCase):
+ def test_invalid_endpoints_fail_before_any_vm_is_created(self):
+ for flags in [
+ ['--vnc-port', '5899'], ['--vnc-port', '65536'],
+ ['--ssh-port', '22'], ['--ssh-port', '65536'],
+ ['--vnc-port', '5900', '--ssh-port', '5900'],
+ ['--remote-host', 'vm.example'],
+ ['--vnc-port', '5900', '--remote-host=-oProxyCommand=bad'],
+ ['--vnc-port', '5900', '--remote-host', 'vm; echo bad'],
+ ]:
+ with self.subTest(flags=flags), contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
+ launcher.arguments(flags)
+
+ def test_services_are_loopback_only_and_the_tunnel_matches_both(self):
+ _, args = launcher.arguments(['--vnc-port', '5901', '--ssh-port', '2222', '--remote-host', '[email protected]'])
+ options = launcher.remote_options(args)
+ self.assertIn('127.0.0.1:1', options)
+ self.assertIn('user,id=net,hostfwd=tcp:127.0.0.1:2222-:22', options)
+ command = shlex.split(launcher.connection_help(args)[1])
+ self.assertEqual(command[-1], '[email protected]')
+ self.assertIn('127.0.0.1:5901:127.0.0.1:5901', command)
+ self.assertIn('127.0.0.1:2222:127.0.0.1:2222', command)
+ self.assertIn('ExitOnForwardFailure=yes', command)
+
+ def test_default_launch_has_no_remote_listeners(self):
+ _, args = launcher.arguments([])
+ self.assertEqual(launcher.remote_options(args), ['-netdev', 'user,id=net'])
+ self.assertEqual(launcher.connection_help(args), [])
+
+ def test_acceleration_required_refuses_emulation_before_touching_the_disk(self):
+ with tempfile.TemporaryDirectory() as temp:
+ directory = Path(temp) / 'new-vm'
+ with patch.object(launcher.shutil, 'which', return_value='/qemu'), \
+ patch.object(launcher, 'acceleration', return_value='tcg'), \
+ contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
+ launcher.main(['--installed', '--directory', str(directory), '--require-acceleration'])
+ self.assertFalse(directory.exists())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_vm_protocol.py b/os/tests/test_vm_protocol.py
new file mode 100644
index 000000000..2f6c865c9
--- /dev/null
+++ b/os/tests/test_vm_protocol.py
@@ -0,0 +1,39 @@
+"""Exercise command framing with a real shell, without QEMU or guest assumptions."""
+import importlib.util
+import io
+from pathlib import Path
+import socket
+import subprocess
+import unittest
+
+spec = importlib.util.spec_from_file_location('hn_vm', Path(__file__).with_name('vm.py'))
+vm_module = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(vm_module)
+
+
+class SerialProtocol(unittest.TestCase):
+ def setUp(self):
+ self.vm = vm_module.VM.__new__(vm_module.VM)
+ self.vm.serial, guest = socket.socketpair()
+ self.vm.log = io.BytesIO()
+ self.vm.process = subprocess.Popen(['bash', '--noprofile', '--norc'], stdin=guest, stdout=guest, stderr=guest)
+ guest.close()
+
+ def tearDown(self):
+ self.vm.process.terminate()
+ self.vm.process.wait(timeout=5)
+ self.vm.serial.close()
+
+ def test_explicit_exit_and_exec_preserve_serial_session(self):
+ self.assertEqual(self.vm.command('exit 7', timeout=5, check=False)[1], 7)
+ self.assertEqual(self.vm.command('exec printf still-connected', timeout=5)[0], 'still-connected')
+ self.assertEqual(self.vm.command('printf next-probe', timeout=5)[0], 'next-probe')
+
+ def test_failed_probe_reports_status_and_allows_diagnostics(self):
+ with self.assertRaisesRegex(RuntimeError, 'Guest command failed \\(3\\)'):
+ self.vm.command("printf 'probe failed'; exit 3", timeout=5)
+ self.assertEqual(self.vm.command('printf diagnostics', timeout=5)[0], 'diagnostics')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/update_guest.py b/os/tests/update_guest.py
new file mode 100644
index 000000000..011b76fa3
--- /dev/null
+++ b/os/tests/update_guest.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python3
+"""Update acceptance, only inside the disposable HN_OS_TEST guest."""
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import time
+
+
+def run(*args, check=True):
+ result = subprocess.run(args, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=180)
+ print(result.stdout, flush=True)
+ if check and result.returncode:
+ raise RuntimeError('Command failed: ' + repr(args))
+ return result
+
+
+def version():
+ return run('pacman', '-Q', 'harness-os').stdout.strip()
+
+
+def main():
+ assert sys.platform == 'linux' and os.geteuid() != 0
+ assert subprocess.check_output(['lsblk', '-dn', '-o', 'SERIAL', '/dev/vda'], text=True).strip() == 'HN_OS_TEST'
+ assert Path('/var/lib/harness-os/install.json').is_file() and not Path('/etc/harness-live').exists()
+ bundle = Path(sys.argv[1]).resolve()
+ manifest = json.loads((bundle / 'package-manifest.json').read_text())
+ updater = str(bundle / 'apply-update.py')
+ original_version = version()
+ original_runtime = Path('/usr/share/harness-os/runtime.json').read_text()
+ project = Path.home() / 'Projects/update-survivor'
+ project.mkdir()
+ (project / 'keep.txt').write_text('keep this project through apply, restart and rollback\n')
+ (project / 'heartbeat.py').write_text('''import os, pathlib, time
+root = pathlib.Path.home() / 'Projects/update-survivor'
+(root / 'pid').write_text(str(os.getpid()))
+while True:
+ with (root / 'heartbeat').open('a') as output: output.write('alive\\n')
+ time.sleep(0.2)
+''')
+ run('hn', 'new-window', '-n', 'update-survivor', 'python3 ' + str(project / 'heartbeat.py'))
+ for _ in range(100):
+ if (project / 'pid').exists():
+ break
+ time.sleep(0.1)
+ pid = int((project / 'pid').read_text())
+ process_start = Path(f'/proc/{pid}/stat').read_text().split()[21]
+ def alive():
+ assert Path(f'/proc/{pid}/stat').read_text().split()[21] == process_start
+ size = (project / 'heartbeat').stat().st_size
+ time.sleep(0.5)
+ assert (project / 'heartbeat').stat().st_size > size
+ assert (project / 'keep.txt').read_text() == 'keep this project through apply, restart and rollback\n'
+ def restart():
+ run('systemctl', '--user', 'daemon-reload')
+ run('systemctl', '--user', 'restart', 'harness-daemon')
+ run('systemctl', '--user', 'restart', 'hn-screen')
+ run('/usr/lib/harness-os/wait-runtime')
+ for _ in range(100):
+ if subprocess.run(['systemctl', '--user', 'is-active', '--quiet', 'hn-screen']).returncode == 0:
+ break
+ time.sleep(0.1)
+ run('systemctl', '--user', 'is-active', '--quiet', 'hn-screen')
+ alive()
+ receipt = {'status': 'running', 'checks': [], 'previous_package': original_version,
+ 'candidate': manifest['package'], 'source_commit': manifest['source_commit']}
+ broken = bundle.parent / 'broken-bundle'
+ shutil.copytree(bundle, broken)
+ with (broken / manifest['package']['name']).open('r+b') as handle:
+ handle.truncate(100)
+ assert run('sudo', 'python3', updater, 'apply', str(broken), check=False).returncode != 0
+ assert version() == original_version and Path('/usr/share/harness-os/runtime.json').read_text() == original_runtime
+ alive()
+ receipt['checks'].append('Truncated download rejected before runtime or package identity changed; running work survives')
+ # A real pre-transaction failure must retain its original rollback state.
+ hook = bundle.parent / '00-harness-update-fixture.hook'
+ hook.write_text('[Trigger]\nOperation = Upgrade\nType = Package\nTarget = harness-os\n[Action]\nDescription = Disposable update failure fixture\nWhen = PreTransaction\nExec = /usr/bin/false\nAbortOnFail\n')
+ run('sudo', 'install', '-m', '644', str(hook), '/etc/pacman.d/hooks/00-harness-update-fixture.hook')
+ assert run('sudo', 'python3', updater, 'apply', str(bundle), check=False).returncode != 0
+ run('sudo', 'rm', '/etc/pacman.d/hooks/00-harness-update-fixture.hook')
+ state = Path('/var/lib/harness-os/runtime-updates')
+ failed = run('sudo', 'cat', str(state / 'latest.json')).stdout
+ assert run('sudo', 'python3', updater, 'apply', str(bundle), check=False).returncode != 0
+ assert run('sudo', 'cat', str(state / 'latest.json')).stdout == failed
+ run('sudo', 'python3', updater, 'rollback')
+ assert version() == original_version
+ alive()
+ receipt['checks'].append('Real pacman failure records recoverable state; retry cannot replace it; rollback restores the original package')
+ started = time.monotonic()
+ run('sudo', 'python3', updater, 'apply', str(bundle))
+ receipt['apply_seconds'] = round(time.monotonic() - started, 3)
+ assert version() == 'harness-os ' + manifest['package']['version']
+ assert json.loads(Path('/usr/share/harness-os/runtime.json').read_text()) == manifest['runtime']
+ alive()
+ receipt['checks'].append('Small package installed offline and verified without restarting the existing terminal process')
+ run('sudo', 'harness', 'upgrade', str(bundle))
+ alive()
+ receipt['checks'].append('Repeated apply recognizes the installed build without another transaction')
+ restart()
+ receipt['checks'].append('The same terminal process and project survive restarting both Harness daemon and screen')
+ for name, info in manifest['runtime']['files'].items():
+ path = Path('/usr/lib/harness') / name
+ assert hashlib.sha256(path.read_bytes()).hexdigest() == info['sha256']
+ assert path.stat().st_uid == 0
+ started = time.monotonic()
+ run('sudo', 'harness', 'rollback')
+ receipt['rollback_seconds'] = round(time.monotonic() - started, 3)
+ assert version() == original_version and Path('/usr/share/harness-os/runtime.json').read_text() == original_runtime
+ restart()
+ receipt['checks'].append('Rollback restores the prior package and source identity; the same process and project survive both service restarts again')
+ # Leave the candidate installed for the host to verify a real reboot as well.
+ run('sudo', 'python3', updater, 'apply', str(bundle))
+ alive()
+ receipt['status'] = 'passed'
+ Path('/tmp/update-acceptance.json').write_text(json.dumps(receipt, indent=2) + '\n')
+ print('HN_UPDATE_ACCEPTANCE=' + json.dumps(receipt), flush=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/update_vm.py b/os/tests/update_vm.py
new file mode 100644
index 000000000..1fbad5c39
--- /dev/null
+++ b/os/tests/update_vm.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+"""Apply and roll back a small package on the previously published ISO in native KVM."""
+import argparse
+import base64
+from functools import partial
+import hashlib
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import shlex
+import shutil
+import subprocess
+import threading
+import time
+from vm import VM, check_graphical_keyboard
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--iso', type=Path, required=True)
+ parser.add_argument('--bundle', type=Path, required=True)
+ parser.add_argument('--output', type=Path, default=Path('os/test-results/runtime-update'))
+ args = parser.parse_args()
+ if not os.access('/dev/kvm', os.R_OK | os.W_OK):
+ parser.error('This acceptance run requires native x86 KVM.')
+ iso, bundle, folder = args.iso.resolve(), args.bundle.resolve(), args.output.resolve()
+ image = json.loads(iso.with_name('manifest.json').read_text())
+ with iso.open('rb') as handle:
+ assert hashlib.file_digest(handle, 'sha256').hexdigest() == image['iso']['sha256']
+ folder.mkdir(parents=True, exist_ok=False)
+ # Only the private disposable guest receives these files. No host disk devices.
+ served = folder / 'served'
+ shutil.copytree(bundle, served)
+ shutil.copyfile(Path(__file__).with_name('update_guest.py'), served / 'update_guest.py')
+ server = ThreadingHTTPServer(('127.0.0.1', 0), partial(SimpleHTTPRequestHandler, directory=str(served)))
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ vm = VM(folder, iso, 'uefi', 2048)
+ receipt = {'status': 'running', 'started_at': time.time(), 'image': image, 'checks': []}
+ config = dict(disk='/dev/vda', expected_serial='HN_OS_TEST', confirm_erase='/dev/vda',
+ username='me', hostname='harness', password='test-password-123', encrypt=True, serial_console=True)
+ try:
+ vm.start(live=True)
+ vm.wait(r'root@[^\r\n]*[#] ', timeout=180)
+ vm.shell_ready = True
+ vm.command('stty -echo')
+ encoded = base64.b64encode(json.dumps(config).encode()).decode()
+ vm.command('printf %s ' + encoded + ' | base64 -d > /tmp/install-config.json')
+ vm.command('nmcli networking off')
+ output, _ = vm.command('harness install --config /tmp/install-config.json --yes-erase-disk', timeout=360)
+ (folder / 'install.log').write_text(output)
+ vm.command('sync')
+ vm.stop()
+ vm.start(live=False)
+ vm.login_installed(config)
+ receipt['checks'].append('Published preview 4 installs offline and boots from its encrypted internal disk')
+ vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S -v')
+ vm.command('mkdir /tmp/update-bundle')
+ url = f'http://10.0.2.2:{server.server_port}'
+ for name in [p.name for p in served.iterdir() if p.is_file()]:
+ vm.command('curl --fail --silent --show-error --max-time 90 ' + shlex.quote(url + '/' + name) +
+ ' -o ' + shlex.quote('/tmp/update-bundle/' + name), timeout=100)
+ vm.command('cd /tmp/update-bundle && sha256sum -c SHA256SUMS')
+ # The actual update/rollback must not require a package repository or network.
+ vm.command('sudo nmcli networking off')
+ output, status = vm.command('python3 /tmp/update-bundle/update_guest.py /tmp/update-bundle', timeout=600, check=False)
+ (folder / 'update.log').write_text(output)
+ assert status == 0, 'Update acceptance failed; see update.log'
+ marker = 'HN_UPDATE_ACCEPTANCE='
+ result = json.loads(next(line.split(marker, 1)[1] for line in output.splitlines() if line.startswith(marker)))
+ receipt['update'] = result
+ vm.screenshot('updated-surviving-terminal')
+ vm.command('sync')
+ vm.stop()
+ vm.start(live=False)
+ vm.login_installed(config)
+ manifest = json.loads((bundle / 'package-manifest.json').read_text())
+ vm.command('test "$(pacman -Q harness-os)" = ' + shlex.quote('harness-os ' + manifest['package']['version']))
+ vm.command('test -s ~/Projects/update-survivor/keep.txt')
+ receipt['keyboard'] = check_graphical_keyboard(vm, 'updated')
+ receipt['checks'].append('Updated encrypted machine reboots to hn, accepts physical-keyboard input and retains the project')
+ receipt['status'] = 'passed'
+ except BaseException as error:
+ receipt['error'] = str(error)
+ try:
+ vm.screenshot('failure')
+ except Exception:
+ pass
+ raise
+ finally:
+ receipt['finished_at'] = time.time()
+ (folder / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')
+ vm.stop()
+ server.shutdown()
+ server.server_close()
+ # The uploaded evidence omits VM disks and repeated package copies.
+ shutil.rmtree(served)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/updates.sh b/os/tests/updates.sh
new file mode 100644
index 000000000..2dedb7558
--- /dev/null
+++ b/os/tests/updates.sh
@@ -0,0 +1,61 @@
+#!/bin/bash
+# Run only inside the disposable installed OS used by vm.py.
+set -euo pipefail
+test -s /var/lib/harness-os/install.json
+work=$(mktemp -d /tmp/hn-os-update-check.XXXXXX)
+cp /etc/pacman.conf "$work/pacman.conf.before"
+snapshot=$(python3 -c 'import json; print(json.load(open("/usr/share/harness-os/lock.json"))["arch_snapshot"])')
+mkdir -p "$work/package/usr/share/hn-os-update-probe" "$work/repo"
+for version in 1 2; do
+ printf '%s\n' "$version" > "$work/package/usr/share/hn-os-update-probe/value"
+ printf 'pkgname = hn-os-update-probe\npkgver = %s-1\npkgdesc = Disposable full-update fixture\narch = any\nsize = 2\n' "$version" > "$work/package/.PKGINFO"
+ bsdtar --zstd -cf "$work/repo/hn-os-update-probe-$version-1-any.pkg.tar.zst" -C "$work/package" .PKGINFO usr
+done
+pacman --noconfirm -U "$work/repo/hn-os-update-probe-1-1-any.pkg.tar.zst"
+repo-add "$work/repo/hn-update-test.db.tar.gz" "$work/repo/hn-os-update-probe-2-1-any.pkg.tar.zst"
+# Pacman stops at the first unavailable repository. Sync the local fixture
+# before hitting the disconnected Arch mirror, leaving a real mixed DB state.
+python3 - "$work" <<'PY'
+from pathlib import Path
+import sys
+config = Path('/etc/pacman.conf')
+text = config.read_text()
+assert '[core]\n' in text
+repo = f'[hn-update-test]\nSigLevel = Never\nServer = file://{sys.argv[1]}/repo\n\n'
+config.write_text(text.replace('[core]\n', repo + '[core]\n', 1))
+PY
+before=$(find /.snapshots -mindepth 1 -maxdepth 1 -type d | wc -l)
+# The local repository can sync v2, but the full Arch refresh fails. A later
+# ordinary install would otherwise upgrade against this partially synced state.
+if env https_proxy=http://127.0.0.1:9 http_proxy=http://127.0.0.1:9 no_proxy= NO_PROXY= hn-os update --snapshot "$snapshot"; then
+ echo 'Expected the deliberately disconnected full update to fail.' >&2
+ exit 1
+fi
+checkpoint=$(python3 -c 'import json; r=json.load(open("/var/lib/harness-os/update.json")); assert r["exit_status"] != 0; print(r["checkpoint"])')
+test "$(cat /usr/share/hn-os-update-probe/value)" = 1
+pacman -Si hn-os-update-probe | grep -E '^Version *: 2-1$'
+if pacman --noconfirm -S hn-os-update-probe > "$work/blocked-package.log" 2>&1; then
+ echo 'Package mutation was allowed after an incomplete full update.' >&2
+ exit 1
+fi
+cat "$work/blocked-package.log"
+grep -F 'full system update did not finish' "$work/blocked-package.log"
+test "$(cat /usr/share/hn-os-update-probe/value)" = 1
+test "$(find /.snapshots -mindepth 1 -maxdepth 1 -type d | wc -l)" -eq "$((before + 1))"
+# A real full upgrade must pass its own pre-transaction hook while holding the
+# system lock, reuse the original checkpoint, and clear the incomplete state.
+printf 'y\n' | hn-os update --snapshot "$snapshot"
+python3 - "$checkpoint" <<'PY'
+import json, sys
+r = json.load(open('/var/lib/harness-os/update.json'))
+assert r['exit_status'] == 0 and r['checkpoint'] == sys.argv[1], r
+PY
+test "$(cat /usr/share/hn-os-update-probe/value)" = 2
+test "$(cat "/.snapshots/$checkpoint/root/usr/share/hn-os-update-probe/value")" = 1
+test "$(find /.snapshots -mindepth 1 -maxdepth 1 -type d | wc -l)" -eq "$((before + 1))"
+pacman --noconfirm -R hn-os-update-probe
+test ! -e /usr/share/hn-os-update-probe/value
+cp "$work/pacman.conf.before" /etc/pacman.conf
+rm -f /var/lib/pacman/sync/hn-update-test.db /var/lib/pacman/sync/hn-update-test.db.sig
+rm -rf "$work"
+echo 'Failed full update blocked packages; retry upgraded successfully and retained the original checkpoint.'
diff --git a/os/tests/vm.py b/os/tests/vm.py
new file mode 100644
index 000000000..61098ef11
--- /dev/null
+++ b/os/tests/vm.py
@@ -0,0 +1,834 @@
+#!/usr/bin/env python3
+"""Boot and install the actual ISO in a disposable QEMU machine.
+
+Uses a private qcow2 disk with a known serial. Never passes a host block device
+to QEMU. Screenshots, serial logs, timings and checks survive every failure.
+"""
+from __future__ import annotations
+import argparse
+import base64
+import hashlib
+import io
+import json
+import os
+from pathlib import Path
+import re
+import select
+import shlex
+import shutil
+import socket
+import subprocess
+import tempfile
+import tarfile
+import time
+import uuid
+
+
+class VM:
+ def __init__(self, folder, iso, firmware, memory, live_transport='cdrom', cpu=None):
+ self.folder, self.iso, self.firmware, self.memory = folder, iso, firmware, memory
+ self.live_transport = live_transport
+ self.cpu = cpu
+ self.unlock_count = 0
+ self.boot_count = 0
+ self.process = None
+ self.serial = None
+ self.qmp = None
+ self.qmp_file = None
+ self.shell_ready = False
+ self.control = tempfile.TemporaryDirectory(prefix='hn-os-vm-', dir='/tmp')
+ self.control_path = Path(self.control.name)
+ self.log = (folder / 'serial.log').open('ab', buffering=0)
+ self.stderr = (folder / 'qemu.log').open('ab', buffering=0)
+ self.disk = folder / 'target.qcow2'
+ subprocess.run(['qemu-img', 'create', '-f', 'qcow2', str(self.disk), '24G'], check=True)
+ if live_transport == 'usb':
+ self.usb = folder / 'live-usb.qcow2'
+ subprocess.run(['qemu-img', 'create', '-f', 'qcow2', '-F', 'raw', '-b',
+ str(iso), str(self.usb)], check=True)
+ subprocess.run(['qemu-img', 'resize', str(self.usb), '16G'], check=True)
+ if firmware == 'uefi':
+ self.code = Path('/usr/share/OVMF/OVMF_CODE_4M.fd')
+ self.vars = folder / 'OVMF_VARS.fd'
+ shutil.copyfile('/usr/share/OVMF/OVMF_VARS_4M.fd', self.vars)
+
+ def start(self, live):
+ self.shell_ready = False
+ for name in ['serial.sock', 'qmp.sock']:
+ (self.control_path / name).unlink(missing_ok=True)
+ self.started = time.monotonic()
+ self.boot_count += 1
+ self.boot_event('start', live=live)
+ acceleration = 'kvm' if os.access('/dev/kvm', os.R_OK | os.W_OK) else 'tcg'
+ self.acceleration = acceleration
+ args = ['qemu-system-x86_64', '-accel', acceleration, '-m', str(self.memory), '-smp', '2',
+ '-cpu', self.cpu or ('host' if acceleration == 'kvm' else 'max'), '-device', 'virtio-vga',
+ '-display', 'none', '-no-reboot',
+ '-drive', f'file={self.disk},format=qcow2,if=none,id=target',
+ '-device', f'virtio-blk-pci,drive=target,serial=HN_OS_TEST,bootindex={2 if live else 1}',
+ '-device', 'virtio-net-pci,netdev=net', '-netdev', 'user,id=net',
+ '-serial', f'unix:{self.control_path / "serial.sock"},server=on,wait=off',
+ '-qmp', f'unix:{self.control_path / "qmp.sock"},server=on,wait=off']
+ if live:
+ # UEFI remembers the installed disk in NVRAM. Explicit device boot
+ # indices are needed to select the recovery ISO again on later boots.
+ if self.live_transport == 'usb':
+ # A private overlay exposes a full-sized writable USB while
+ # preserving the verified host ISO, including on test failure.
+ args += ['-device', 'qemu-xhci,id=usb',
+ '-drive', f'file={self.usb},format=qcow2,if=none,id=live',
+ '-device', 'usb-storage,bus=usb.0,drive=live,serial=HN_OS_LIVE,removable=on,bootindex=1']
+ else:
+ args += ['-drive', f'file={self.iso},format=raw,media=cdrom,if=none,id=live',
+ '-device', 'ide-cd,drive=live,bootindex=1']
+ if self.firmware == 'uefi':
+ args += ['-drive', f'if=pflash,format=raw,readonly=on,file={self.code}',
+ '-drive', f'if=pflash,format=raw,file={self.vars}']
+ self.process = subprocess.Popen(args, stdout=self.stderr, stderr=self.stderr)
+ self.serial = self.connect('serial.sock')
+ self.qmp = self.connect('qmp.sock')
+ self.qmp.settimeout(10)
+ self.qmp_file = self.qmp.makefile('rb')
+ json.loads(self.qmp_file.readline())
+ self.monitor('qmp_capabilities')
+
+ def connect(self, name):
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ if self.process.poll() is not None:
+ raise RuntimeError('QEMU exited before opening its control sockets: ' +
+ (self.folder / 'qemu.log').read_text()[-2000:])
+ sock = socket.socket(socket.AF_UNIX)
+ try:
+ sock.connect(str(self.control_path / name))
+ return sock
+ except (FileNotFoundError, ConnectionRefusedError):
+ sock.close()
+ time.sleep(0.1)
+ raise TimeoutError(f'QEMU did not expose {name}')
+
+ def monitor(self, name, **arguments):
+ identity = uuid.uuid4().hex
+ self.qmp.sendall((json.dumps({'execute': name, 'arguments': arguments, 'id': identity}) + '\n').encode())
+ while True:
+ result = json.loads(self.qmp_file.readline())
+ if result.get('id') == identity:
+ if 'error' in result:
+ raise RuntimeError(result['error'])
+ return result.get('return')
+
+ def wait(self, pattern, timeout=180):
+ deadline = time.monotonic() + timeout
+ output = b''
+ regex = re.compile(pattern.encode(), re.S)
+ while time.monotonic() < deadline:
+ if self.process.poll() is not None:
+ raise RuntimeError(f'QEMU exited while waiting for {pattern!r}')
+ if select.select([self.serial], [], [], min(1, max(0, deadline - time.monotonic())))[0]:
+ chunk = self.serial.recv(65536)
+ if not chunk:
+ raise RuntimeError('Guest serial console disconnected.')
+ self.log.write(chunk)
+ output += chunk
+ if regex.search(output):
+ return output.decode(errors='replace')
+ raise TimeoutError(f'Guest did not produce {pattern!r}; see serial.log')
+
+ def send(self, text):
+ self.serial.sendall(text.encode())
+
+ def boot_event(self, stage, **details):
+ event = dict(boot=self.boot_count, stage=stage,
+ seconds=round(time.monotonic() - self.started, 3), **details)
+ with (self.folder / 'boot-events.jsonl').open('a') as log:
+ log.write(json.dumps(event) + '\n')
+ return event
+
+ def boot_diagnostics(self, config, name):
+ # Keep the initrd journal as well as userspace timings. A single overall
+ # boot duration cannot distinguish waiting for a person from an OS stall.
+ output, _ = self.command('printf %s ' + shlex.quote(config['password'] + '\n') +
+ ' | sudo -S journalctl -b -o short-monotonic --no-pager', timeout=60)
+ (self.folder / (name + '-boot-journal.log')).write_text(output)
+ output, _ = self.command('systemd-analyze --no-pager; systemd-analyze --no-pager blame; '
+ 'systemd-analyze --no-pager critical-chain; systemctl --failed --no-pager')
+ (self.folder / (name + '-boot-analysis.txt')).write_text(output)
+
+ def command(self, command, timeout=90, check=True):
+ marker = 'HN_RESULT_' + uuid.uuid4().hex
+ # A probe may use `exit` or `exec`. Keep it inside a subshell so the
+ # serial login remains available to report its status and run diagnostics.
+ self.send('(' + command + f"); hn_status=$?; printf '\\n{marker}:%s\\n' \"$hn_status\"\n")
+ output = self.wait(r'\r?\n' + marker + r':\d+\r?\n', timeout)
+ match = re.search(r'\r?\n' + marker + r':(\d+)\r?\n', output)
+ status = int(match.group(1))
+ if check and status:
+ raise RuntimeError(f'Guest command failed ({status}): {command}\n{output[-2000:]}')
+ return output[:match.start()], status
+
+ def login_installed(self, config, unlock_delay=0):
+ if config['encrypt']:
+ self.unlock_count += 1
+ self.wait_unlock()
+ self.unlock_prompt_seconds = self.boot_event('unlock-prompt')['seconds']
+ if unlock_delay:
+ time.sleep(unlock_delay)
+ self.screenshot('delayed-disk-unlock')
+ # A wrong password must return to the prompt, without losing
+ # the ability to unlock after the old device-timeout deadline.
+ self.type_probe('wrong-password')
+ self.keys('ret')
+ time.sleep(8)
+ self.wait_unlock()
+ self.boot_event('unlock-retry-prompt')
+ self.screenshot('disk-unlock-retry')
+ self.type_probe(config['password'][:3])
+ self.screenshot(f'disk-unlock-{self.unlock_count}-masked')
+ self.type_probe(config['password'][3:])
+ self.keys('ret')
+ self.boot_event('password-submitted')
+ self.wait(r'login:', timeout=180)
+ self.boot_event('serial-login-prompt')
+ self.send(config['username'] + '\n')
+ self.wait(r'Password:')
+ self.send(config['password'] + '\n')
+ self.wait(r'\$ ')
+ self.shell_ready = True
+ self.command('stty -echo')
+ if not config['encrypt']:
+ for word in [config['username'], config['password']]:
+ for char in word:
+ self.keys('minus' if char == '-' else char)
+ self.keys('ret')
+ time.sleep(2)
+ self.command('for n in $(seq 1 90); do systemctl --user is-active --quiet hn-screen && pgrep -x "hn|harness-tui" >/dev/null && exit 0; sleep 1; done; exit 1', timeout=110)
+ self.command('/usr/lib/harness-os/wait-runtime', timeout=160)
+ self.boot_event('harness-ready')
+
+ def wait_unlock(self):
+ # OCR reads the actual framebuffer; a process or serial prompt alone
+ # cannot prove the intended unlock screen was shown to the user.
+ deadline = time.monotonic() + 180
+ while time.monotonic() < deadline:
+ name = f'disk-unlock-{self.unlock_count}'
+ self.screenshot(name)
+ text = subprocess.check_output(['tesseract', str(self.folder / (name + '.png')),
+ 'stdout', '--psm', '11'], text=True,
+ stderr=subprocess.DEVNULL, timeout=10)
+ if 'enter your password' in text.lower():
+ (self.folder / (name + '.txt')).write_text(text)
+ return
+ time.sleep(2)
+ raise TimeoutError('The Harness graphical unlock prompt was not rendered.')
+
+ def screenshot(self, name):
+ ppm = self.folder / (name + '.ppm')
+ self.monitor('screendump', filename=str(ppm))
+ from PIL import Image
+ Image.open(ppm).save(self.folder / (name + '.png'))
+ ppm.unlink()
+
+ def keys(self, *keys):
+ self.monitor('send-key', keys=[{'type': 'qcode', 'data': key} for key in keys], **{'hold-time': 100})
+ time.sleep(0.12) # Release each key, including repeated password characters.
+
+ def type_probe(self, text):
+ # Send display keyboard events, not hn's CLI input path. Probe commands
+ # deliberately need only these unshifted US-layout characters.
+ if not re.fullmatch(r'[a-z0-9 -]+', text):
+ raise ValueError('Keyboard probe contains unsupported characters.')
+ for char in text:
+ self.keys({' ': 'spc', '-': 'minus'}.get(char, char))
+
+ def stop(self):
+ if self.process and self.process.poll() is None:
+ try:
+ self.monitor('quit')
+ except (OSError, ValueError, RuntimeError):
+ self.process.terminate()
+ try:
+ self.process.wait(timeout=15)
+ except subprocess.TimeoutExpired:
+ self.process.kill()
+ self.process.wait()
+ for handle in [self.serial, self.qmp_file, self.qmp]:
+ if handle:
+ handle.close()
+ self.serial = self.qmp_file = self.qmp = None
+
+
+def check_graphical_keyboard(vm, name):
+ """Prove the installed graphical surface accepts input and renders output."""
+ started = time.monotonic()
+ vm.command('pgrep -x labwc >/dev/null && pgrep -x foot >/dev/null')
+ vm.keys('ctrl', 'b')
+ vm.keys('shift', 't')
+ marker = 'keyboard-' + name + '-ready'
+ vm.type_probe('echo ' + marker)
+ vm.keys('ret')
+ output, _ = vm.command(
+ 'for n in $(seq 1 60); do hn capture-pane -p 2>/dev/null | '
+ 'grep -Fx ' + shlex.quote(marker) +
+ ' >/dev/null && break; sleep 0.25; done; '
+ 'hn capture-pane -p | grep -Fx ' + shlex.quote(marker) +
+ '; hn display-message -p "HN_KEYBOARD_PANE=#{pane_id}"; hn capture-pane -p')
+ pane = re.search(r'HN_KEYBOARD_PANE=(%\d+)', output)
+ if not pane:
+ raise RuntimeError('Keyboard probe did not identify its actual hn pane.')
+ # Require the standalone response, not merely the echoed command text.
+ if not re.search(r'(?m)^' + re.escape(marker) + r'\r?$', output):
+ raise RuntimeError('Graphical keyboard input did not produce shell output.')
+ confirmed = time.monotonic()
+ (vm.folder / (name + '-keyboard.txt')).write_text(output)
+ vm.screenshot(name + '-keyboard')
+ vm.keys('ctrl', 'd')
+ vm.command('for n in $(seq 1 60); do '
+ 'if ! hn list-panes -a -F "#{pane_id}" | grep -Fx ' +
+ shlex.quote(pane.group(1)) + '; then exit 0; fi; '
+ 'sleep 0.25; done; exit 1')
+ vm.command('systemctl --user is-active --quiet hn-screen && pgrep -x "hn|harness-tui" >/dev/null')
+ time.sleep(0.25) # Let the frame following the pane-close event paint.
+ return {'confirmed_seconds_since_boot': round(confirmed - vm.started, 3),
+ 'probe_seconds_including_automated_typing': round(confirmed - started, 3)}
+
+
+def check_console_fallback(vm, user, folder):
+ """Break graphics in the live overlay, then type through hn on a real VT."""
+ # The payload and session launcher remain unchanged. An invalid wlroots
+ # backend forces the compositor to fail through its normal startup path.
+ override = '/etc/profile.d/00-hn-test-broken-graphics.sh'
+ vm.command('printf %s ' + shlex.quote('export WLR_BACKENDS=hn-test-missing\n') +
+ ' > ' + override + '; systemctl restart [email protected]')
+ try:
+ vm.command('for n in $(seq 1 60); do '
+ 'for p in $(pgrep -u 1000 -x "hn|harness-tui"); do '
+ 'if test "$(readlink /proc/$p/fd/0)" = /dev/tty1; then '
+ 'printf "HN_CONSOLE_PID=%s\\n" "$p"; exit 0; fi; done; '
+ 'sleep 1; done; exit 1', timeout=75)
+ vm.command('! pgrep -u 1000 -x labwc && ! pgrep -u 1000 -x foot')
+ vm.command(user('/usr/lib/harness-os/wait-runtime'), timeout=160)
+ vm.command('kill -0 "$(cat /tmp/hn-survivor.pid)"')
+ probe = ('printf "Console input ready\\n"; touch /tmp/hn-console-input-ready; '
+ 'read -r answer; test "$answer" = ready && '
+ 'touch /tmp/hn-console-input-passed; exec sleep 1800')
+ vm.command(user('hn new-window -n console-input ' + shlex.quote(probe)))
+ vm.command('for n in $(seq 1 15); do test -e /tmp/hn-console-input-ready && '
+ 'exit 0; sleep 1; done; exit 1', timeout=20)
+ for key in ['r', 'e', 'a', 'd', 'y', 'ret']:
+ vm.keys(key)
+ vm.command('for n in $(seq 1 15); do test -e /tmp/hn-console-input-passed && '
+ 'exit 0; sleep 1; done; exit 1', timeout=20)
+ vm.screenshot('03a-console-fallback')
+ finally:
+ output, _ = vm.command('cat /home/me/.local/state/harness-os/display.log; '
+ 'ps -u 1000 -o pid,ppid,tty,comm; cat /dev/vcs1', check=False)
+ (folder / 'console-fallback.log').write_text(output)
+ vm.command('rm -f ' + override + '; systemctl restart [email protected]')
+ vm.command(user("sh -c 'for n in $(seq 1 60); do systemctl --user is-active --quiet hn-screen && "
+ "pgrep -x labwc >/dev/null && pgrep -x foot >/dev/null && exit 0; "
+ "sleep 1; done; exit 1'"), timeout=75)
+ vm.command('kill -0 "$(cat /tmp/hn-survivor.pid)"')
+ vm.command(user('/usr/lib/harness-os/wait-runtime'), timeout=160)
+ vm.screenshot('03b-graphics-restored')
+
+
+def check_first_use(vm, user, folder):
+ """Operate the actual USB front door without a terminal command from the user."""
+ vm.command('test "$(uname -n)" = harness && test "$(id -nu 1000)" = me && test -f /etc/harness-live')
+ vm.command('nmcli networking off')
+ version, _ = vm.command(user('/usr/bin/opencode --version'))
+ (folder / 'bundled-opencode-version.txt').write_text(version)
+ vm.command('test ! -e /home/me/.config/opencode/opencode.json')
+ vm.keys('t')
+ vm.command('for n in $(seq 1 30); do pgrep -x "nmtui|nmtui-connect" >/dev/null && exit 0; sleep 1; done; exit 1', timeout=40)
+ vm.command('! pgrep -u 1000 -x opencode')
+ vm.screenshot('01a-try-needs-network')
+ vm.keys('esc')
+ vm.command('for n in $(seq 1 15); do ! pgrep -x "nmtui|nmtui-connect" >/dev/null && exit 0; sleep 1; done; exit 1', timeout=20)
+ vm.keys('ret')
+ vm.command('sleep 1; ! pgrep -u 1000 -x opencode')
+ # Enter is Install, including while the network is disabled.
+ vm.keys('ret')
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do hn capture-pane -p | grep -q "All data on this disk will be erased" && exit 0; sleep 1; done; exit 1')), timeout=40)
+ vm.screenshot('01b-direct-install-offline')
+ vm.keys('esc')
+ vm.command('sleep 1; test "$(lsblk -n -o TYPE /dev/vda | wc -l)" -eq 1')
+ # A preflight error must remain visible in a command-owned pane until read.
+ vm.command(user('hn new-window -n install-error ' + shlex.quote('sudo /usr/bin/harness install --source /run/hn-missing-image')))
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 15); do hn capture-pane -p | grep -q "Press Enter to return to Harness" && exit 0; sleep 1; done; exit 1')), timeout=20)
+ installer_process = '^/usr/bin/python3 /usr/lib/harness-os/install[.]py --source /run/hn-missing-image$'
+ vm.command('pgrep -f ' + shlex.quote(installer_process))
+ vm.screenshot('01b-install-error')
+ vm.keys('ret')
+ vm.command('for n in $(seq 1 15); do ! pgrep -f ' + shlex.quote(installer_process) + ' && exit 0; sleep 1; done; exit 1', timeout=20)
+ # New terminal is a shell immediately, without agent/project/task fields.
+ vm.keys('ctrl', 'b')
+ vm.keys('shift', 't')
+ vm.type_probe('echo terminal-ready')
+ vm.keys('ret')
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 20); do hn capture-pane -p | grep -qx terminal-ready && exit 0; sleep 1; done; exit 1')), timeout=30)
+ vm.screenshot('01c-direct-terminal')
+ # Allow a full discovery cycle, then ensure a live-overlay shell or
+ # installer has not been promoted to an agent by rounded file identities.
+ vm.command('sleep 6')
+ identity_probe = '''const fs = require('node:fs');
+for (const path of ['/usr/bin/opencode', '/usr/bin/bash', '/usr/bin/python3', '/usr/bin/nmtui', '/usr/bin/sudo']) {
+ const numeric = fs.statSync(path), exact = fs.statSync(path, {bigint: true});
+ console.log(JSON.stringify({path, numberKey: `${numeric.dev}:${numeric.ino}`, exactKey: `${exact.dev}:${exact.ino}`}));
+}
+const rows = JSON.parse(fs.readFileSync('/home/me/.harness/cli/data/registry.json', 'utf8'));
+for (const row of rows) console.log(JSON.stringify({agentId: row.agentId, engine: row.engine, active: row.active, processIdentity: row.processIdentity}));
+if (rows.some(row => row.engine !== 'terminal')) throw new Error('A plain shell or installer was misidentified as an agent');
+'''
+ output, identity_status = vm.command(user('node -e ' + shlex.quote(identity_probe)), check=False)
+ (folder / 'live-process-identities.txt').write_text(output)
+ assert identity_status == 0, 'Live USB executable discovery must distinguish shells and installers from agents'
+ output, _ = vm.command(user('hn display-message -p "HN_FIRST_TERMINAL=#{pane_id}"'))
+ pane = re.search(r'HN_FIRST_TERMINAL=(%\d+)', output)
+ assert pane, 'New terminal must identify its actual pane'
+ vm.keys('ctrl', 'd')
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 30); do '
+ 'hn list-panes -a -F "#{pane_id}" | grep -Fx ' + shlex.quote(pane.group(1)) +
+ ' >/dev/null || exit 0; sleep .25; done; exit 1')), timeout=15)
+ vm.command('nmcli networking on; for n in $(seq 1 30); do test "$(nmcli -t -f STATE general)" = connected && exit 0; sleep 1; done; exit 1', timeout=40)
+ vm.keys('t')
+ vm.command('for n in $(seq 1 90); do pgrep -u 1000 -x opencode >/dev/null && exit 0; sleep 1; done; exit 1', timeout=100)
+ time.sleep(5)
+ vm.screenshot('01d-bundled-opencode')
+ vm.command('test ! -e /home/me/.config/opencode/plugin/launcher-register.js && test -s /home/me/.config/opencode/plugins/launcher-register/tui.js')
+ screen, _ = vm.command(user('hn capture-pane -p'))
+ (folder / 'bundled-opencode-screen.txt').write_text(screen)
+ assert 'Plugin failed:' not in screen and 'plugin failed /plugins' not in screen, 'Bundled OpenCode must open without a plugin error'
+ output, _ = vm.command(user('hn display-message -p "HN_FIRST_AGENT=#{pane_id}"'))
+ agent_pane = re.search(r'HN_FIRST_AGENT=(%\d+)', output)
+ assert agent_pane, 'The visible OpenCode must identify its actual pane'
+ # Exercise what a first-time user actually does after choosing Try: type
+ # into the visible agent and receive its answer, without a CLI/API shortcut.
+ vm.type_probe('what is six times seven reply with digits only')
+ vm.keys('ret')
+ _, interactive_status = vm.command(user('sh -c ' + shlex.quote(
+ 'for n in $(seq 1 120); do hn capture-pane -p > /tmp/hn-first-tui.txt; '
+ "grep -Eq '^[^[:alnum:]]*42[^[:alnum:]]*$' /tmp/hn-first-tui.txt && exit 0; "
+ 'sleep 1; done; exit 1')), timeout=140, check=False)
+ screen, _ = vm.command('cat /tmp/hn-first-tui.txt')
+ (folder / 'first-opencode-interactive.txt').write_text(screen)
+ vm.screenshot('01e-first-agent-reply')
+ assert interactive_status == 0, 'The visible bundled agent must accept keyboard input and display its reply'
+ # No model flag/config, API key, account, or installer. Validate a real
+ # upstream-default reply; preserve all events rather than just the exit code.
+ prompt = 'What is six times seven? Reply with only the decimal number. Do not use tools.'
+ command = 'cd "$HOME/Projects" && timeout 120 /usr/bin/opencode run --format json ' + shlex.quote(prompt) + ' > /tmp/hn-first-chat.jsonl 2>/tmp/hn-first-chat.err'
+ _, status = vm.command(user('sh -c ' + shlex.quote(command)), timeout=140, check=False)
+ output, _ = vm.command('cat /tmp/hn-first-chat.jsonl')
+ errors, _ = vm.command('cat /tmp/hn-first-chat.err')
+ (folder / 'first-opencode-chat.jsonl').write_text(output)
+ (folder / 'first-opencode-chat.stderr.txt').write_text(errors)
+ events = []
+ for line in output.splitlines():
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(event, dict):
+ events.append(event)
+ reply = ''.join(e.get('part', {}).get('text', '') for e in events if e.get('type') == 'text').strip()
+ assert status == 0 and reply == '42', f'Bundled OpenCode default conversation failed: exit={status}, reply={reply!r}'
+ vm.keys('ctrl', 'c')
+ time.sleep(.3)
+ vm.keys('ctrl', 'c')
+ # OpenCode 2 keeps `opencode serve --service` alive after its TUI exits.
+ # The user's pane must close; the vendor's shared service is not a window.
+ vm.command(user('sh -c ' + shlex.quote('for n in $(seq 1 60); do '
+ 'hn list-panes -a -F "#{pane_id}" | grep -Fx ' + shlex.quote(agent_pane.group(1)) +
+ ' >/dev/null || exit 0; sleep .25; done; exit 1')), timeout=20)
+
+
+def install_interactively(vm, config, folder):
+ # The shipped form and installer run on a real guest TTY. The only test
+ # addition is serial-console boot output, needed to observe the next boot.
+ bootstrap = f'''import importlib.util
+from pathlib import Path
+spec = importlib.util.spec_from_file_location('installer', '/usr/lib/harness-os/install.py')
+installer = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(installer)
+expected = {config!r}
+installer.selected_disk(expected)
+original_install = installer.install
+def observed_install(actual, source, target):
+ assert actual == {{k: v for k, v in expected.items() if k != 'serial_console'}}, 'Interactive installation choices differ from test input'
+ actual['serial_console'] = True
+ return original_install(actual, source, target)
+installer.install = observed_install
+installer.main()
+'''
+ encoded = base64.b64encode(bootstrap.encode()).decode()
+ assert len(encoded) < 3000, 'Keep serial-console commands below the line discipline limit.'
+ vm.command(f"printf %s {shlex.quote(encoded)} | base64 -d > /run/hn-interactive-test.py; chmod 600 /run/hn-interactive-test.py")
+ vm.command('stty rows 24 cols 80')
+ marker = 'HN_INTERACTIVE_' + uuid.uuid4().hex
+ vm.send('(TERM=xterm-256color python3 /run/hn-interactive-test.py); '
+ f"hn_status=$?; printf '\\n{marker}:%s\\n' \"$hn_status\"\n")
+ transcript = []
+ def wait(pattern, timeout=30):
+ output = vm.wait(pattern, timeout)
+ transcript.append(output)
+ return output
+ try:
+ wait(r'All data on this disk will be erased')
+ vm.send('\n')
+ wait(r'Select disk')
+ vm.send('\x1b')
+ wait(r'All data on this disk will be erased')
+ vm.send('\n')
+ wait(r'Select disk')
+ vm.send('\n')
+ wait(r'All data on this disk will be erased')
+ vm.send('\t' + ('' if config['encrypt'] else ' ') + '\t')
+ vm.send(config['password'] + '\n' + config['password'] + '\n')
+ # Password entry focuses Install. Only its explicit activation starts it.
+ time.sleep(.25)
+ vm.send('\n')
+ output = wait(r'Harness is installed|\r?\n' + marker + r':\d+\r?\n', timeout=900)
+ assert 'Harness is installed' in output, 'Interactive installation failed; see installer-ui.log'
+ vm.send('\x1b') # Completion remains visible; return to the live system for the receipt.
+ output = wait(r'\r?\n' + marker + r':\d+\r?\n', timeout=900)
+ status = int(re.search(r'\r?\n' + marker + r':(\d+)\r?\n', output).group(1))
+ assert status == 0, 'Interactive installation failed; see installer-ui.log'
+ finally:
+ (folder / 'installer-ui.log').write_text(''.join(transcript))
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--iso', required=True, type=Path)
+ parser.add_argument('--firmware', choices=['bios', 'uefi'], default='bios')
+ parser.add_argument('--encrypt', action='store_true')
+ parser.add_argument('--memory', type=int, default=2048)
+ parser.add_argument('--live-transport', choices=['cdrom', 'usb'], default='cdrom')
+ parser.add_argument('--cpu', help='Optional QEMU CPU model, for an older instruction-set baseline')
+ parser.add_argument('--output', type=Path)
+ parser.add_argument('--agents', action='store_true', help='Install and start real agent executables after recovery; no accounts/API calls')
+ parser.add_argument('--workloads', action='store_true', help='Opt in to real free-model project builds and browser acceptance after --agents')
+ parser.add_argument('--dsh', action='store_true', help='Exercise three real DSH agents and shared viewers after --agents')
+ parser.add_argument('--workload-seed', type=Path, help='Previous workload artifact: preserve its generated projects and rerun acceptance')
+ parser.add_argument('--live-only', action='store_true', help='Development probe: stop after the live-session checks, without installing')
+ args = parser.parse_args()
+ if args.workloads and not args.agents:
+ parser.error('--workloads requires --agents')
+ if args.dsh and not args.agents:
+ parser.error('--dsh requires --agents')
+ if args.workloads and args.dsh:
+ parser.error('Run the two long model suites separately.')
+ if args.workload_seed and not args.workloads:
+ parser.error('--workload-seed requires --workloads')
+ folder = (args.output or Path(__file__).resolve().parents[1] / 'test-results' / (args.firmware + ('-encrypted' if args.encrypt else '-plain'))).resolve()
+ folder.mkdir(parents=True, exist_ok=False)
+ result = {'firmware': args.firmware, 'encrypted': args.encrypt, 'memory_mib': args.memory,
+ 'live_transport': args.live_transport, 'cpu': args.cpu or 'native/default',
+ 'scope': 'live session only' if args.live_only else 'live session, offline installation and recovery',
+ 'started_at_unix': time.time(), 'checks': [], 'status': 'running'}
+ manifest = json.loads((args.iso.parent / 'manifest.json').read_text())
+ with args.iso.open('rb') as handle:
+ digest = hashlib.file_digest(handle, 'sha256').hexdigest()
+ if digest != manifest['iso']['sha256']:
+ raise RuntimeError('ISO does not match its build manifest.')
+ result['iso_sha256'] = digest
+ result['image_source_commit'] = manifest['source_commit']
+ result['test_source_commit'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
+ result['test_script_sha256'] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
+ vm = VM(folder, args.iso.resolve(), args.firmware, args.memory, args.live_transport, args.cpu)
+ user = lambda cmd: 'runuser -u "$(id -nu 1000)" -- env XDG_RUNTIME_DIR=/run/user/1000 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus ' + cmd
+ try:
+ vm.start(live=True)
+ vm.wait(r'root@[^\r\n]*[#] ')
+ vm.shell_ready = True
+ vm.command('stty -echo')
+ if args.live_transport == 'usb' and args.memory >= 4096:
+ vm.command('test -f /run/archiso/copytoram/airootfs.sfs && test ! -e /run/archiso/bootmnt')
+ result['checks'].append('Real USB boot automatically copies the payload into RAM and unmounts the boot medium')
+ # The unmounted writable boot USB must still be rejected, even
+ # though its size otherwise makes it an eligible target.
+ probe = '''import importlib.util
+s = importlib.util.spec_from_file_location('installer', '/usr/lib/harness-os/install.py')
+i = importlib.util.module_from_spec(s)
+s.loader.exec_module(i)
+d = next(d for d in i.inventory() if d.get('serial') == 'HN_OS_LIVE')
+assert not d['ro'] and d['size'] >= i.MIN_DISK_BYTES
+try:
+ i.validate_disk(d)
+except ValueError as e:
+ assert 'booted into RAM' in str(e), str(e)
+else:
+ raise AssertionError('The unmounted boot USB was offered as a target')
+assert str(i.live_payload()) == '/run/archiso/copytoram/airootfs.sfs'
+'''
+ encoded = base64.b64encode(probe.encode()).decode()
+ vm.command('printf %s ' + encoded + ' | base64 -d | python3')
+ result['checks'].append('The unmounted writable Harness USB is rejected as an installation target in RAM mode')
+ vm.command('foot --check-config --config=/usr/share/harness-os/foot.ini')
+ vm.command(user("sh -c 'for n in $(seq 1 90); do systemctl --user is-active --quiet hn-screen && pgrep -u 1000 -x \"hn|harness-tui\" >/dev/null && exit 0; sleep 1; done; systemctl --user --no-pager status hn-screen harness-daemon; exit 1'"), timeout=110)
+ vm.command(user('/usr/lib/harness-os/wait-runtime'), timeout=160)
+ result['live_hn_ready_seconds'] = round(time.monotonic() - vm.started, 3)
+ result['checks'].append('Harness runtime reports discovery ready before hn startup is measured')
+ output, _ = vm.command("printf 'HN_SCRATCH=%s\\n' \"$(df -B1 --output=size /run/archiso/cowspace | tail -1)\"")
+ scratch_bytes = int(re.search(r'HN_SCRATCH=\s*(\d+)', output).group(1))
+ if scratch_bytes < args.memory * 1024 ** 2 * 0.45:
+ raise RuntimeError('Live writable space is too small for on-demand agent installation.')
+ result['live_scratch_mib'] = round(scratch_bytes / 1024 ** 2, 1)
+ vm.command('! pgrep -x chromium')
+ result['checks'].append('Live hn ready; browser absent at boot')
+ vm.command('systemctl start harness-keyring; pacman -Si git chromium >/dev/null', timeout=180)
+ result['checks'].append('Dated package repositories are queryable before the first download')
+ vm.command(user('systemd-run --user --quiet --wait --pipe --collect /bin/sh -c ' +
+ shlex.quote('printf hn-clipboard-check | wl-copy; test "$(wl-paste --no-newline)" = hn-clipboard-check')))
+ result['checks'].append('Wayland clipboard round trip')
+ vm.screenshot('01-live-hn')
+ output, _ = vm.command(user('hn-os measure'))
+ (folder / 'live-measurement.txt').write_text(output)
+ check_first_use(vm, user, folder)
+ result['checks'].append('USB Enter opens Install offline; Try opens network setup while disconnected; direct terminal accepts physical keyboard input')
+ result['checks'].append('Installer errors remain visible until acknowledged; exiting a direct terminal removes its pane')
+ result['checks'].append('USB first agent conversation accepts physical keyboard input and displays the expected reply')
+ result['checks'].append('Bundled OpenCode starts offline and its upstream-default clean-profile conversation returns the independently checked answer')
+ vm.keys('meta_l', 'b')
+ vm.command("for n in $(seq 1 45); do pgrep -x chromium >/dev/null && break; sleep 1; done; pgrep -x chromium", timeout=60)
+ time.sleep(3)
+ vm.screenshot('02-browser')
+ vm.keys('meta_l', 'b')
+ time.sleep(1)
+ vm.screenshot('03-return-to-hn')
+ result['checks'].append('Browser starts only on shortcut; toggle screenshots recorded')
+ # hn has its own tmux-style settings; the underlying tmux server needs
+ # its separate system configuration so a short-lived last pane cannot
+ # restart the server and reuse a still-registered terminal identity.
+ for index in range(3):
+ vm.command(user('hn new-window -n quick-exit ' + shlex.quote(f'touch /tmp/hn-quick-exit-{index}')))
+ vm.command(f'for n in $(seq 1 10); do test -e /tmp/hn-quick-exit-{index} && exit 0; sleep 1; done; exit 1', timeout=15)
+ result['checks'].append('Closing the last terminal and immediately opening another works repeatedly')
+ # A long-lived terminal process proves a screen restart does not kill the work.
+ survivor = "echo $$ > /tmp/hn-survivor.pid; exec sleep 1800"
+ vm.command(user("hn new-window -n persistence " + shlex.quote(survivor)))
+ vm.command('for n in $(seq 1 15); do test -s /tmp/hn-survivor.pid && exit 0; sleep 1; done; exit 1', timeout=20)
+ clipboard_probe = 'printf hn-pane-clipboard | wl-copy; test "$(wl-paste --no-newline)" = hn-pane-clipboard && touch /tmp/hn-pane-clipboard-passed'
+ vm.command(user('hn new-window -n clipboard ' + shlex.quote(clipboard_probe)))
+ vm.command('for n in $(seq 1 15); do test -e /tmp/hn-pane-clipboard-passed && exit 0; sleep 1; done; exit 1', timeout=20)
+ result['checks'].append('An hn terminal pane inherits the working Wayland clipboard environment')
+ vm.command('! ' + user('hn detach'))
+ vm.command('! ' + user('hn suspend-client'))
+ vm.command('kill -0 "$(cat /tmp/hn-survivor.pid)"')
+ result['checks'].append('OS surface refuses detach and suspend while work stays alive')
+ vm.command(user('systemctl --user restart hn-screen'))
+ vm.command('sleep 3; kill -0 "$(cat /tmp/hn-survivor.pid)"')
+ result['checks'].append('Terminal process survives screen restart')
+ check_console_fallback(vm, user, folder)
+ result['checks'].append('Graphics startup failure falls back to hn on tty1; physical-keyboard input reaches a terminal pane and existing work survives')
+ result['checks'].append('Restoring graphics returns to the fullscreen hn service without losing the terminal process')
+ if args.live_only:
+ result['status'] = 'passed'
+ return
+ config = dict(disk='/dev/vda', expected_serial='HN_OS_TEST', confirm_erase='/dev/vda',
+ username='me', hostname='harness', password='test-password-123',
+ encrypt=args.encrypt, serial_console=True)
+ # Installation must work with the NIC down, using the ISO's immutable payload.
+ vm.command('nmcli networking off')
+ install_interactively(vm, config, folder)
+ result['checks'].append('Keyboard disk selection, encryption checkbox, masked password entry and a single Install action work on the guest terminal')
+ result['checks'].append('Offline installer completed on disposable disk')
+ vm.command('sync')
+ vm.stop()
+ vm.start(live=False)
+ unlock_delay = 100 if config['encrypt'] else 0
+ vm.login_installed(config, unlock_delay=unlock_delay)
+ result['deliberate_unlock_delay_seconds'] = unlock_delay
+ if unlock_delay:
+ result['installed_unlock_prompt_seconds'] = vm.unlock_prompt_seconds
+ result['checks'].append('Harness unlock screen renders, masks input, accepts a retry after a wrong password, and unlocks after the deliberate 100-second wait')
+ result['installed_hn_ready_seconds_including_test_login'] = round(time.monotonic() - vm.started, 3)
+ result['installed_keyboard_readiness'] = check_graphical_keyboard(vm, 'installed')
+ result['checks'].append('Installed graphical hn accepts physical-keyboard shell input, returns output and returns home after closing the pane')
+ vm.command('test "$(id -un)" = ' + shlex.quote(config['username']) +
+ ' && test "$HOME" = ' + shlex.quote('/home/' + config['username']) +
+ ' && test "$(uname -n)" = ' + shlex.quote(config['hostname']))
+ vm.command('test ! -e /etc/sudoers.d/10-live && test ! -e /etc/harness-live && ! sudo -n true')
+ vm.command('! pgrep -x chromium')
+ vm.command('test "$(npm prefix -g)" = "$HOME/.local"')
+ vm.command('findmnt -n -o FSTYPE / | grep -qx btrfs')
+ vm.command('findmnt -n -o FSTYPE /boot | grep -qx vfat')
+ output, _ = vm.command('cat /var/lib/harness-os/install.json; hn-os measure')
+ (folder / 'installed-measurement.txt').write_text(output)
+ vm.screenshot('04-installed-hn')
+ result['checks'].append('Installed disk boots to hn with intended account permissions and no browser')
+ # Let boot jobs settle before calling a sample "idle". Keep all three
+ # measurements, including CPU, rather than selecting the smallest one.
+ output, _ = vm.command('sleep 45; for n in 1 2 3; do hn-os measure; done', timeout=65)
+ (folder / 'installed-idle-measurements.txt').write_text(output)
+ vm.boot_diagnostics(config, 'installed')
+ if config['encrypt'] and vm.acceleration == 'kvm':
+ assert vm.unlock_prompt_seconds < 30, 'Unlock prompt exceeded 30 seconds; see boot-events.jsonl and installed-boot-journal.log'
+ result['checks'].append('Encrypted unlock prompt appears within 30 seconds on the native x86 VM')
+ # A disposable failure exercises actual root + boot restoration, including
+ # an encrypted root in the UEFI row. The project's separate subvolume survives.
+ vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S -v')
+ update_script = base64.b64encode(Path(__file__).with_name('updates.sh').read_bytes()).decode()
+ vm.command(': > /tmp/hn-os-updates.b64')
+ for offset in range(0, len(update_script), 2000):
+ vm.command('printf %s ' + update_script[offset:offset + 2000] + ' >> /tmp/hn-os-updates.b64')
+ vm.command('base64 -d /tmp/hn-os-updates.b64 > /tmp/hn-os-updates.sh')
+ output, status = vm.command('sudo bash /tmp/hn-os-updates.sh', timeout=300, check=False)
+ (folder / 'update-retry.log').write_text(output)
+ assert status == 0, 'Full-update failure/retry check failed; see update-retry.log'
+ result['checks'].append('Failed full update blocks package changes; successful retry upgrades a local fixture and retains the original recovery checkpoint')
+ # A local package exercises the actual pacman PreTransaction hook while
+ # networking is unavailable. Its checkpoint includes the active db.lck.
+ package_script = '''set -eu
+mkdir -p /tmp/hn-recovery-package/etc
+printf 'pkgname = hn-os-recovery-probe\npkgver = 1-1\npkgdesc = Disposable VM rollback probe\narch = any\nsize = 7\n' > /tmp/hn-recovery-package/.PKGINFO
+printf changed > /tmp/hn-recovery-package/etc/hn-os-recovery-probe
+bsdtar --zstd -cf /tmp/hn-os-recovery-probe-1-1-any.pkg.tar.zst -C /tmp/hn-recovery-package .PKGINFO etc
+pacman --noconfirm -U /tmp/hn-os-recovery-probe-1-1-any.pkg.tar.zst
+'''
+ encoded = base64.b64encode(package_script.encode()).decode()
+ output, _ = vm.command('printf %s ' + encoded + ' | base64 -d | sudo bash', timeout=180)
+ checkpoint = re.search(r'Checkpoint ([A-Za-z0-9_-]+)', output).group(1)
+ vm.command('pacman -Q hn-os-recovery-probe && test -f /etc/hn-os-recovery-probe')
+ result['checks'].append('A real offline package transaction creates its pre-update checkpoint')
+ vm.command('printf keep-my-project > ~/Projects/recovery-probe.txt')
+ vm.command("sudo sh -c 'printf broken > /etc/hn-os-recovery-probe; chmod 000 /usr/lib/harness/harness-tui'")
+ vm.command('sync')
+ vm.stop()
+ vm.start(live=True)
+ vm.wait(r'root@[^\r\n]*[#] ')
+ vm.shell_ready = True
+ vm.command('stty -echo')
+ root_device = '/dev/vda3'
+ if config['encrypt']:
+ vm.command('printf %s ' + shlex.quote(config['password']) + ' | cryptsetup open --key-file=- /dev/vda3 hn-recovery')
+ root_device = '/dev/mapper/hn-recovery'
+ vm.command('hn-os recover ' + root_device + ' ' + checkpoint, timeout=180)
+ if config['encrypt']:
+ vm.command('cryptsetup close hn-recovery')
+ result['checks'].append('Offline checkpoint restored root and verified matching boot files')
+ vm.stop()
+ vm.start(live=False)
+ vm.login_installed(config)
+ vm.boot_diagnostics(config, 'recovered')
+ if config['encrypt']:
+ result['recovered_unlock_prompt_seconds'] = vm.unlock_prompt_seconds
+ if vm.acceleration == 'kvm':
+ assert vm.unlock_prompt_seconds < 30, 'Recovered unlock prompt exceeded 30 seconds; see recovered-boot-journal.log'
+ vm.command('test ! -e /etc/hn-os-recovery-probe && test -x /usr/lib/harness/harness-tui && test "$(cat ~/Projects/recovery-probe.txt)" = keep-my-project')
+ vm.command('test ! -e /var/lib/pacman/db.lck && ! pacman -Q hn-os-recovery-probe')
+ result['recovered_keyboard_readiness'] = check_graphical_keyboard(vm, 'recovered')
+ result['checks'].append('Recovered graphical hn accepts physical-keyboard shell input, returns output and returns home after closing the pane')
+ vm.screenshot('05-recovered-hn')
+ result['checks'].append('Recovered disk boots to hn; system and package database reverted, stale lock cleared and project preserved')
+ if args.agents:
+ # A real development toolchain must install from the shipped package
+ # indexes, compile a project, and serve its preview in another hn pane.
+ vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S pacman --noconfirm -S --needed gcc make', timeout=300)
+ development = base64.b64encode(Path(__file__).with_name('development.sh').read_bytes()).decode()
+ vm.command(f'printf %s {development} | base64 -d > /tmp/hn-os-development.sh')
+ vm.command('hn new-window -n development ' + shlex.quote('bash /tmp/hn-os-development.sh > "$HOME/.local/state/harness-os/development.log" 2>&1'))
+ output, _ = vm.command('for n in $(seq 1 60); do test -s ~/.local/state/harness-os/development-check/status && break; sleep 1; done; cat ~/.local/state/harness-os/development.log; test "$(cat ~/.local/state/harness-os/development-check/status)" = 0', timeout=75)
+ (folder / 'development.log').write_text(output)
+ vm.command('hn new-window -n local-preview ' + shlex.quote('node "$HOME/Projects/os-validation/server.mjs"'))
+ vm.command('curl --fail --retry 15 --retry-connrefused --retry-delay 1 http://127.0.0.1:18781 | grep -F "Local development works."', timeout=30)
+ vm.command('hn-browser http://127.0.0.1:18781')
+ time.sleep(5)
+ vm.screenshot('06-local-development-preview')
+ vm.keys('meta_l', 'ret')
+ vm.command('pkill -x chromium', check=False)
+ result['checks'].append('On-demand gcc/make installation, C compilation, Git diff and Node preview in an hn pane passed')
+ script = Path(__file__).with_name('agents.sh').read_bytes()
+ encoded = base64.b64encode(script).decode()
+ vm.command(f'printf %s {shlex.quote(encoded)} | base64 -d > /tmp/hn-os-agents.sh')
+ vm.command('hn new-window -n agent-compatibility ' + shlex.quote('bash /tmp/hn-os-agents.sh > "$HOME/.local/state/harness-os/agent-check.log" 2>&1'))
+ output, _ = vm.command('for n in $(seq 1 600); do test -s ~/.local/state/harness-os/agent-check/status && break; sleep 1; done; cat ~/.local/state/harness-os/agent-check.log; test "$(cat ~/.local/state/harness-os/agent-check/status)" = 0', timeout=630)
+ (folder / 'agent-installation.log').write_text(output)
+ output, _ = vm.command('cat ~/.local/state/harness-os/agent-check/packages.json')
+ (folder / 'agent-versions.txt').write_text(output)
+ result['checks'].append('Claude Code, Codex and pi install on demand; bundled OpenCode and all four agents report versions inside an hn terminal')
+ if args.workloads:
+ # Public fictional tasks only, in the disposable guest. No host keys,
+ # accounts or workspaces are made available to the model.
+ package = io.BytesIO()
+ with tarfile.open(fileobj=package, mode='w:gz') as archive:
+ archive.add(Path(__file__).with_name('workloads'), arcname='workloads')
+ if args.workload_seed:
+ seeds = list(args.workload_seed.rglob('Projects/os-workloads'))
+ if len(seeds) != 1:
+ raise RuntimeError('Need exactly one prior generated project tree.')
+ for name in ['terminal-tool', 'website', 'game', 'fullstack']:
+ archive.add(seeds[0] / name, arcname='workloads/seed/' + name)
+ result['workload_project_source_run_id'] = os.environ.get('OS_WORKLOAD_SOURCE_RUN')
+ encoded = base64.b64encode(package.getvalue()).decode()
+ vm.command(': > /tmp/hn-workloads.b64')
+ for offset in range(0, len(encoded), 2000):
+ vm.command('printf %s ' + encoded[offset:offset + 2000] + ' >> /tmp/hn-workloads.b64')
+ vm.command('base64 -d /tmp/hn-workloads.b64 | tar -xz -C /tmp; rm /tmp/hn-workloads.b64')
+ vm.command('hn new-window -n programmer-workloads ' + shlex.quote('bash /tmp/workloads/run.sh > "$HOME/.local/state/harness-os/workloads.log" 2>&1'))
+ output, _ = vm.command('for n in $(seq 1 3300); do test -s ~/.local/state/harness-os/workloads/status && break; sleep 1; done; cat ~/.local/state/harness-os/workloads.log', timeout=3320)
+ (folder / 'workloads.log').write_text(output)
+ # Keep both successful and failed model output for review; exclude
+ # install caches and dependencies from the small source archive.
+ vm.command('tar --exclude=node_modules --exclude=.git --exclude=__pycache__ -czf /tmp/hn-workloads-results.tgz -C "$HOME" Projects/os-workloads .local/state/harness-os/workloads', timeout=60)
+ output, _ = vm.command("printf 'HN_WORKLOAD_ARCHIVE='; base64 -w0 /tmp/hn-workloads-results.tgz; printf '\\n'", timeout=120)
+ packed = base64.b64decode(re.search(r'HN_WORKLOAD_ARCHIVE=([A-Za-z0-9+/=]+)', output).group(1), validate=True)
+ destination = folder / 'workloads'
+ destination.mkdir()
+ with tarfile.open(fileobj=io.BytesIO(packed), mode='r:gz') as archive:
+ archive.extractall(destination, filter='data')
+ (destination / '.local/state/harness-os/workloads').rename(destination / 'reports')
+ vm.command('test "$(cat ~/.local/state/harness-os/workloads/status)" = 0')
+ result['checks'].append('Free OpenCode built four projects; independent CLI, keyboard browser, game and persistent API checks passed')
+ if args.dsh:
+ package = io.BytesIO()
+ with tarfile.open(fileobj=package, mode='w:gz') as archive:
+ archive.add(Path(__file__).with_name('dsh'), arcname='dsh')
+ store = Path(__file__).resolve().parents[2] / 'store'
+ for component in ['viewers/web-viewer', 'viewers/game-viewer', 'examples/hello-world']:
+ archive.add(store / component, arcname='dsh/components/' + component)
+ encoded = base64.b64encode(package.getvalue()).decode()
+ vm.command(': > /tmp/hn-dsh.b64')
+ for offset in range(0, len(encoded), 2000):
+ vm.command('printf %s ' + encoded[offset:offset + 2000] + ' >> /tmp/hn-dsh.b64')
+ vm.command('base64 -d /tmp/hn-dsh.b64 | tar -xz -C /tmp; rm /tmp/hn-dsh.b64')
+ vm.command('hn new-window -n dsh-acceptance ' + shlex.quote('bash /tmp/dsh/run.sh > "$HOME/.local/state/harness-os/dsh-check.log" 2>&1'))
+ output, _ = vm.command('for n in $(seq 1 2700); do test -s ~/.local/state/harness-os/dsh-check/status && break; sleep 1; done; cat ~/.local/state/harness-os/dsh-check.log', timeout=2720)
+ (folder / 'dsh-check.log').write_text(output)
+ vm.command('tar --exclude=node_modules --exclude=.git --exclude=__pycache__ -czf /tmp/hn-dsh-results.tgz -C "$HOME" Projects/os-dsh .local/state/harness-os/dsh-check', timeout=60)
+ output, _ = vm.command("printf 'HN_DSH_ARCHIVE='; base64 -w0 /tmp/hn-dsh-results.tgz; printf '\\n'", timeout=120)
+ packed = base64.b64decode(re.search(r'HN_DSH_ARCHIVE=([A-Za-z0-9+/=]+)', output).group(1), validate=True)
+ destination = folder / 'dsh'
+ destination.mkdir()
+ with tarfile.open(fileobj=io.BytesIO(packed), mode='r:gz') as archive:
+ archive.extractall(destination, filter='data')
+ (destination / '.local/state/harness-os/dsh-check').rename(destination / 'reports')
+ vm.command('test "$(cat ~/.local/state/harness-os/dsh-check/status)" = 0')
+ result['checks'].append('Three managed DSH agents, terminal output, shared Web Viewer reload and Game Viewer keyboard play/export passed')
+ result['status'] = 'passed'
+ except Exception as error:
+ result['status'] = 'failed'
+ result['error'] = str(error)
+ if vm.shell_ready:
+ try:
+ diagnostics, _ = vm.command('journalctl -b --no-pager -n 350; systemctl --failed --no-pager; cat /home/*/.local/state/harness-os/display.log; ps -efww', timeout=20, check=False)
+ (folder / 'guest-diagnostics.log').write_text(diagnostics)
+ except Exception:
+ pass
+ try:
+ vm.screenshot('failure')
+ except Exception:
+ pass
+ raise
+ finally:
+ vm.stop()
+ vm.control.cleanup()
+ result['finished_at_unix'] = time.time()
+ (folder / 'receipt.json').write_text(json.dumps(result, indent=2) + '\n')
+ # Large disposable disks are never uploaded with the small evidence set.
+ vm.disk.unlink(missing_ok=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/workloads/check-browser.mjs b/os/tests/workloads/check-browser.mjs
new file mode 100644
index 000000000..69ad3cfaa
--- /dev/null
+++ b/os/tests/workloads/check-browser.mjs
@@ -0,0 +1,156 @@
+// Exercise generated applications with the OS's sandboxed Chromium, not a downloaded browser.
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { mkdirSync, openSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { chromium } from 'playwright';
+
+const [work, report] = process.argv.slice(2);
+mkdirSync(report, { recursive: true });
+const results = [];
+const servers = new Set();
+const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
+function start(name, command, args, env = {}) {
+ const log = openSync(join(report, `${name}-server.log`), 'a');
+ const child = spawn(command, args, { cwd: join(work, name), env: { ...process.env, ...env },
+ detached: true, stdio: ['ignore', log, log] });
+ servers.add(child);
+ return child;
+}
+async function stop(child) {
+ if (child.exitCode === null) {
+ try { process.kill(-child.pid, 'SIGTERM'); } catch {}
+ for (let i = 0; i < 50 && child.exitCode === null; i++) await delay(100);
+ if (child.exitCode === null) { try { process.kill(-child.pid, 'SIGKILL'); } catch {} }
+ }
+ servers.delete(child);
+}
+async function available(url) {
+ for (let i = 0; i < 120; i++) {
+ try { if ((await fetch(url)).ok) return; } catch {}
+ await delay(500);
+ }
+ throw new Error(`Server did not become ready: ${url}`);
+}
+async function row(name, check) {
+ const started = Date.now();
+ try { await check(); results.push({ name, status: 'passed', seconds: (Date.now() - started) / 1000 }); }
+ catch (error) { results.push({ name, status: 'failed', error: String(error), seconds: (Date.now() - started) / 1000 }); }
+ console.log(JSON.stringify(results.at(-1)));
+}
+
+const browser = await chromium.launch({ executablePath: '/usr/bin/chromium', chromiumSandbox: true, headless: true });
+const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
+try {
+ await row('website keyboard filtering and help', async () => {
+ const child = start('website', 'python3', ['-m', 'http.server', '18881', '--bind', '127.0.0.1']);
+ const page = await context.newPage();
+ try {
+ await available('http://127.0.0.1:18881');
+ await page.goto('http://127.0.0.1:18881');
+ assert.ok(await page.locator('article.talk:visible').count() >= 6, 'Six talks must be visible initially');
+ await page.screenshot({ path: join(report, 'website.png'), fullPage: true });
+ await page.locator('#search').focus();
+ await page.keyboard.type('no-such-conference-talk-987');
+ await page.waitForFunction(() => ![...document.querySelectorAll('article.talk')].some(t => !t.hidden));
+ await page.locator('#search').fill('');
+ await page.locator('#day-filter').focus();
+ await page.keyboard.press('ArrowDown');
+ await page.keyboard.press('Enter');
+ const day = await page.locator('#day-filter').inputValue();
+ assert.notEqual(day, 'all');
+ assert.ok(await page.locator('article.talk:visible').count() > 0);
+ assert.ok(await page.locator('article.talk:visible').evaluateAll((talks, selected) => talks.every(t => t.dataset.day === selected), day));
+ await page.locator('#help-button').focus();
+ await page.keyboard.press('Enter');
+ await page.locator('dialog').waitFor({ state: 'visible' });
+ await page.keyboard.press('Escape');
+ await page.locator('dialog').waitFor({ state: 'hidden' });
+ assert.equal(await page.evaluate(() => document.activeElement.id), 'help-button', 'Help restores keyboard focus');
+ await page.setViewportSize({ width: 390, height: 844 });
+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No horizontal overflow on a phone');
+ await page.screenshot({ path: join(report, 'website-mobile.png'), fullPage: true });
+ } finally { await page.close(); await stop(child); }
+ });
+ await row('game movement pause restart and state restoration', async () => {
+ const child = start('game', 'python3', ['-m', 'http.server', '18883', '--bind', '127.0.0.1']);
+ const page = await context.newPage();
+ try {
+ await available('http://127.0.0.1:18883');
+ await page.goto('http://127.0.0.1:18883');
+ await page.waitForFunction(() => window.harnessGame?.stats);
+ for (const viewport of [{ width: 1024, height: 768 }, { width: 1280, height: 800 }]) {
+ await page.setViewportSize(viewport);
+ assert.ok(await page.evaluate(() => {
+ const board = document.querySelector('canvas').getBoundingClientRect();
+ // TASK.txt requires a visible keyboard legend, not a CSS class name.
+ // Find its smallest containing element using the required controls.
+ const controls = element => /space/i.test(element.textContent) &&
+ /pause/i.test(element.textContent) && /restart/i.test(element.textContent);
+ const element = [...document.querySelectorAll('body *')].find(element =>
+ controls(element) && ![...element.children].some(controls));
+ if (!element) return false;
+ const legend = element.getBoundingClientRect();
+ return board.width > 200 && board.height > 200 && board.top >= 0 &&
+ board.bottom <= innerHeight && legend.width > 0 && legend.height > 0 &&
+ legend.top >= 0 && legend.bottom <= innerHeight &&
+ document.documentElement.scrollHeight <= innerHeight + 1;
+ }), 'The whole game and keyboard legend fit the laptop viewport');
+ }
+ await page.keyboard.press('Enter');
+ await page.screenshot({ path: join(report, 'game.png') });
+ let moved = false;
+ for (const key of ['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp']) {
+ const before = await page.evaluate(() => window.harnessGame.stats().player);
+ await page.keyboard.down(key); await delay(150); await page.keyboard.up(key);
+ const after = await page.evaluate(() => window.harnessGame.stats().player);
+ if (JSON.stringify(before) !== JSON.stringify(after)) { moved = true; break; }
+ }
+ assert.ok(moved, 'Arrow keys move the player');
+ await page.keyboard.press('Space');
+ assert.equal(await page.evaluate(() => window.harnessGame.stats().paused), true);
+ const frozen = await page.evaluate(() => window.harnessGame.captureState());
+ await delay(300);
+ assert.deepEqual(await page.evaluate(() => window.harnessGame.captureState()), frozen, 'Pause freezes simulation');
+ await page.keyboard.press('r');
+ assert.equal(await page.evaluate(() => window.harnessGame.stats().score), 0);
+ await page.evaluate(state => { window.harnessGame.setPaused(true); window.harnessGame.restoreState(state); }, frozen);
+ assert.deepEqual(await page.evaluate(() => window.harnessGame.captureState()), frozen);
+ } finally { await page.close(); await stop(child); }
+ });
+ await row('fullstack browser CRUD validation and persistence', async () => {
+ const url = 'http://127.0.0.1:18882';
+ const env = { PORT: '18882', DB_PATH: join(report, 'acceptance.sqlite') };
+ let child = start('fullstack', 'npm', ['start'], env);
+ const page = await context.newPage();
+ const request = (path, method = 'GET', data) => fetch(url + path, { method,
+ ...(data === undefined ? {} : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(data) }) });
+ try {
+ await available(url);
+ assert.equal((await request('/api/issues', 'POST', { title: '' })).status, 400);
+ assert.equal((await request('/api/issues/9999999', 'PATCH', { status: 'done' })).status, 404);
+ await page.goto(url);
+ await page.locator('#issue-title').focus(); await page.keyboard.type('Built on Harness');
+ await page.locator('#issue-body').fill('Created through the real keyboard-accessible frontend.');
+ await page.locator('#create-issue').focus(); await page.keyboard.press('Enter');
+ await page.getByText('Built on Harness', { exact: true }).waitFor();
+ const list = await (await request('/api/issues')).json();
+ const item = list.find(issue => issue.title === 'Built on Harness');
+ assert.ok(item?.id); assert.equal(item.status, 'open');
+ assert.equal((await request(`/api/issues/${item.id}`, 'PATCH', { status: 'invalid' })).status, 400);
+ assert.ok((await request(`/api/issues/${item.id}`, 'PATCH', { status: 'done' })).ok);
+ await page.reload();
+ await page.screenshot({ path: join(report, 'fullstack.png'), fullPage: true });
+ await stop(child); child = start('fullstack', 'npm', ['start'], env); await available(url);
+ const restored = await (await request('/api/issues')).json();
+ assert.equal(restored.find(issue => issue.id === item.id)?.status, 'done', 'SQLite data survives a server restart');
+ assert.ok((await request(`/api/issues/${item.id}`, 'DELETE')).ok);
+ assert.ok(!(await (await request('/api/issues')).json()).some(issue => issue.id === item.id));
+ } finally { await page.close(); await stop(child); }
+ });
+} finally {
+ await browser.close();
+ for (const child of servers) await stop(child);
+ writeFileSync(join(report, 'browser-receipt.json'), JSON.stringify({ chromium: browser.version(), results }, null, 2) + '\n');
+}
+if (results.some(result => result.status !== 'passed')) process.exitCode = 1;
diff --git a/os/tests/workloads/check-cli.py b/os/tests/workloads/check-cli.py
new file mode 100644
index 000000000..caba9acbe
--- /dev/null
+++ b/os/tests/workloads/check-cli.py
@@ -0,0 +1,31 @@
+"""Acceptance fixtures independent of the model-written logscope tests."""
+import json
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+
+tool = Path(sys.argv[1]).resolve()
+rows = '\n'.join([
+ '{"level":"info","service":"api","latency_ms":10}',
+ '{"level":"error","service":"api","latency_ms":90}',
+ 'not json',
+ '{"level":"info","service":"worker","latency_ms":-1}',
+ '{"level":"info","service":"api","latency_ms":20}',
+]) + '\n'
+
+def run(*args, text=None):
+ return json.loads(subprocess.check_output([sys.executable, str(tool), *args], input=text, text=True, timeout=10))
+
+with tempfile.TemporaryDirectory() as temp:
+ source = Path(temp) / 'events.jsonl'
+ source.write_text(rows)
+ actual = run(str(source))
+ assert actual == {'total': 4, 'malformed': 1, 'levels': {'info': 3, 'error': 1},
+ 'services': {'api': 3, 'worker': 1}, 'p50': 20, 'p95': 90}, actual
+ assert run(text=rows) == actual, 'stdin and file results differ'
+ filtered = run('--level', 'error', str(source))
+ assert filtered['total'] == 1 and filtered['p95'] == 90 and filtered['levels'] == {'error': 1}, filtered
+ empty = run(text='')
+ assert empty['total'] == 0 and empty['malformed'] == 0 and empty['p50'] is None and empty['p95'] is None, empty
+print('Independent CLI acceptance passed: file, stdin, malformed data, filtering and empty input.')
diff --git a/os/tests/workloads/fullstack.txt b/os/tests/workloads/fullstack.txt
new file mode 100644
index 000000000..308fc94b8
--- /dev/null
+++ b/os/tests/workloads/fullstack.txt
@@ -0,0 +1,2 @@
+Act as a full-stack programmer on Harness. Build a small local issue tracker called Patchboard using Node.js 22, the npm package fastify, and built-in node:sqlite. Install Fastify into this project with npm (do not install anything globally). Serve a responsive keyboard-accessible plain HTML/CSS/JS frontend and a REST API for creating, listing, updating status and deleting issues. Each issue has a title, body, status (open/in_progress/done), and created time. Bind to 127.0.0.1 on configurable PORT default 18882. Store data in a SQLite file configurable by DB_PATH, use parameterized statements, validate inputs, return 400 for bad requests and 404 for missing IDs. Include search and status filter in the frontend and a way to add an issue without using the mouse. Write meaningful Node built-in tests using Fastify inject and a temporary database: CRUD, invalid input, missing IDs, persistence across server close/reopen, and that HTML and assets are served. Add npm test and npm start scripts, run tests, fix failures. Keep dependencies minimal and do not use a bundler, framework frontend or external CDN. Include a concise README. Do the work now without questions or subagents.
+API contract: GET /api/issues returns an array of issue objects; POST /api/issues accepts {title,body} and returns a created object with an id and status=open; PATCH /api/issues/:id accepts {status}; DELETE /api/issues/:id deletes it. The frontend uses id=issue-title and id=issue-body for input fields and id=create-issue for the submit button.
diff --git a/os/tests/workloads/game.txt b/os/tests/workloads/game.txt
new file mode 100644
index 000000000..ffebd9cfd
--- /dev/null
+++ b/os/tests/workloads/game.txt
@@ -0,0 +1,2 @@
+Act as a game programmer on Harness. Create a polished small keyboard-only canvas game called Signal Run: the player moves through a grid collecting signal packets while avoiding moving hazards. Arrow keys or WASD move, Space pauses, R restarts, Enter starts. Include scoring, win and loss states, and a clear compact control legend. Use only HTML, CSS and vanilla JavaScript, no dependencies, no external assets. Keep simulation logic deterministic with a seeded random source and export the core state/update logic so meaningful Node tests can cover movement, wall bounds, collection, hazard collision, pause and restart. Add index.html, styles.css, game.mjs, simulation.mjs and test.mjs. Draw immediately on load and respond to resize. Expose window.harnessGame with setMode(mode), setPaused(boolean), restart(), stats() reporting state/score/player position, captureState(), restoreState(state); dispatch new CustomEvent("harness:ready") after the first real canvas render. Save a studio.json with title, description and controls. Run node --test test.mjs and fix failures. Document how to serve it with python3 -m http.server. Do the work now without questions or subagents.
+The stats() contract is {score:number,player:{x:number,y:number},paused:boolean,status:string}. Paused is false after start. Restart sets score=0 and a fresh player state. Start the player at an open grid position with at least one unobstructed neighboring cell.
diff --git a/os/tests/workloads/run.sh b/os/tests/workloads/run.sh
new file mode 100644
index 000000000..80add2957
--- /dev/null
+++ b/os/tests/workloads/run.sh
@@ -0,0 +1,78 @@
+#!/usr/bin/env bash
+# Opt-in live-model acceptance. These projects and tools never enter the ISO.
+set -uo pipefail
+INPUTS=$(cd -- "$(dirname -- "$0")" && pwd)
+WORK="$HOME/Projects/os-workloads"
+REPORT="$HOME/.local/state/harness-os/workloads"
+# The disposable guest has no provider credentials. Exercise the bundled
+# binary's upstream model choice, just as a clean first launch does.
+mkdir -p "$WORK" "$REPORT"
+if [[ -d "$INPUTS/seed" ]]; then
+ cp -a "$INPUTS/seed/." "$WORK/"
+ printf '%s\n' 'Reusing previously generated projects; only the interrupted game agent runs again.' > "$REPORT/reuse.txt"
+fi
+trap 'printf "%s\n" "$?" > "$REPORT/status"' EXIT
+/usr/bin/opencode --version > "$REPORT/opencode-version.txt" || exit 1
+printf '%s\n' 'Upstream default; no model flag or configuration override.' > "$REPORT/model.txt"
+failed=0
+for scenario in terminal-tool website game fullstack; do
+ project="$WORK/$scenario"
+ mkdir -p "$project"
+ cp "$INPUTS/$scenario.txt" "$project/TASK.txt"
+ cat > "$project/opencode.json" <<EOF
+{"permission":{"question":"deny","task":"deny","external_directory":{"*":"deny","$HOME/Projects/**":"allow","/tmp/opencode/**":"allow","/usr/share/harness-os/**":"allow"}}}
+EOF
+ printf '\nChecking %s with the upstream default model\n' "$scenario"
+ if [[ -d "$INPUTS/seed" && "$scenario" != game ]]; then
+ status=0
+ printf '%s\n' 'Prior completed model turn reused; project checks run again.' > "$REPORT/$scenario-agent-reused.txt"
+ # Dependencies are deliberately absent from the retained source artifact.
+ if [[ "$scenario" == fullstack ]]; then
+ (cd "$project" && npm ci --no-audit --no-fund) || exit 1
+ fi
+ else
+ prompt='Read TASK.txt, implement the complete task, run its tests, and fix failures. Work now without questions or subagents. Browser acceptance runs separately with sandboxed system Chromium; finish after your unit tests and do not launch a browser or long-running server.'
+ if [[ -d "$INPUTS/seed" ]]; then
+ prompt='The existing Signal Run game already passes its unit tests and independent keyboard/pause/restart/state checks. Perform ONE remaining task: adjust styles.css so the entire canvas and compact keyboard legend fit within a 1280x800 or 1024x768 browser viewport without vertical scrolling. Let the stage shrink into the remaining viewport height. Preserve simulation and bridge behavior. Do not rewrite the game, broaden features, audit edge cases, or add test frameworks. Run node --test test.mjs once, fix only regressions from your CSS change, then give your final answer and stop. A separate browser tester will verify layout. No questions or subagents.'
+ fi
+ (
+ cd "$project" || exit 1
+ timeout --signal=TERM --kill-after=15s 12m /usr/bin/opencode run --format json \
+ "$prompt" \
+ > "$REPORT/$scenario-agent.jsonl" 2>&1
+ )
+ status=$?
+ fi
+ printf '%s\n' "$status" > "$REPORT/$scenario-agent.status"
+ # The agent's process exit alone is not evidence it made working software.
+ (
+ set -e
+ cd "$project"
+ case "$scenario" in
+ terminal-tool)
+ test -s logscope.py
+ python3 -m unittest discover -v
+ python3 "$INPUTS/check-cli.py" "$project/logscope.py"
+ ;;
+ website) test -s index.html; test -s app.js; node --check app.js; node --test test.mjs ;;
+ game) test -s index.html; test -s game.mjs; node --check game.mjs; node --test test.mjs ;;
+ fullstack) test -s package-lock.json; npm test ;;
+ esac
+ ) > "$REPORT/$scenario-checks.log" 2>&1
+ check_status=$?
+ printf '%s\n' "$check_status" > "$REPORT/$scenario-checks.status"
+ if (( status || check_status )); then failed=1; fi
+ printf '%s: agent=%s, checks=%s\n' "$scenario" "$status" "$check_status"
+ tail -n 12 "$REPORT/$scenario-checks.log"
+done
+# Browser interaction and API persistence are checked independently of model-written tests.
+mkdir -p "$WORK/qa"
+PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install --prefix "$WORK/qa" --no-audit --no-fund playwright \
+ > "$REPORT/browser-install.log" 2>&1 || exit 1
+cp "$INPUTS/check-browser.mjs" "$WORK/qa/check-browser.mjs"
+node "$WORK/qa/check-browser.mjs" "$WORK" "$REPORT" > "$REPORT/browser-checks.log" 2>&1
+browser_status=$?
+printf '%s\n' "$browser_status" > "$REPORT/browser-checks.status"
+cat "$REPORT/browser-checks.log"
+if (( browser_status )); then failed=1; fi
+exit "$failed"
diff --git a/os/tests/workloads/terminal-tool.txt b/os/tests/workloads/terminal-tool.txt
new file mode 100644
index 000000000..e5ae9c4e4
--- /dev/null
+++ b/os/tests/workloads/terminal-tool.txt
@@ -0,0 +1,2 @@
+Act as a backend programmer on Harness. Build a Python 3 standard-library-only command-line tool named logscope.py for newline-delimited JSON logs. Read a file or stdin. Records contain level, service, and latency_ms. Print deterministic JSON with total valid rows, malformed rows, counts per level and service, and p50/p95 latency using nearest-rank percentiles. A malformed row should be counted and skipped, not crash. Negative or non-numeric latency is ignored for percentile calculations but the row remains valid. Empty input is valid. Add --level filtering. Create realistic fixtures and at least six meaningful unittest cases covering normal input, malformed input, empty input, percentile calculation, filtering, and stdin. Run python3 -m unittest discover -v and fix failures. Include a short README with terminal examples. Do not install dependencies. Work only in this project. Do the work now; do not ask questions or delegate to subagents.
+Use these exact JSON result keys: total, malformed, levels, services, p50, p95. total counts valid records after any level filter. Null percentiles represent no eligible latencies. --level filters valid rows before counting and percentile calculation. The command is python3 logscope.py [--level LEVEL] [FILE]; without FILE it reads stdin.
diff --git a/os/tests/workloads/website.txt b/os/tests/workloads/website.txt
new file mode 100644
index 000000000..de79b5980
--- /dev/null
+++ b/os/tests/workloads/website.txt
@@ -0,0 +1,2 @@
+Act as a frontend programmer on Harness. Build a complete single-page HTML/CSS/vanilla JS website for a fictional tiny developer conference called Terminal Days. Provide a schedule with at least 6 talks, day and track filters, live text search, and a keyboard-help dialog. All controls must work from the keyboard; use native buttons, inputs and labels, visible focus styles, Escape to close the dialog, and restore focus. Use a distinctive warm off-white and near-black visual design with one orange accent, a large editorial heading, and responsive layout. No external assets, fonts or CDN dependencies. Files: index.html, styles.css, app.js. Include a README with a Python http.server command. Keep the implementation small. Check JavaScript syntax and verify filter logic with Node tests in test.mjs (node --test test.mjs); use pure functions when useful. Do the work now; do not ask questions or delegate. Do not claim a browser check you did not actually run.
+For automated acceptance, use id=search for text search, id=day-filter and id=track-filter for native select elements with an all value; each schedule entry is an article.talk with data-day and data-track. Filtering must hide nonmatches with the hidden attribute. Give the keyboard help button id=help-button and use a native dialog element.
diff --git a/os/tools/build-package.py b/os/tools/build-package.py
new file mode 100644
index 000000000..6bf5106ae
--- /dev/null
+++ b/os/tools/build-package.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""Build the same small Harness package for an ISO or an installed test machine."""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import tarfile
+import tempfile
+
+
+def digest(path):
+ with path.open('rb') as handle:
+ return hashlib.file_digest(handle, 'sha256').hexdigest()
+
+
+def git(source, *args):
+ return subprocess.check_output(['git', '-c', f'safe.directory={source}', '-C', str(source), *args], text=True).strip()
+
+
+def validate_runtime(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('target') != 'x86_64-unknown-linux-musl':
+ raise ValueError('Runtime must be built from this clean source commit for Linux x86-64.')
+ 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') != 62:
+ raise ValueError('The terminal binary must be a 64-bit x86 Linux ELF executable.')
+ for name in ['cli.js', 'notify.mjs']:
+ if not (runtime / name).is_file() or not (runtime / name).stat().st_size:
+ raise ValueError('Missing runtime file: ' + name)
+ return info
+
+
+def stage(source, runtime, destination, commit):
+ info = validate_runtime(runtime, commit)
+ os_source = source / 'os'
+ shutil.copytree(os_source / 'root', destination, symlinks=True)
+ special = {
+ 'LICENSE': 'usr/share/licenses/harness-os/LICENSE',
+ 'os/installer.py': 'usr/lib/harness-os/install.py',
+ 'os/system.py': 'usr/lib/harness-os/system.py',
+ 'os/runtime_update.py': 'usr/lib/harness-os/runtime_update.py',
+ 'os/tools/hn-os': 'usr/bin/hn-os',
+ 'os/lock.json': 'usr/share/harness-os/lock.json',
+ }
+ for local, target in special.items():
+ path = destination / target
+ path.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source / local, path)
+ path.chmod(0o644)
+ 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 / target).chmod(0o755 if local == 'harness-tui' else 0o644)
+ (library / 'hn').symlink_to('harness-tui')
+ for directory in ['usr/bin', 'usr/lib/harness-os']:
+ for path in (destination / directory).rglob('*'):
+ if path.is_file() and not path.is_symlink():
+ path.chmod(0o755)
+ for name in ['autostart', 'shutdown']:
+ (destination / 'usr/share/harness-os/labwc' / name).chmod(0o755)
+ info.update(mode='source', files={p.name: {'sha256': digest(p), 'bytes': p.stat().st_size}
+ for p in library.iterdir() if p.is_file() and not p.is_symlink()})
+ (destination / 'usr/share/harness-os/runtime.json').write_text(json.dumps(info, indent=2) + '\n')
+ return info
+
+
+def archive_package(root, output, pkginfo, timestamp):
+ """Write root-owned package files without requiring root on the build host."""
+ (root / '.PKGINFO').write_text(pkginfo)
+ partial = output.with_name(output.name + '.partial')
+ try:
+ with tarfile.open(partial, 'w:gz', compresslevel=6, 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)
+ partial.replace(output)
+ finally:
+ partial.unlink(missing_ok=True)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--runtime', type=Path, required=True)
+ parser.add_argument('--output', type=Path, required=True)
+ parser.add_argument('--development', action='store_true', help='Include a source revision in the package version')
+ args = parser.parse_args()
+ source = Path(__file__).resolve().parents[2]
+ if git(source, 'status', '--porcelain', '--untracked-files=normal'):
+ parser.error('Commit source changes before building a traceable package.')
+ commit = git(source, 'rev-parse', 'HEAD')
+ timestamp = int(git(source, 'log', '-1', '--format=%ct'))
+ lock = json.loads((source / 'os/lock.json').read_text())
+ if lock['architecture'] != 'x86_64' or not re.fullmatch(r'\d+\.\d+\.\d+-preview\.\d+', lock['version']):
+ parser.error('Expected a versioned x86-64 OS preview.')
+ version = lock['version'].replace('-preview.', 'pre')
+ if args.development:
+ version += '.r' + git(source, 'rev-list', '--count', 'HEAD') + '.g' + commit[:10]
+ version += '-1'
+ folder = args.output.resolve()
+ folder.mkdir(parents=True, exist_ok=True)
+ package = folder / f'harness-os-{version}-x86_64.pkg.tar.gz'
+ if package.exists() or (folder / 'package-manifest.json').exists():
+ parser.error('Use a fresh output directory; package artifacts are immutable.')
+ with tempfile.TemporaryDirectory(prefix='harness-package-') as temp:
+ root = Path(temp) / 'root'
+ runtime = stage(source, args.runtime.resolve(), root, commit)
+ size = sum(p.stat().st_size for p in root.rglob('*') if p.is_file() and not p.is_symlink())
+ pkginfo = (f'pkgname = harness-os\npkgbase = harness-os\nxdata = pkgtype=pkg\npkgver = {version}\n'
+ 'pkgdesc = Harness session and verified Harness runtime\n'
+ 'url = https://github.com/autonomous-ai/openharness\n'
+ f'builddate = {timestamp}\npackager = OpenHarness\nsize = {size}\n'
+ 'arch = x86_64\nlicense = MIT\ndepend = nodejs-lts-jod\ndepend = tmux\n'
+ 'depend = foot\ndepend = labwc\n')
+ archive_package(root, package, pkginfo, timestamp)
+ manifest = {'schema': 1, 'kind': 'harness-os-package', 'development': args.development,
+ 'source_commit': commit, 'architecture': lock['architecture'],
+ 'requires_os_version': lock['version'], 'arch_snapshot': lock['arch_snapshot'],
+ 'runtime': runtime,
+ 'package': {'name': package.name, 'version': version, 'bytes': package.stat().st_size, 'sha256': digest(package)}}
+ (folder / 'package-manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
+ (folder / (package.name + '.sha256')).write_text(f'{manifest["package"]["sha256"]} {package.name}\n')
+ # A preview 4 installation can bootstrap the updater from this same bundle.
+ bootstrap = folder / 'apply-update.py'
+ shutil.copyfile(source / 'os/runtime_update.py', bootstrap)
+ (folder / 'SHA256SUMS').write_text(''.join(f'{digest(path)} {path.name}\n' for path in
+ [package, folder / 'package-manifest.json', bootstrap]))
+ print(json.dumps(manifest, indent=2))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tools/build-runtime.sh b/os/tools/build-runtime.sh
new file mode 100644
index 000000000..cb638e6ad
--- /dev/null
+++ b/os/tools/build-runtime.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Build as an ordinary user on x86_64 Linux, before the privileged image build.
+set -euo pipefail
+REPO_DIR=$(cd -- "$(dirname -- "$0")/../.." && pwd)
+[[ $(uname -sm) == 'Linux x86_64' ]] || { echo 'OS runtimes require an x86_64 Linux build host.' >&2; exit 1; }
+cd "$REPO_DIR"
+npm 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
+def output(*args):
+ return subprocess.check_output(args, text=True).strip()
+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'}
+pathlib.Path('os/work/runtime/source.json').write_text(json.dumps(data, indent=2) + '\n')
+PY
diff --git a/os/tools/check.py b/os/tools/check.py
new file mode 100644
index 000000000..786041fde
--- /dev/null
+++ b/os/tools/check.py
@@ -0,0 +1,21 @@
+#!/usr/bin/env python3
+"""Portable checks for image inputs, without installing packages or touching disks."""
+import ast
+import json
+from pathlib import Path
+import subprocess
+import xml.etree.ElementTree as ET
+
+root = Path(__file__).resolve().parents[1]
+for p in root.rglob('*'):
+ if not p.is_file() or set(p.relative_to(root).parts) & {'work', 'dist', 'test-results', '__pycache__'}:
+ continue
+ if p.suffix == '.py' or p.name == 'hn-os':
+ ast.parse(p.read_text(), filename=str(p))
+ elif p.suffix == '.json':
+ json.loads(p.read_text())
+ elif p.suffix == '.xml':
+ ET.parse(p)
+ elif p.read_bytes().startswith((b'#!/bin/sh', b'#!/bin/bash', b'#!/usr/bin/env bash')):
+ subprocess.run(['bash', '-n', str(p)], check=True)
+print('Python, JSON, XML and shell syntax checked.')
diff --git a/os/tools/customize-live.sh b/os/tools/customize-live.sh
new file mode 100644
index 000000000..dfbf94289
--- /dev/null
+++ b/os/tools/customize-live.sh
@@ -0,0 +1,60 @@
+#!/bin/bash
+set -euo pipefail
+# Validate with the exact terminal version being shipped, before compressing it.
+foot --check-config --config=/usr/share/harness-os/foot.ini
+echo 'en_US.UTF-8 UTF-8' > /etc/locale.gen
+locale-gen
+echo 'LANG=en_US.UTF-8' > /etc/locale.conf
+echo harness > /etc/hostname
+touch /etc/harness-live
+ln -sf /usr/share/zoneinfo/UTC /etc/localtime
+ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
+useradd -m -G wheel,video,audio -s /bin/bash me
+passwd -d me
+passwd -d root
+mkdir -p /etc/sudoers.d /home/me/Projects /etc/systemd/system/[email protected]
+echo 'me ALL=(ALL:ALL) NOPASSWD: ALL' > /etc/sudoers.d/10-live
+chmod 440 /etc/sudoers.d/10-live
+chown me:me /home/me/Projects
+systemctl enable NetworkManager systemd-resolved systemd-timesyncd [email protected]
+systemctl enable harness-keyring.service
+# hn-screen starts the daemon after labwc has published the display environment.
+# Linger keeps that runtime alive if its graphical client is restarted.
+mkdir -p /var/lib/systemd/linger
+touch /var/lib/systemd/linger/me
+# Agent auth and browser downloads never block boot. No SSH listener by default.
+systemctl disable NetworkManager-wait-online.service || true
+systemctl disable archlinux-keyring-wkd-sync.timer
+systemctl mask systemd-networkd.service systemd-networkd-wait-online.service
+ln -sf /usr/lib/systemd/system/multi-user.target /etc/systemd/system/default.target
+printf '[Service]\nExecStart=\nExecStart=-/usr/bin/agetty --autologin me --noclear %%I $TERM\n' > /etc/systemd/system/[email protected]/autologin.conf
+# A serial console is useful for recovering a live USB; never carried into the install.
+mkdir -p /etc/systemd/system/[email protected]
+printf '[Service]\nExecStart=\nExecStart=-/usr/bin/agetty --autologin root --noclear %%I 115200\n' > /etc/systemd/system/[email protected]/live.conf
+systemctl enable [email protected]
+python3 - <<'PY'
+import hashlib, json
+from pathlib import Path
+lock = json.loads(Path('/usr/share/harness-os/lock.json').read_text())
+snapshot = lock['arch_snapshot']
+Path('/etc/pacman.conf').write_text(
+ '[options]\nArchitecture = auto\nCheckSpace\nSigLevel = Required DatabaseOptional\nLocalFileSigLevel = Optional\n' +
+ ''.join(f'[{repo}]\nServer = https://archive.archlinux.org/repos/{snapshot}/$repo/os/$arch\n' for repo in ['core', 'extra']))
+# archiso removes /boot from SquashFS after placing boot files on the ISO.
+# Keep the exact package-owned kernel location for an offline disk install.
+kernels = [p.parent / 'vmlinuz' for p in Path('/usr/lib/modules').glob('*/pkgbase') if p.read_text().strip() == 'linux-lts']
+if len(kernels) != 1 or not kernels[0].is_file():
+ raise SystemExit('Expected one package-owned LTS kernel for the installer.')
+kernel = kernels[0]
+with kernel.open('rb') as handle:
+ digest = hashlib.file_digest(handle, 'sha256').hexdigest()
+Path('/usr/share/harness-os/kernel.json').write_text(json.dumps({'path': str(kernel.relative_to('/')), 'sha256': digest}) + '\n')
+PY
+pacman -Q > /usr/share/harness-os/packages.txt
+# Archiso removes pacman's sync databases during cleanup. Preserve the two
+# dated repositories so the first package query/install works immediately.
+install -d /usr/share/harness-os/repository-databases
+for repo in core extra; do
+ install -m 644 "/var/lib/pacman/sync/$repo.db" "/usr/share/harness-os/repository-databases/$repo.db"
+done
+rm -rf /var/cache/pacman/pkg/* /root/.cache
diff --git a/os/tools/hn-os b/os/tools/hn-os
new file mode 100644
index 000000000..794c761d9
--- /dev/null
+++ b/os/tools/hn-os
@@ -0,0 +1,86 @@
+#!/usr/bin/env python3
+"""System operations callable from an agent's ordinary shell."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+
+
+def capture(*args):
+ result = subprocess.run(args, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ return {'exit_status': result.returncode, 'output': result.stdout.strip()}
+
+
+def cpu_ticks():
+ # user/nice/system/idle/iowait/irq/softirq/steal; guest times are already in user/nice.
+ values = [int(value) for value in Path('/proc/stat').read_text().splitlines()[0].split()[1:9]]
+ return sum(values), values[3] + values[4]
+
+
+def connected():
+ result = subprocess.run(['nmcli', '--wait', '5', '-t', '-f', 'STATE', 'general'],
+ text=True, capture_output=True, timeout=8, env=dict(os.environ, LC_ALL='C'))
+ return result.returncode == 0 and result.stdout.strip() == 'connected'
+
+
+def wifi():
+ # Reuse NetworkManager's keyboard UI; it owns password entry and storage.
+ # Never put a Wi-Fi password in shell arguments, logs, or our own config.
+ subprocess.run(['sudo', 'nmcli', 'radio', 'wifi', 'on'], check=False)
+ return subprocess.call(['sudo', 'nmtui-connect'])
+
+
+def try_harness():
+ if not connected():
+ if wifi() != 0 or not connected():
+ print('OpenCode needs an internet connection. Connect to Wi-Fi or plug in Ethernet, then try again.')
+ if sys.stdin.isatty():
+ input('Press Enter to return to Harness.')
+ return
+ projects = Path.home() / 'Projects'
+ projects.mkdir(exist_ok=True)
+ os.chdir(projects)
+ os.execv('/usr/bin/opencode', ['opencode'])
+
+
+def main():
+ args = sys.argv[1:]
+ command = args.pop(0) if args else 'status'
+ if command == 'install':
+ 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])
+ if command == 'wifi':
+ raise SystemExit(wifi())
+ if command == 'try':
+ try_harness()
+ return
+ if command in ['checkpoint', 'update', 'recover']:
+ 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())
+ subprocess.run(['systemctl', '--user', '--no-pager', 'status', 'harness-daemon', 'hn-screen'])
+ return
+ if command == 'measure':
+ before, idle_before = cpu_ticks()
+ time.sleep(2)
+ after, idle_after = cpu_ticks()
+ memory = {line.split(':')[0]: int(line.split()[1]) for line in Path('/proc/meminfo').read_text().splitlines()}
+ disk = os.statvfs('/')
+ data = {'uptime_seconds': float(Path('/proc/uptime').read_text().split()[0]),
+ 'memory_total_mib': round(memory['MemTotal'] / 1024, 2),
+ 'memory_used_excluding_available_mib': round((memory['MemTotal'] - memory['MemAvailable']) / 1024, 2),
+ 'cpu_busy_percent_over_2s': round(100 * (1 - (idle_after - idle_before) / max(1, after - before)), 2),
+ 'root_filesystem_used_bytes_including_home_and_snapshots': (disk.f_blocks - disk.f_bfree) * disk.f_frsize,
+ 'boot': capture('systemd-analyze'),
+ 'screen_service_started_monotonic_usec': capture('systemctl', '--user', 'show', 'hn-screen', '--property=ActiveEnterTimestampMonotonic', '--value'),
+ 'processes_rss_kib_and_lifetime_cpu': capture('ps', '-eo', 'comm,rss,pcpu', '--sort=-rss')}
+ print(json.dumps(data, indent=2))
+ return
+ raise SystemExit('Usage: hn-os [status | try | wifi | install | browser [URL] | measure | checkpoint | update [--snapshot YYYY/MM/DD] | recover ROOT_DEVICE [CHECKPOINT]]')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tools/inspect_image.py b/os/tools/inspect_image.py
new file mode 100644
index 000000000..a54f4ce2a
--- /dev/null
+++ b/os/tools/inspect_image.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Inspect the actual ISO payload, independently of the image's staging tree."""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+
+
+def sha256(path):
+ with path.open('rb') as handle:
+ return hashlib.file_digest(handle, 'sha256').hexdigest()
+
+
+def inspect(iso):
+ source = Path(__file__).resolve().parents[1]
+ manifest = json.loads((iso.parent / 'manifest.json').read_text())
+ assert iso.name == manifest['iso']['name'] and iso.stat().st_size == manifest['iso']['bytes']
+ assert sha256(iso) == manifest['iso']['sha256'], 'ISO checksum mismatch'
+ report = subprocess.run(['xorriso', '-no_rc', '-indev', str(iso), '-report_el_torito', 'plain', '-report_system_area', 'plain'], check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True).stdout
+ (iso.parent / 'boot-layout.txt').write_text(report)
+ for platform in ['BIOS', 'UEFI']:
+ assert re.search(r'El Torito boot img\s*:.*\b' + platform + r'\b', report), f'{platform} boot entry is missing'
+ checked = []
+ with tempfile.TemporaryDirectory(prefix='hn-iso-inspect-') as temp:
+ payload = Path(temp) / 'airootfs.sfs'
+ subprocess.run(['xorriso', '-no_rc', '-osirrox', 'on', '-indev', str(iso), '-extract', '/arch/x86_64/airootfs.sfs', str(payload)], check=True)
+ def read(path):
+ return subprocess.check_output(['unsquashfs', '-cat', str(payload), path])
+ files = {str(p.relative_to(source / 'root')): p for p in (source / 'root').rglob('*') if p.is_file()}
+ files.update({'usr/lib/harness-os/install.py': source / 'installer.py',
+ 'usr/lib/harness-os/system.py': source / 'system.py',
+ 'usr/bin/hn-os': source / 'tools/hn-os',
+ 'usr/share/harness-os/lock.json': source / 'lock.json'})
+ for path, expected in files.items():
+ assert read(path) == expected.read_bytes(), f'Payload does not match source: {path}'
+ checked.append(path)
+ listing = subprocess.check_output(['unsquashfs', '-lln', str(payload)], text=True)
+ owners = {}
+ for line in listing.splitlines():
+ fields = line.split(maxsplit=5)
+ if len(fields) == 6 and fields[1].count('/') == 1 and fields[5].startswith('squashfs-root'):
+ path = fields[5].split(' -> ', 1)[0] if fields[0].startswith('l') else fields[5]
+ owners[path.removeprefix('squashfs-root').lstrip('/')] = fields[1]
+ for path in [*files, '', 'etc', 'usr', 'usr/bin', 'usr/lib/harness-os', 'usr/share/harness-os']:
+ assert owners.get(path) == '0/0', f'Packaged system path is not owned by root: {path}'
+ runtime = json.loads(read('usr/share/harness-os/runtime.json'))
+ assert runtime == manifest['harness_inputs'] and runtime['source_commit'] == manifest['source_commit']
+ assert not runtime['dirty'] and runtime['target'] == 'x86_64-unknown-linux-musl'
+ for name, identity in runtime['files'].items():
+ data = read('usr/lib/harness/' + name)
+ assert len(data) == identity['bytes'] and hashlib.sha256(data).hexdigest() == identity['sha256'], f'Runtime mismatch: {name}'
+ kernel = json.loads(read('usr/share/harness-os/kernel.json'))
+ assert re.fullmatch(r'usr/lib/modules/[a-zA-Z0-9._+-]+/vmlinuz', kernel['path'])
+ assert hashlib.sha256(read(kernel['path'])).hexdigest() == kernel['sha256'], 'Offline install kernel mismatch'
+ assert read(str(Path(kernel['path']).with_name('pkgbase'))).strip() == b'linux-lts'
+ packages = read('usr/share/harness-os/packages.txt').decode()
+ assert packages == (iso.parent / 'packages.txt').read_text(), 'Package inventory mismatch'
+ inventory = dict(row.split(maxsplit=1) for row in packages.splitlines())
+ names = set(inventory)
+ version = json.loads(read('usr/share/harness-os/lock.json'))['version']
+ assert version == manifest['version'], 'Image version differs from the build manifest'
+ assert inventory['harness-os'] == version.replace('-preview.', 'pre') + '-1', 'OS package version differs from the image version'
+ wanted = {row.strip() for row in (source / 'packages.x86_64').read_text().splitlines() if row.strip() and not row.startswith('#')}
+ assert wanted.issubset(names), f'Missing packages: {wanted - names}'
+ config = read('etc/pacman.conf').decode()
+ assert config.count('/' + manifest['arch_snapshot'] + '/') == 2 and '[harness-build]' not in config
+ assert 'SigLevel = Required DatabaseOptional' in config
+ for repo in ['core', 'extra']:
+ assert len(read(f'usr/share/harness-os/repository-databases/{repo}.db')) > 65536, f'Missing offline {repo} repository database'
+ assert b'me:x:1000:' in read('etc/passwd'), 'Live user was not created'
+ assert b'--autologin me' in read('etc/systemd/system/[email protected]/autologin.conf')
+ assert read('etc/hostname').strip() == b'harness'
+ assert 'etc/harness-live' in owners, 'Live welcome marker is missing'
+ for executable in ['usr/bin/opencode', 'usr/bin/nmtui', 'usr/bin/nmtui-connect']:
+ assert owners.get(executable) == '0/0', f'Missing or non-root-owned executable: {executable}'
+ receipt = {'status': 'passed', 'scope': 'ISO boot entries, exact SquashFS configuration, runtime and offline kernel hashes, live account and package inventory',
+ 'source_commit': manifest['source_commit'], 'iso_sha256': manifest['iso']['sha256'],
+ 'payload_sha256': sha256(payload), 'package_count': len(names), 'source_files_compared': checked,
+ 'limitations': 'Does not establish that the guest boots, installs, recovers or supports physical hardware.'}
+ (iso.parent / 'inspection.json').write_text(json.dumps(receipt, indent=2) + '\n')
+ print(json.dumps({key: value for key, value in receipt.items() if key != 'source_files_compared'}, indent=2))
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('iso', type=Path)
+ inspect(parser.parse_args().iso.resolve())
diff --git a/os/tools/manifest.py b/os/tools/manifest.py
new file mode 100644
index 000000000..990355d95
--- /dev/null
+++ b/os/tools/manifest.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python3
+import hashlib
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+
+out, root = map(Path, sys.argv[1:])
+lock = json.loads((Path(__file__).resolve().parents[1] / 'lock.json').read_text())
+isos = list(out.glob('*.iso'))
+if len(isos) != 1:
+ raise SystemExit('Expected exactly one ISO')
+iso = isos[0]
+with iso.open('rb') as handle:
+ digest = hashlib.file_digest(handle, 'sha256').hexdigest()
+(out / (iso.name + '.sha256')).write_text(f'{digest} {iso.name}\n')
+packages = (root / 'usr/share/harness-os/packages.txt').read_text()
+(out / 'packages.txt').write_text(packages)
+manifest = {
+ 'version': lock['version'], 'architecture': 'x86_64',
+ 'source_commit': os.environ.get('HARNESS_OS_SOURCE_SHA') or subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(),
+ 'built_at_unix': int(time.time()), 'arch_snapshot': lock['arch_snapshot'],
+ 'iso': {'name': iso.name, 'bytes': iso.stat().st_size, 'sha256': digest},
+ 'harness_inputs': json.loads((root / 'usr/share/harness-os/runtime.json').read_text()), 'validation': 'pending',
+}
+(out / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
diff --git a/os/tools/publish.py b/os/tools/publish.py
new file mode 100644
index 000000000..55447f0f7
--- /dev/null
+++ b/os/tools/publish.py
@@ -0,0 +1,221 @@
+#!/usr/bin/env python3
+"""Publish an already-tested preview; never turn an incomplete VM run into a release."""
+import argparse
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+import time
+import zipfile
+
+REQUIRED_CHECKS = ['Live hn ready;', 'Wayland clipboard round trip',
+ 'USB Enter opens Install offline;',
+ 'USB first agent conversation accepts physical keyboard input',
+ 'Bundled OpenCode starts offline and its upstream-default clean-profile conversation',
+ 'Keyboard disk selection, encryption checkbox, masked password entry and a single Install action',
+ 'Browser starts only on shortcut', 'Dated package repositories are queryable',
+ 'Closing the last terminal and immediately opening another',
+ 'An hn terminal pane inherits', 'OS surface refuses detach',
+ 'Terminal process survives screen restart', 'Offline installer completed',
+ 'Installed disk boots to hn', 'A real offline package transaction',
+ 'Offline checkpoint restored', 'Recovered disk boots to hn']
+
+
+def digest(path):
+ with path.open('rb') as handle:
+ return hashlib.file_digest(handle, 'sha256').hexdigest()
+
+
+def gh(*args):
+ return subprocess.check_output(['gh', *map(str, args)], text=True, timeout=120).strip()
+
+
+def read(path):
+ return json.loads(path.read_text())
+
+
+def validate_install_guide(manifest, guide):
+ if (f'These instructions are for **{manifest["version"]}**' not in guide or
+ manifest['iso']['name'] not in guide):
+ raise ValueError('The installation guide must match the release version and ISO filename.')
+
+
+def validate_receipts(manifest, receipts):
+ rows = {(r['firmware'], r['encrypted']): r for r in receipts}
+ if set(rows) != {('bios', False), ('uefi', True)} or len(receipts) != 2:
+ raise ValueError('Need one plain BIOS and one encrypted UEFI receipt.')
+ for receipt in receipts:
+ if receipt['status'] != 'passed' or receipt.get('scope') == 'live session only':
+ raise ValueError('Machine validation is incomplete or failed.')
+ if receipt['iso_sha256'] != manifest['iso']['sha256'] or receipt['image_source_commit'] != manifest['source_commit']:
+ raise ValueError('Machine receipt covers a different image or source.')
+ checks = receipt.get('checks', [])
+ if any(not any(check.startswith(prefix) for check in checks) for prefix in REQUIRED_CHECKS):
+ raise ValueError('A required live, installation or recovery check is absent.')
+ if not any(check.startswith('Harness unlock screen renders, masks input, accepts a retry') for check in rows[('uefi', True)]['checks']):
+ raise ValueError('The encrypted graphical unlock and retry checks have not passed.')
+ if not any(check.startswith('Claude Code, Codex and pi install on demand; bundled OpenCode') for check in rows[('bios', False)]['checks']):
+ raise ValueError('Real agent executable compatibility has not passed.')
+ if not any(check.startswith('On-demand gcc/make installation') for check in rows[('bios', False)]['checks']):
+ raise ValueError('The real compiler and local web development check has not passed.')
+
+
+def validate_examples(folder, kind):
+ """Reject missing/failed independent application evidence before publishing it."""
+ reports = list(folder.rglob(f'{kind}/reports'))
+ if len(reports) != 1:
+ raise ValueError(f'Expected one {kind} report directory.')
+ report = reports[0]
+ if kind == 'dsh':
+ rows = read(report / 'results.json')
+ if len(rows) != 3 or {r['name'] for r in rows} != {'hello', 'logs', 'game'} or any(r['status'] != 'passed' for r in rows):
+ raise ValueError('All three real DSH exercises must pass.')
+ else:
+ for name in ['terminal-tool', 'website', 'game', 'fullstack']:
+ for stage in ['agent', 'checks']:
+ if (report / f'{name}-{stage}.status').read_text().strip() != '0':
+ raise ValueError(f'{name} {stage} did not complete successfully.')
+ rows = read(report / 'browser-receipt.json')['results']
+ names = {'website keyboard filtering and help', 'game movement pause restart and state restoration',
+ 'fullstack browser CRUD validation and persistence'}
+ if len(rows) != 3 or {r['name'] for r in rows} != names or any(r['status'] != 'passed' for r in rows):
+ raise ValueError('All independent browser/API checks must pass.')
+ return rows
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--input', type=Path, required=True)
+ parser.add_argument('--tests', type=int, required=True)
+ parser.add_argument('--image', type=int, required=True)
+ parser.add_argument('--dsh', type=int, default=0)
+ parser.add_argument('--repo', required=True)
+ parser.add_argument('--prepare-only', action='store_true', help='Validate and assemble local review files without publishing')
+ args = parser.parse_args()
+ root = args.input.resolve()
+ folder = root / 'image'
+ manifest = read(folder / 'manifest.json')
+ version = manifest['version']
+ if not re.fullmatch(r'\d+\.\d+\.\d+-preview\.\d+', version):
+ raise ValueError('This publisher only creates explicitly versioned previews.')
+ iso = folder / manifest['iso']['name']
+ if iso.parent != folder or not iso.name.endswith('.iso') or iso.stat().st_size != manifest['iso']['bytes'] or digest(iso) != manifest['iso']['sha256']:
+ raise ValueError('ISO identity does not match its manifest.')
+ inspection = read(folder / 'inspection.json')
+ if inspection['status'] != 'passed' or inspection['iso_sha256'] != manifest['iso']['sha256'] or inspection['source_commit'] != manifest['source_commit']:
+ raise ValueError('The actual image payload has not passed inspection.')
+ receipts = [read(path) for path in (root / 'machines').rglob('receipt.json')]
+ validate_receipts(manifest, receipts)
+ run = json.loads(gh('api', f'repos/{args.repo}/actions/runs/{args.tests}'))
+ image = json.loads(gh('api', f'repos/{args.repo}/actions/runs/{args.image}'))
+ jobs = json.loads(gh('api', f'repos/{args.repo}/actions/runs/{args.image}/jobs?filter=latest&per_page=100'))
+ if run['conclusion'] != 'success' or run['status'] != 'completed' or run['path'] != '.github/workflows/os.yml':
+ raise ValueError('The machine workflow did not finish successfully.')
+ if image['head_sha'] != manifest['source_commit'] or not any(j['name'] == 'image' and j['conclusion'] == 'success' for j in jobs['jobs']):
+ raise ValueError('The image does not match a successful build job.')
+ examples = {}
+ if list((root / 'machines').rglob('workloads/reports')):
+ examples['workloads'] = {'run': run['html_url'], 'browser_checks': validate_examples(root / 'machines', 'workloads')}
+ if args.dsh:
+ dsh_run = json.loads(gh('api', f'repos/{args.repo}/actions/runs/{args.dsh}'))
+ if dsh_run['conclusion'] != 'success' or dsh_run['status'] != 'completed' or dsh_run['path'] != '.github/workflows/os.yml':
+ raise ValueError('The DSH workflow did not finish successfully.')
+ dsh_receipts = [read(path) for path in (root / 'dsh-machines').rglob('receipt.json')]
+ validate_receipts(manifest, dsh_receipts)
+ examples['dsh'] = {'run': dsh_run['html_url'], 'machines': dsh_receipts,
+ 'checks': validate_examples(root / 'dsh-machines', 'dsh')}
+ limitations = ['Physical ThinkPad, Wi-Fi, suspend and NVIDIA hardware remain unverified.',
+ 'Account-authenticated Claude/Codex model turns remain unverified. Bundled OpenCode default first-use turns are recorded in the machine evidence; upstream model availability may change.',
+ 'Timing and memory measurements describe these VMs, not physical laptop power-on time.']
+ validation = {'status': 'passed', 'image_run': image['html_url'], 'machine_run': run['html_url'],
+ 'machines': receipts, 'examples': examples, 'limitations': limitations}
+ (folder / 'validation.json').write_text(json.dumps(validation, indent=2) + '\n')
+ manifest['validation'] = {'status': 'passed', 'receipt': 'validation.json', 'machine_run': run['html_url'], 'limitations': limitations}
+ (folder / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
+ guide = (Path(__file__).resolve().parents[1] / 'INSTALL.md').read_text()
+ validate_install_guide(manifest, guide)
+ (folder / 'INSTALL.md').write_text(guide)
+ with zipfile.ZipFile(folder / 'machine-evidence.zip', 'w', compression=zipfile.ZIP_DEFLATED) as archive:
+ for directory in ['machines', 'dsh-machines']:
+ for path in sorted((root / directory).rglob('*')):
+ include = path.suffix in {'.png', '.json', '.txt', '.jsonl'} or path.name.endswith('-boot-journal.log')
+ if path.is_file() and include and 'Projects' not in path.relative_to(root / directory).parts:
+ archive.write(path, path.relative_to(root))
+ if examples:
+ with zipfile.ZipFile(folder / 'harness-examples.zip', 'w', compression=zipfile.ZIP_DEFLATED) as archive:
+ for directory, kind in [('machines', 'workloads'), ('dsh-machines', 'dsh')]:
+ if kind not in examples:
+ continue
+ for project_root in (root / directory).rglob('Projects'):
+ for path in sorted(project_root.rglob('*')):
+ if path.is_file() and not set(path.relative_to(project_root).parts) & {'node_modules', '.git', '.harness', '__pycache__'}:
+ archive.write(path, path.relative_to(project_root))
+ assets = sorted(p for p in folder.iterdir() if p.is_file())
+ identities = {p.name: {'sha256': digest(p), 'bytes': p.stat().st_size} for p in assets}
+ tag = 'os-v' + version
+ notes = root / 'release-notes.md'
+ interactive_install = all(any(c.startswith('Keyboard disk selection, encryption checkbox') for c in r['checks']) for r in receipts)
+ update_retry = all(any(c.startswith('Failed full update blocks package changes') for c in r['checks']) for r in receipts)
+ project_source_runs = sorted({str(r['workload_project_source_run_id']) for r in receipts if r.get('workload_project_source_run_id')})
+ reuse_note = ('Completed project sources were retained from ' + ', '.join(
+ f'[run {source}](https://github.com/{args.repo}/actions/runs/{source})' for source in project_source_runs) +
+ '. The game agent ran again; all four projects\' unit tests and independent acceptance checks reran on this exact image.') if project_source_runs else ''
+ notes.write_text(f'''Boot directly into hn. Open agents with Ctrl+B, then N. Super+B opens Chromium or returns to hn.
+
+Arch Linux with the LTS kernel, labwc, foot, and an on-demand browser. No desktop panels or preinstalled development stacks.
+
+To try it: follow the included `INSTALL.md` for Mac → USB → ThinkPad instructions. Verify the ISO's SHA-256, write the whole ISO to a USB stick, and boot an x86-64 PC with Secure Boot disabled. On the USB welcome screen, press Enter to install or T to try Harness. Try opens Wi-Fi setup when needed, then bundled OpenCode with its upstream default settings. Ctrl+B then T opens a terminal directly; Ctrl+B then I opens the installer from a live session. This preview's installer erases the entire selected disk; it does not resize another OS. Encryption is enabled by default.
+
+{'The installer has four aligned fields: disk, encryption, password, repeat password. Disk choices fit on one line. Activate Install to begin; there is no second confirmation screen or minimum password length. Empty passwords are rejected. The account is me@harness. The password initially protects both the local account and, when enabled, the encrypted disk. There is no first-boot account wizard.' if interactive_install else ''}
+
+{'Interrupted full OS updates now block ordinary package transactions until a full retry succeeds. Retrying keeps the original recovery checkpoint. This was exercised with a real failed repository refresh, blocked package upgrade, successful retry, and offline recovery. The bundled Harness runtime remains pinned to this preview; hn-os update updates Arch packages.' if update_retry else ''}
+
+BIOS/plain and UEFI/encrypted VM boot, clipboard, browser switching, offline installation and package-checkpoint recovery passed. The BIOS VM uses a Nehalem CPU profile without AVX2, starts bundled OpenCode, installs the other agent executables, installs a compiler on demand, builds C, and serves a local Node preview. See `validation.json` and `machine-evidence.zip` for the exact checks and measurements.
+
+{'Real free OpenCode agents built a Python CLI, a conference website, a keyboard game and a Fastify/SQLite application. Their unit tests and independent browser/API checks passed. The retained projects are in `harness-examples.zip`, separate from the minimal ISO.' if 'workloads' in examples else ''}
+
+{reuse_note}
+
+{'Three DSHs also passed: a live HTML greeting, a terminal CSV tool, and a game using the existing shared viewers, including keyboard play, pause and standalone export.' if 'dsh' in examples else ''}
+
+{chr(10).join('- ' + item for item in limitations)}
+
+Source: `{manifest['source_commit']}`. [Machine validation]({run['html_url']}).
+''')
+ if args.prepare_only:
+ print(json.dumps({'status': 'prepared', 'tag': tag, 'repository': args.repo,
+ 'notes': str(notes), 'files': identities}, indent=2))
+ return
+ subprocess.run(['gh', 'release', 'create', tag, '--repo', args.repo, '--target', manifest['source_commit'],
+ '--draft', '--prerelease', '--title', 'Harness ' + version, '--notes-file', str(notes),
+ *map(str, assets)], check=True, timeout=900)
+ try:
+ subprocess.run(['gh', 'release', 'edit', tag, '--repo', args.repo, '--draft=false'], check=True, timeout=120)
+ release = json.loads(gh('api', f'repos/{args.repo}/releases/tags/{tag}'))
+ def verify(asset):
+ expected = identities[asset['name']]
+ with tempfile.TemporaryDirectory(prefix='hn-release-check-') as temp:
+ downloaded = Path(temp) / asset['name']
+ subprocess.run(['curl', '--fail', '--location', '--retry', '2', '--max-time', '600', '--silent', '--show-error',
+ asset['browser_download_url'], '--output', str(downloaded)], check=True, timeout=650)
+ if downloaded.stat().st_size != expected['bytes'] or digest(downloaded) != expected['sha256']:
+ raise ValueError('Public asset checksum mismatch: ' + asset['name'])
+ return asset['name']
+ if {a['name'] for a in release['assets']} != set(identities):
+ raise ValueError('Published asset set differs from the verified build.')
+ with ThreadPoolExecutor(max_workers=3) as pool:
+ checked = list(pool.map(verify, release['assets']))
+ receipt = {'status': 'passed', 'release_url': release['html_url'], 'source_commit': manifest['source_commit'],
+ 'finished_at_unix': time.time(), 'verified_public_assets': checked, 'files': identities}
+ (root / 'publication.json').write_text(json.dumps(receipt, indent=2) + '\n')
+ print(release['html_url'])
+ except BaseException:
+ subprocess.run(['gh', 'release', 'edit', tag, '--repo', args.repo, '--draft=true'], check=True, timeout=120)
+ raise
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tools/run-vm.py b/os/tools/run-vm.py
new file mode 100644
index 000000000..9126f074d
--- /dev/null
+++ b/os/tools/run-vm.py
@@ -0,0 +1,183 @@
+#!/usr/bin/env python3
+"""Try the real installer and installed OS in a persistent, isolated QEMU window."""
+import argparse
+import fcntl
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import shlex
+import shutil
+import subprocess
+import tempfile
+
+
+def arguments(argv=None):
+ root = Path(__file__).resolve().parents[1]
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--iso', type=Path, help='ISO with its manifest.json beside it')
+ parser.add_argument('--installed', action='store_true', help='Boot the virtual disk without the ISO')
+ parser.add_argument('--directory', type=Path, default=root / 'work' / 'interactive-vm')
+ parser.add_argument('--memory', type=int, default=2048, help='Guest RAM in MiB')
+ parser.add_argument('--firmware', choices=['uefi', 'bios'], default='uefi')
+ parser.add_argument('--headless', action='store_true', help='Use QMP/serial sockets without opening a window')
+ parser.add_argument('--vnc-port', type=int, help='Serve the VM display on localhost TCP port 5900–65535; implies headless')
+ parser.add_argument('--ssh-port', type=int, help='Forward localhost TCP port 1024–65535 to guest SSH; does not enable sshd')
+ parser.add_argument('--remote-host', help='Print an SSH tunnel command for this server (user@host or an SSH config alias)')
+ parser.add_argument('--require-acceleration', action='store_true', help='Stop instead of falling back to software emulation')
+ args = parser.parse_args(argv)
+ if args.memory < 1024:
+ parser.error('Use at least 1024 MiB for this development image.')
+ if args.vnc_port is not None and not 5900 <= args.vnc_port <= 65535:
+ parser.error('--vnc-port must be between 5900 and 65535.')
+ if args.ssh_port is not None and not 1024 <= args.ssh_port <= 65535:
+ parser.error('--ssh-port must be between 1024 and 65535.')
+ if args.vnc_port is not None and args.vnc_port == args.ssh_port:
+ parser.error('Use different display and guest SSH ports.')
+ if args.remote_host:
+ if not re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_.@:-]*', args.remote_host):
+ parser.error('--remote-host must be a user@host or SSH config alias.')
+ if args.vnc_port is None and args.ssh_port is None:
+ parser.error('--remote-host needs --vnc-port or --ssh-port.')
+ return parser, args
+
+
+def acceleration():
+ mac = platform.system() == 'Darwin'
+ native_x86 = platform.machine().lower() in ['x86_64', 'amd64']
+ return 'hvf' if mac and native_x86 else 'kvm' if native_x86 and os.access('/dev/kvm', os.R_OK | os.W_OK) else 'tcg'
+
+
+def remote_options(args):
+ network = 'user,id=net'
+ if args.ssh_port is not None:
+ network += f',hostfwd=tcp:127.0.0.1:{args.ssh_port}-:22'
+ options = ['-netdev', network]
+ if args.vnc_port is not None:
+ options += ['-vnc', f'127.0.0.1:{args.vnc_port - 5900}']
+ return options
+
+
+def connection_help(args):
+ lines = []
+ if args.remote_host:
+ tunnel = ['ssh', '-N', '-o', 'ExitOnForwardFailure=yes']
+ for port in [args.vnc_port, args.ssh_port]:
+ if port is not None:
+ tunnel += ['-L', f'127.0.0.1:{port}:127.0.0.1:{port}']
+ tunnel += [args.remote_host]
+ lines += ['On your Mac, keep this tunnel running:', shlex.join(tunnel)]
+ if args.vnc_port is not None:
+ lines += [f'Display: vnc://127.0.0.1:{args.vnc_port}',
+ f'On macOS: open vnc://127.0.0.1:{args.vnc_port}']
+ if args.ssh_port is not None:
+ lines += [f'Guest SSH: ssh -p {args.ssh_port} [email protected]',
+ 'Guest SSH requires sshd and your login/key setup inside the VM.']
+ return lines
+
+
+def main(argv=None):
+ root = Path(__file__).resolve().parents[1]
+ parser, args = arguments(argv)
+ qemu = shutil.which('qemu-system-x86_64')
+ image_tool = shutil.which('qemu-img')
+ if not qemu or not image_tool:
+ parser.error('Install QEMU first: brew install qemu (macOS), or qemu-system-x86 and qemu-utils (Debian/Ubuntu).')
+ accel = acceleration()
+ if args.require_acceleration and accel == 'tcg':
+ parser.error('Hardware acceleration is unavailable. Use an x86 Linux host with /dev/kvm access or an Intel Mac. This x86 image requires software emulation on Apple Silicon.')
+ iso = None
+ if not args.installed:
+ candidates = list((root / 'dist').glob('*.iso'))
+ iso = (args.iso or (candidates[0] if len(candidates) == 1 else Path('missing.iso'))).resolve()
+ if not iso.is_file():
+ parser.error('Provide --iso PATH, or put one ISO and its manifest in os/dist/.')
+ manifest = json.loads((iso.parent / 'manifest.json').read_text())
+ with iso.open('rb') as handle:
+ digest = hashlib.file_digest(handle, 'sha256').hexdigest()
+ if iso.stat().st_size != manifest['iso']['bytes'] or digest != manifest['iso']['sha256']:
+ parser.error('ISO does not match its manifest.')
+ folder = args.directory.resolve()
+ folder.mkdir(parents=True, exist_ok=True)
+ # Keep one QEMU process per virtual disk. Never accept a host block device.
+ lock = (folder / 'vm.lock').open('w')
+ try:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ parser.error('This VM is already running.')
+ disk = folder / 'disk.qcow2'
+ if disk.is_symlink() or (disk.exists() and not disk.is_file()):
+ parser.error('The virtual disk must be a regular file, not a symlink or device.')
+ if not disk.exists():
+ if args.installed:
+ parser.error('Install to the VM disk from the ISO first.')
+ if shutil.disk_usage(folder).free < 6 * 1024 ** 3:
+ parser.error('Keep at least 6 GiB free before creating an installation VM.')
+ subprocess.run([image_tool, 'create', '-f', 'qcow2', str(disk), '24G'], check=True)
+ info = json.loads(subprocess.check_output([image_tool, 'info', '--output=json', str(disk)], text=True))
+ if info['format'] != 'qcow2' or info.get('backing-filename'):
+ parser.error('Expected a standalone qcow2 disk without a backing file.')
+ mac = platform.system() == 'Darwin'
+ display = 'none' if args.headless or args.vnc_port is not None else 'cocoa,left-command-key=on' if mac else 'gtk'
+ # QEMU key/value arguments escape literal commas by doubling them.
+ path_arg = lambda path: str(path).replace(',', ',,')
+ with tempfile.TemporaryDirectory(prefix='hn-os-', dir='/tmp') as control:
+ control = Path(control)
+ command = [qemu, '-name', 'Harness', '-accel', accel,
+ '-cpu', 'max' if accel == 'tcg' else 'host', '-m', str(args.memory), '-smp', '2',
+ '-device', 'virtio-vga', '-display', display,
+ '-drive', f'file={path_arg(disk)},format=qcow2,if=none,id=target',
+ '-device', f'virtio-blk-pci,drive=target,serial=HN_OS_VM,bootindex={1 if args.installed else 2}',
+ '-device', 'virtio-net-pci,netdev=net', *remote_options(args),
+ '-serial', f'unix:{control / "serial.sock"},server=on,wait=off',
+ '-qmp', f'unix:{control / "qmp.sock"},server=on,wait=off']
+ if iso:
+ command += ['-drive', f'file={path_arg(iso)},format=raw,media=cdrom,if=none,id=live',
+ '-device', 'ide-cd,drive=live,bootindex=1']
+ if args.firmware == 'uefi':
+ share = Path(qemu).resolve().parents[1] / 'share' / 'qemu'
+ options = [(share / 'edk2-x86_64-code.fd', share / 'edk2-i386-vars.fd'),
+ (Path('/usr/share/OVMF/OVMF_CODE_4M.fd'), Path('/usr/share/OVMF/OVMF_VARS_4M.fd'))]
+ firmware = next(((code, template) for code, template in options if code.is_file() and template.is_file()), None)
+ if not firmware:
+ parser.error('UEFI firmware not found. Install OVMF, or use --firmware bios.')
+ code, template = firmware
+ variables = folder / 'uefi-vars.fd'
+ if not variables.exists():
+ shutil.copyfile(template, variables)
+ command += ['-drive', f'if=pflash,format=raw,readonly=on,file={path_arg(code)}',
+ '-drive', f'if=pflash,format=raw,file={path_arg(variables)}']
+ state = {'disk': str(disk), 'iso': str(iso) if iso else None, 'acceleration': accel,
+ 'serial_socket': str(control / 'serial.sock'), 'qmp_socket': str(control / 'qmp.sock'),
+ 'vnc_address': f'127.0.0.1:{args.vnc_port}' if args.vnc_port is not None else None,
+ 'guest_ssh_address': f'127.0.0.1:{args.ssh_port}' if args.ssh_port is not None else None}
+ (folder / 'running.json').write_text(json.dumps(state, indent=2) + '\n')
+ print(f'Virtual disk: {disk} ({info["virtual-size"] / 1024 ** 3:g} GiB capacity; grows only as used)', flush=True)
+ print(f'Guest: {args.memory} MiB RAM, 2 CPUs, {accel}; control: {control}', flush=True)
+ if not args.installed:
+ print('Press Enter on the Harness welcome screen to install (choose /dev/vda), or T to try it.', flush=True)
+ reboot = ['python3', 'os/tools/run-vm.py', '--installed', '--directory', str(folder),
+ '--firmware', args.firmware, '--memory', str(args.memory)]
+ for flag, value in [('--vnc-port', args.vnc_port), ('--ssh-port', args.ssh_port), ('--remote-host', args.remote_host)]:
+ if value is not None:
+ reboot += [flag, str(value)]
+ if args.headless:
+ reboot += ['--headless']
+ if args.require_acceleration:
+ reboot += ['--require-acceleration']
+ print('After shutdown: ' + shlex.join(reboot), flush=True)
+ for line in connection_help(args):
+ print(line, flush=True)
+ try:
+ with (folder / 'qemu.log').open('ab') as log:
+ result = subprocess.run(command, stderr=log)
+ if result.returncode:
+ raise SystemExit(f'QEMU exited with {result.returncode}; see {folder / "qemu.log"}')
+ finally:
+ (folder / 'running.json').unlink(missing_ok=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/store/README.md b/store/README.md
index e71af79bc..26e4a6b89 100644
--- a/store/README.md
+++ b/store/README.md
@@ -19,7 +19,7 @@ store/
```
Both a reusable Store package and its running sessions are called **harnesses**.
-A **swarm** groups running harnesses. See [product terminology](../docs/terminology.md).
+A **tab** groups running harnesses. See the [Naming System](../docs/naming-system.md).
In code and on the wire a package is still a **DSH**, a domain-specific harness: `harness dsh …`,
`dsh_list`, `cli/src/dsh/`. Those names are the CLI's public contract and stay.
diff --git a/tui/README.md b/tui/README.md
index 5a403c634..6de04267d 100644
--- a/tui/README.md
+++ b/tui/README.md
@@ -26,6 +26,11 @@ hn follows tmux 3.5a's keys, commands, formats and `~/.tmux.conf`, with your har
every machine behind them. What tmux users have asked for over the years, and what hn does
about it: [docs/tmux-improved.md](docs/tmux-improved.md).
+The [Harness OS image](../os/README.md) uses the same hn binary with an explicit OS session
+mode. Its live USB offers Install and Try; an installed OS offers agents, terminals and Wi-Fi.
+These screens and installation shortcuts are absent from ordinary hn on macOS and other Linux
+systems. Installing or updating hn alone does not turn a computer into Harness OS.
+
![Three harnesses on two machines, side by side](docs/panes.png)
![C-b s: every harness on every machine, the one waiting on you nearest the prompt](docs/launcher.png)
diff --git a/tui/src/app.rs b/tui/src/app.rs
index c8389f32a..0d74fffdd 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -667,6 +667,11 @@ pub struct App {
/// No terminal (--headless): tmux's server with no client attached, holding sessions for
/// the commands of a script until a client takes them.
pub headless: bool,
+ /// The OS's primary screen: keep a home screen when empty and refuse client detach/suspend.
+ /// This controls the interface, not the user's ability to administer their machine.
+ pub os_session: bool,
+ /// A disposable USB session offers direct try, install and network actions on its home.
+ pub os_live: bool,
/// While a command runs in another session (`-t work:2`): the session to come back to.
pub swap_back: Option<u32>,
/// The session asked for at start (`hn new -A -s main`, `hn attach -t work`).
@@ -872,6 +877,8 @@ impl App {
handed_over: false,
sessions_sig: String::new(),
headless: false,
+ os_session: std::env::var("HARNESS_OS").as_deref() == Ok("1"),
+ os_live: std::env::var("HARNESS_OS").as_deref() == Ok("1") && std::env::var("HARNESS_OS_LIVE").as_deref() == Ok("1"),
wait_channels: HashMap::new(),
cli_held: std::collections::VecDeque::new(),
last_cli: Instant::now(),
@@ -3491,7 +3498,7 @@ impl App {
return;
}
// (hn with no terminal is tmux's server, not a client: it keeps the sessions it has.)
- let how = if self.headless { "off".to_string() } else { self.options.get("detach-on-destroy", "", None).unwrap_or_default() };
+ let how = if self.headless || self.os_session { "off".to_string() } else { self.options.get("detach-on-destroy", "", None).unwrap_or_default() };
let others: Vec<u32> = self.sessions.iter().map(|s| s.id).collect();
let next = match how.as_str() {
"off" | "no-detached" => self.last_session.filter(|l| others.contains(l)).or_else(|| self.sessions.iter().max_by_key(|s| s.created).map(|s| s.id)),
@@ -3506,8 +3513,12 @@ impl App {
self.last_session = None;
if !desk { self.sessions.retain(|s| s.id != gone) }
}
- // hn with no terminal (tmux's server) and exit-empty off: it stays, with no session.
- None if self.headless && !desk && self.options.get("exit-empty", "", None).as_deref() == Some("off") => {
+ None if self.os_session && desk => {
+ self.tabs = vec![Tab::home()];
+ self.active = 0;
+ }
+ // The OS surface stays on home, as does a headless server with exit-empty off.
+ None if !desk && (self.os_session || (self.headless && self.options.get("exit-empty", "", None).as_deref() == Some("off"))) => {
self.session_id = UNNUMBERED;
self.session_alias = None;
self.tabs = vec![Tab::home()];
@@ -5271,6 +5282,9 @@ impl App {
if self.shell_asked || !self.desk_answered || self.capture.is_some() { return }
// A headless client makes only the sessions it is asked for.
if self.headless { self.shell_asked = true; return }
+ // The OS opens on the agent launcher. An explicit `hn new ...` still gets
+ // its requested shell; reconnecting to existing work is handled by the desk.
+ if self.os_session && self.start_session.is_none() { self.shell_asked = true; return }
// `hn new -s work` (a session besides the desk's): made here, with its shell.
if self.start_session.as_ref().map(|s| s.create && self.session_alias.as_deref() != s.name.as_deref()).unwrap_or(false) {
if self.link(&self.fleet.local_id).is_none() { return }
@@ -6019,6 +6033,51 @@ mod scroll_settle_tests {
mod recovery_tests {
use super::*;
+ #[tokio::test]
+ async fn os_starts_at_the_agent_launcher_without_creating_an_unused_shell() {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (80, 24));
+ app.handed_over = true;
+ app.os_session = true;
+ app.desk_answered = true;
+ app.maybe_start_shell();
+ assert!(app.shell_asked);
+ assert!(app.starting_shell.is_none());
+ assert!(app.tabs.iter().all(|tab| tab.root.is_none()));
+ assert!(!app.quit);
+ }
+
+ #[tokio::test]
+ async fn os_surface_stays_home_after_its_last_session_closes() {
+ for desk in [false, true] {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (80, 24));
+ app.handed_over = true; // This state fixture must not persist a session.
+ app.os_session = true;
+ app.session_desk = desk;
+ app.tabs.clear();
+ app.session_gone_quiet();
+ assert!(!app.quit);
+ assert!(!app.exited);
+ assert_eq!(app.tabs.len(), 1);
+ assert!(app.tabs[0].root.is_none());
+ assert_eq!(app.active, 0);
+ }
+ }
+
+ #[tokio::test]
+ async fn ordinary_client_still_exits_after_its_last_session_closes() {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (80, 24));
+ app.handed_over = true;
+ app.os_session = false;
+ app.session_desk = false;
+ app.tabs.clear();
+ app.session_gone_quiet();
+ assert!(app.quit);
+ assert!(app.exited);
+ }
+
#[tokio::test]
async fn respawn_reply_and_fast_exit_deliver_one_death_hook_in_either_order() {
for exit_before_reply in [false, true] {
diff --git a/tui/src/commands.rs b/tui/src/commands.rs
index 4fb716af1..fc2e0c998 100644
--- a/tui/src/commands.rs
+++ b/tui/src/commands.rs
@@ -1808,6 +1808,9 @@ fn run_words_in(app: &mut App, words: &[String]) {
_ => &Words::plain(list),
};
let command = resolve(&words[0]);
+ if app.os_session && !app.headless && matches!(command, "detach-client" | "suspend-client") {
+ return app.error("hn is the OS session; open a Terminal with C-b N")
+ }
// A client's own command where no terminal is attached: tmux's cmd_find_client finds none.
let client_only = matches!(command, "switch-client" | "detach-client" | "refresh-client" | "suspend-client" | "lock-client" | "display-panes" | "command-prompt" | "confirm-before" | "display-menu" | "display-popup");
if app.headless && client_only && !(command == "detach-client" && opt(words, "-s").is_some()) { return app.error("no current client") }
@@ -3620,6 +3623,35 @@ fn run_words_in(app: &mut App, words: &[String]) {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn os_session_refuses_detach_and_suspend_including_aliases() {
+ for command in ["detach-client", "detach", "detach -E sh", "suspend-client", "suspendc", "quit"] {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (80, 24));
+ app.os_session = true;
+ app.handed_over = true;
+ execute(&mut app, command);
+ assert!(!app.quit, "{command}");
+ assert!(!app.suspend, "{command}");
+ assert!(app.exec_after.is_none(), "{command}");
+ assert_eq!(app.errors, 1, "{command}");
+ }
+ }
+
+ #[tokio::test]
+ async fn ordinary_client_can_still_detach_and_suspend() {
+ for command in ["detach", "suspendc"] {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (80, 24));
+ app.os_session = false;
+ app.handed_over = true;
+ execute(&mut app, command);
+ assert_eq!(app.quit, command == "detach");
+ assert_eq!(app.suspend, command == "suspendc");
+ assert_eq!(app.errors, 0);
+ }
+ }
+
#[test]
fn splits_like_tmux() {
assert_eq!(split("split-window -h"), vec![vec!["split-window", "-h"]]);
diff --git a/tui/src/input.rs b/tui/src/input.rs
index 0d01fb3ca..b5cedb827 100644
--- a/tui/src/input.rs
+++ b/tui/src/input.rs
@@ -524,8 +524,33 @@ pub fn resume_external_as(app: &mut App, x: &crate::app::External, placement: Pl
});
}
+/// The OS opts in through its session launcher. Ordinary hn on macOS or any
+/// other Linux keeps its normal home, even with a stray live-session flag.
+pub fn os_home(app: &App) -> bool {
+ app.os_session && (app.os_live || home_rows(app).is_empty())
+}
+
+fn os_home_command(app: &App, key: KeyEvent) -> Option<Option<&'static str>> {
+ if !os_home(app) || key.modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER) { return None }
+ match key.code {
+ KeyCode::Enter if app.os_live => Some(Some("sudo /usr/bin/harness install")),
+ KeyCode::Char('i' | 'I') if app.os_live => Some(Some("sudo /usr/bin/harness install")),
+ KeyCode::Enter => Some(Some("/usr/bin/hn-os try")),
+ KeyCode::Char('t' | 'T') if app.os_live => Some(Some("/usr/bin/hn-os try")),
+ KeyCode::Char('w' | 'W') => Some(Some("/usr/bin/hn-os wifi")),
+ KeyCode::Char('t' | 'T') => Some(None),
+ _ => None,
+ }
+}
+
/// A window with no harness in it has no pane to take keys from, so plain letters work here.
fn home_key(app: &mut App, key: KeyEvent) {
+ if os_home(app) {
+ if let Some(command) = os_home_command(app, key) {
+ new_shell_from(app, None, Placement::Auto(None), None, command.map(str::to_string));
+ }
+ return;
+ }
let rows = home_rows(app);
let open = |app: &mut App, index: usize| {
match rows.get(index).cloned() {
@@ -870,8 +895,8 @@ pub fn run(app: &mut App, command: &str) {
"store" => launch(app, "*", Filter::All),
"new" => crate::new_harness::open(app, None, None),
"terminal" => {
- let machine = focused_agent(app).map(|(m, _)| m).unwrap_or(app.fleet.local_id.clone());
- create(app, machine, What { engine: "terminal".into(), dsh: None, label: "Terminal".into() }, None, None);
+ let focused = focused_agent(app);
+ new_shell_from(app, focused, Placement::Auto(None), None, None);
}
"send" => prompt(app, PromptKind::Send, "Send to harness", "What should be done?", "Harness picks the harness that fits best; you confirm.", "", false),
"broadcast" => {
@@ -965,6 +990,7 @@ pub fn run(app: &mut App, command: &str) {
"messages" => picker(app, PickerKind::Messages, "messages", ""),
"keys" => picker(app, PickerKind::Keys, "keys", ""),
"choose-buffer" => picker(app, PickerKind::Buffers, "buffers", ""),
+ "quit" if app.os_session => app.error("hn is the OS session; open a Terminal with C-b N"),
"quit" => app.quit = true,
c if c.starts_with("tab-") => { if let Some(n) = c[4..].parse::<usize>().ok().and_then(|n| n.checked_sub(1)) { app.select_tab(n) } }
// ── machines & devices ──
@@ -3247,6 +3273,37 @@ pub fn menu_mouse(app: &mut App, m: &crate::mouse::Event) {
mod tests {
use super::*;
+ #[test]
+ fn os_actions_are_unavailable_in_ordinary_hn_and_install_is_live_only() {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (80, 24));
+ app.handed_over = true;
+ let key = |code| KeyEvent::new(code, KeyModifiers::NONE);
+ app.os_session = false;
+ for live in [false, true] {
+ app.os_live = live;
+ assert!(!os_home(&app));
+ for code in [KeyCode::Enter, KeyCode::Char('i'), KeyCode::Char('I'), KeyCode::Char('t'), KeyCode::Char('T'), KeyCode::Char('w'), KeyCode::Char('W')] {
+ assert_eq!(os_home_command(&app, key(code)), None);
+ }
+ }
+ app.os_session = true;
+ app.os_live = false;
+ assert_eq!(os_home_command(&app, key(KeyCode::Enter)), Some(Some("/usr/bin/hn-os try")));
+ assert_eq!(os_home_command(&app, key(KeyCode::Char('T'))), Some(None));
+ for code in [KeyCode::Char('i'), KeyCode::Char('I')] {
+ assert_eq!(os_home_command(&app, key(code)), None);
+ }
+ app.os_live = true;
+ for code in [KeyCode::Enter, KeyCode::Char('i'), KeyCode::Char('I')] {
+ assert_eq!(os_home_command(&app, key(code)), Some(Some("sudo /usr/bin/harness install")));
+ }
+ assert_eq!(os_home_command(&app, key(KeyCode::Char('T'))), Some(Some("/usr/bin/hn-os try")));
+ for modifiers in [KeyModifiers::CONTROL, KeyModifiers::ALT, KeyModifiers::SUPER] {
+ assert_eq!(os_home_command(&app, KeyEvent::new(KeyCode::Enter, modifiers)), None);
+ }
+ }
+
#[tokio::test]
async fn created_harness_stays_in_the_current_window() {
for existing in 0..=2 {
diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rs
index ee14f021e..44b7a6d3f 100644
--- a/tui/src/new_harness.rs
+++ b/tui/src/new_harness.rs
@@ -1201,6 +1201,26 @@ fn back(app: &mut App, form: &mut Form) -> bool {
false
}
}
+fn terminal_selected(form: &Form) -> bool {
+ form.child_active && form.child.as_ref().is_some_and(|child|
+ child.kind == Choice::Agent && child.picker.current_id().as_deref() == Some("engine:terminal"))
+}
+
+fn open_terminal(app: &mut App, mut form: Box<Form>) {
+ let machine = form.draft.machine.clone();
+ let cwd = match &form.draft.project {
+ Project::Folder(path) if !path.is_empty() => Some(path.clone()),
+ _ => (!form.home.is_empty()).then(|| form.home.clone()),
+ };
+ // Terminal is an immediate action. Keep the agent draft (including its task)
+ // for when New Harness is reopened; never send that task to a shell.
+ form.child = None;
+ form.child_active = false;
+ form.trail.clear();
+ app.new_harness_draft = Some(form);
+ crate::input::new_shell_from(app, Some((machine, String::new())), crate::app::Placement::Auto(None), cwd, None);
+}
+
pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
if key.code == KeyCode::Esc || (ctrl && matches!(key.code, KeyCode::Char('c' | 'g'))) {
@@ -1223,6 +1243,10 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
}
return;
}
+ if key.code == KeyCode::Enter && terminal_selected(&form) {
+ open_terminal(app, form);
+ return;
+ }
let mut launch = false;
let task_width = form.child_area.width.saturating_sub(6).max(1) as usize;
if form.child_active {
@@ -1427,6 +1451,10 @@ pub fn mouse(app: &mut App, mouse: MouseEvent) {
task::click(&mut c.picker, form.child_area, pos);
} else if let Some((_, index)) = c.picker.row_at.iter().find(|(y, _)| *y == mouse.row) {
c.picker.cursor = *index;
+ if terminal_selected(&form) {
+ open_terminal(app, form);
+ return;
+ }
choose(app, &mut form);
}
} else if let Some((_, field)) = form.hits.iter().find(|(r, _)| r.contains(pos)) {
diff --git a/tui/src/ui.rs b/tui/src/ui.rs
index 75a3acbca..041fa1022 100644
--- a/tui/src/ui.rs
+++ b/tui/src/ui.rs
@@ -584,6 +584,7 @@ fn box_style(app: &App, id: u64) -> Style {
const WORDMARK: [&str; 2] = ["█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀", "█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█"];
fn empty_window(buf: &mut Buffer, app: &App, area: Rect) {
+ if crate::input::os_home(app) { os_welcome(buf, app, area); return }
let rows = home_rows(app);
let (_, theme_fg, _) = crate::theme::palette();
let width = area.width.min(84).saturating_sub(4);
@@ -657,7 +658,7 @@ fn empty_window(buf: &mut Buffer, app: &App, area: Rect) {
// Typing here is a shell's (as after tmux's C-b c); the rows by number, or the arrows and Enter;
// the rest on the prefix's keys, as everywhere.
let hint = |c: &str| app.keymap.hint(c).unwrap_or_default();
- let keys: Vec<(String, &str)> = vec![("1-9".into(), "open"), ("↑↓ enter".into(), "choose"), ("type".into(), "a shell here"), (hint("choose-tree -Zs"), "harnesses"), (hint("new-harness"), "new"), (hint("choose-tree -a"), "waiting"), (hint("choose-tree -m"), "machines")];
+ let keys: Vec<(String, &str)> = vec![("1-9".into(), "open"), ("↑↓ enter".into(), "choose"), ("type".into(), "a shell here"), (hint("new-terminal"), "new terminal"), (hint("choose-tree -Zs"), "harnesses"), (hint("new-harness"), "new agent"), (hint("choose-tree -a"), "waiting"), (hint("choose-tree -m"), "machines")];
let keys: Vec<(String, &str)> = keys.into_iter().filter(|(k, _)| !k.is_empty()).collect();
let mut row: Vec<Span> = Vec::new();
let mut row_w = 0;
@@ -671,7 +672,9 @@ fn empty_window(buf: &mut Buffer, app: &App, area: Rect) {
if !row.is_empty() { lines.push(Line::from(row)) }
lines.push(Line::raw(""));
let prefix = crate::keys::name(&app.keymap.prefix);
- lines.push(Line::from(vec![Span::styled(format!("{prefix} ?"), bold(theme::accent())), Span::styled(" every key ", fg(theme::SOFT)), Span::styled(format!("{prefix} d"), bold(theme::accent())), Span::styled(" detach — everything keeps running", fg(theme::SOFT))]));
+ let (key, description) = if app.os_session { ("Super+B".into(), " browser · Super+Enter terminal") }
+ else { (format!("{prefix} d"), " detach — everything keeps running") };
+ lines.push(Line::from(vec![Span::styled(format!("{prefix} ?"), bold(theme::accent())), Span::styled(" every key ", fg(theme::SOFT)), Span::styled(key, bold(theme::accent())), Span::styled(description, fg(theme::SOFT))]));
let top = area.y + area.height.saturating_sub(lines.len() as u16) / 2;
for (index, line) in lines.iter().enumerate() {
let y = top + index as u16;
@@ -683,6 +686,70 @@ fn empty_window(buf: &mut Buffer, app: &App, area: Rect) {
themed_home(buf, area);
}
+fn os_welcome(buf: &mut Buffer, app: &App, area: Rect) {
+ let mut lines = Vec::new();
+ if area.height >= 24 {
+ for word in WORDMARK { lines.push(Line::styled(word, fg(theme::accent()))) }
+ } else { lines.push(Line::styled("harness", bold(theme::accent()))) }
+ lines.push(Line::raw(""));
+ let centered = lines.len();
+ let actions = if app.os_live { vec![("Enter", "Install Harness"), ("T", "Try without installing")] }
+ else { vec![("Enter", "Start OpenCode"), ("T", "New terminal"), ("W", "Connect to Wi-Fi")] };
+ for (key, action) in actions {
+ lines.push(Line::from(vec![Span::styled(format!("{key:7}"), bold(theme::accent())), Span::styled(action, bold(theme::TEXT))]));
+ lines.push(Line::raw(""));
+ }
+ lines.push(Line::raw(""));
+ let prefix = crate::keys::name(&app.keymap.prefix);
+ lines.push(Line::styled(format!("{prefix} T terminal · {prefix} W Wi-Fi · Super+B browser"), fg(theme::MUTED)));
+ if app.os_live { lines.push(Line::styled(format!("Inside a session: {prefix} I install"), fg(theme::MUTED))) }
+ let width = area.width.saturating_sub(4).min(58);
+ let left = area.x + area.width.saturating_sub(width) / 2;
+ let top = area.y + area.height.saturating_sub(lines.len() as u16) / 2;
+ for (index, line) in lines.iter().enumerate() {
+ let y = top + index as u16;
+ if y >= area.y + area.height { break }
+ let x = if index < centered { area.x + area.width.saturating_sub(line.width() as u16) / 2 } else { left };
+ buf.set_line(x, y, line, area.width.saturating_sub(x - area.x));
+ }
+}
+
+#[cfg(test)]
+mod os_welcome_tests {
+ use super::*;
+
+ #[test]
+ fn ordinary_hn_installed_os_and_live_usb_have_separate_homes() {
+ for (width, height) in [(80, 24), (60, 18), (120, 40)] {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (width, height));
+ app.handed_over = true;
+ for (os, live) in [(false, false), (false, true), (true, false), (true, true)] {
+ app.os_session = os;
+ app.os_live = live;
+ let area = Rect::new(0, 0, width, height);
+ let mut buf = Buffer::empty(area);
+ empty_window(&mut buf, &app, area);
+ let text = (0..height).map(|y| (0..width).map(|x| buf[(x, y)].symbol()).collect::<String>()).collect::<Vec<_>>().join("\n");
+ if !os {
+ for action in ["Install Harness", "Try without installing", "Start OpenCode", "Wi-Fi", "Super+B"] {
+ assert!(!text.contains(action), "ordinary hn must not offer {action}: {text}");
+ }
+ assert!(text.contains("detach"), "{text}");
+ } else if live {
+ assert!(text.contains("Enter Install Harness"), "{text}");
+ assert!(text.contains("T Try without installing"), "{text}");
+ assert!(!text.contains("Nothing running"), "{text}");
+ } else {
+ assert!(text.contains("Start OpenCode"), "{text}");
+ assert!(text.contains("New terminal"), "{text}");
+ assert!(!text.contains("Install Harness"), "{text}");
+ }
+ }
+ }
+ }
+}
+
// ── a theme over the panes ──
fn rgb(c: [u8; 3]) -> Color { Color::Rgb(c[0], c[1], c[2]) }
diff --git a/tui/tests/e2e.sh b/tui/tests/e2e.sh
index c80733599..53fb626b8 100755
--- a/tui/tests/e2e.sh
+++ b/tui/tests/e2e.sh
@@ -158,7 +158,13 @@ tmux_ send-keys -t t C-b z
expect "C-b z zooms (Z flag)" "*Z"
tmux_ send-keys -t t C-b z
tmux_ send-keys -t t C-b I
-expect "C-b I: models for the focused harness" "Sonnet / High"
+# Models now shares the desktop's subscriptions/local/Grid picker. This pane is
+# a shell, so it lists available sources without offering an engine model switch.
+expect "C-b I opens the shared Models picker" "Subscriptions"
+expect "Models lists the connected Anthropic subscription" "Anthropic"
+expect "Models lists the connected OpenAI subscription" "OpenAI"
+expect "Models lists the available Grid model" "demo-model"
+expect "a shell must focus a harness before switching models" "Focus a harness"
tmux_ send-keys -t t Escape
tmux_ send-keys -t t C-b @
expect "C-b @: machines" "mock-remote"
diff --git a/tui/tests/new-harness.py b/tui/tests/new-harness.py
index 15d72b892..baa5e94bc 100644
--- a/tui/tests/new-harness.py
+++ b/tui/tests/new-harness.py
@@ -122,7 +122,8 @@ def field_position(label):
left, top, width, height = form_bounds(lines)
for y, line in enumerate(lines[top:top+height], top):
# Labels begin at the field column; "Harness" in the dialog title is not a field.
- m = re.match(r'^[ ›]{3}(' + re.escape(label) + r')(?= {2,}|$)', line[left:left+width])
+ # Like field_at, accept alternatives such as Agent|Harness.
+ m = re.match(r'^[ ›]{3}(' + label + r')(?= {2,}|$)', line[left:left+width])
if m: return left + m.start(1), y
def field(label):
wait(lambda: field_position(label), f'field {label}')
@@ -141,6 +142,18 @@ def placed_in_current_window(before):
assert placement() == (window, windows, panes + 1), 'New Harness must add a pane in the current window'
# Keep room for the next launch as this suite creates several harnesses in one window.
hn('select-layout', 'tiled')
+def end_new_terminal(previous_agents, previous_placement):
+ created = {a['id'] for a in state()['agents']} - previous_agents
+ assert len(created) == 1, created
+ agent = created.pop()
+ wait(lambda: any(s['agent'] == agent for c in state('reconnect')['connections'] for s in c['streams']), 'new terminal stream is open')
+ request = urllib.request.Request(f'http://127.0.0.1:{PORT}/test/reconnect',
+ data=json.dumps({'action': 'close', 'agent': agent, 'reason': 'process exited'}).encode(),
+ headers={'Content-Type': 'application/json'})
+ with urllib.request.urlopen(request, timeout=2) as response:
+ assert json.load(response)['data']['ok']
+ wait(lambda: placement() == previous_placement, 'exited terminal removes its pane')
+ assert 'The terminal closed' not in screen(), 'an ordinary shell must not leave an agent error card'
def submit(count):
# Git discovery is asynchronous. Wait for its answer before accepting the visible draft.
time.sleep(.15)
@@ -251,23 +264,35 @@ try:
print('PASS New Harness: machine-scoped profiles and explicit model routes', flush=True)
# Blender asks for its coding agent next in the same side chooser.
- new_form(); field('Agent'); type_text('Blender'); keys('Enter'); shows('Choose a coding agent'); type_text('codex'); keys('Enter'); shows('Blender · Codex')
+ new_form(); field('Agent|Harness'); type_text('Blender'); keys('Enter'); shows('Choose a coding agent'); type_text('codex'); keys('Enter'); shows('Blender · Codex')
submit(before + 6)
assert state()['created'][-1]['dsh'] == 'example/blender'
- new_form(); choose_field('Harness', 'Terminal')
- snapshot('new-harness-terminal')
- assert not re.search(field_at('Model|Approvals|Profile'), form_screen()), 'Terminal omits irrelevant settings\n' + screen()
- # Return focus to the action without accepting any of the disabled Git rows.
+ new_form()
before_terminal = placement()
- field('Start Terminal')
- wait(lambda: create_count() == before + 7 and not form_visible(), 'terminal launch')
+ previous_agents = {a['id'] for a in state()['agents']}
+ field('Harness'); type_text('Terminal'); keys('Enter')
+ wait(lambda: create_count() == before + 7 and not form_visible(), 'Terminal choice opens a shell immediately')
+ snapshot('new-harness-terminal')
placed_in_current_window(before_terminal)
request = state()['created'][-1]
assert request['engine'] == 'terminal' and request.get('permissionMode') is None, request
assert not any(k in request for k in ('dsh', 'prompt', 'gridModel', 'gitSource', 'codexHome')), request
+ end_new_terminal(previous_agents, before_terminal)
print('PASS New Harness: specialized harness compatibility and ordinary Terminal launch', flush=True)
- new_form(); field('Agent'); type_text('claude'); keys('Enter'); choose_field('Approvals', 'plan'); shows('Plan first')
+ # The keyboard shortcut owns the same shell lifecycle as the chooser.
+ # Its normal exit closes its view, rather than showing an agent error card.
+ previous_agents = {a['id'] for a in state()['agents']}
+ count = create_count()
+ keys('C-b', 'T')
+ wait(lambda: create_count() == count + 1 and not form_visible(), 'Ctrl+B T opens a terminal directly')
+ placed_in_current_window(before_terminal)
+ request = state()['created'][-1]
+ assert request['engine'] == 'terminal' and 'prompt' not in request and 'dsh' not in request, request
+ end_new_terminal(previous_agents, before_terminal)
+ print('PASS New terminal: chooser and Ctrl+B T both close their views on normal shell exit', flush=True)
+
+ new_form(); field('Agent|Harness'); type_text('claude'); keys('Enter'); choose_field('Approvals', 'plan'); shows('Plan first')
keys('Escape'); new_form(); shows('Plan first')
count = create_count()
for w, h in [(80, 24), (45, 14), (22, 5), (1, 1), (150, 42)] * 3:
@@ -296,10 +321,15 @@ try:
snapshot('new-harness-flat-task')
tmux('resize-window', '-t', 'test', '-x', '80', '-y', '24'); settle_ui()
snapshot('new-harness-flat-narrow')
- # Clearing the task allows an unsupported engine; it must never silently discard one.
- choose_field('Agent', 'Terminal'); field('Start Terminal'); shows('This agent cannot start with a task')
- assert create_count() == count, 'an unsupported task is rejected before creating a harness'
- field('Task'); keys('C-a', 'C-k', 'Enter'); choose_field('Agent', 'claude')
+ # A terminal starts immediately and leaves the agent draft intact. Never run
+ # the retained natural-language task as a shell command.
+ field('Agent|Harness'); type_text('Terminal'); keys('Enter')
+ wait(lambda: create_count() == count + 1 and not form_visible(), 'terminal launch with retained agent draft')
+ request = state()['created'][-1]
+ assert request['engine'] == 'terminal' and 'prompt' not in request and 'command' not in request, request
+ count += 1
+ new_form(); shows('Improve the New Harness keyboard flow.')
+ field('Task'); keys('C-a', 'C-k', 'Enter'); choose_field('Agent|Harness', 'claude')
field('Task'); type_text('x' * 2001); keys('Enter'); field('Start Claude Code'); shows('Task is too long')
assert create_count() == count, 'an overlong task is rejected before creating a harness'
field('Task'); keys('C-a', 'C-k', 'Enter')