diff --git a/bin/omarchy-mac-e2e-collect b/bin/omarchy-mac-e2e-collect new file mode 100755 index 000000000000..a8b990b06e08 --- /dev/null +++ b/bin/omarchy-mac-e2e-collect @@ -0,0 +1,47 @@ +#!/bin/bash +# omarchy:summary=Collect Mac compatibility results for community submissions +# +# Fetches the collector and its vendored helpers from the same ref into a +# cache directory, then executes it. The collector itself is network-free +# and redacts before writing; --submit is the only network call it makes, +# and only when you pass it. +# +# Usage (same flags as scripts/collect_e2e.py): +# bin/omarchy-mac-e2e-collect --interview --out e2e-mytest.tar.gz +# bin/omarchy-mac-e2e-collect --out e2e-mytest.tar.gz \ +# --submit https://mlx-omarchy-community-data.joshua-s-warren.workers.dev +# +# Pin a ref with OMARCHY_MAC_REF (default: quattro). Re-running refreshes +# nothing unless you pass --refresh. +set -euo pipefail + +REF="${OMARCHY_MAC_REF:-quattro}" +BASE="${OMARCHY_MAC_RAW_BASE:-https://raw.githubusercontent.com/omacom/omarchy-mac/$REF/scripts}" +CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/omarchy-mac-e2e/$REF" + +if [ "${1:-}" = "--refresh" ]; then + shift + rm -rf "$CACHE" +fi + +mkdir -p "$CACHE" +fetch() { curl -fsSL "$1/$2.py" -o "$CACHE/$2.py" 2>/dev/null; } +for f in collect_common collect_submit collect_quick collect_macos collect_e2e; do + if [ ! -s "$CACHE/$f.py" ] && ! fetch "$BASE" "$f"; then + if [ -z "${FALLBACK_BASE:-}" ]; then + # Pre-merge, quattro does not carry the collector yet; the PR branch + # does. Say which base served the file so provenance stays visible. + FALLBACK_BASE="https://raw.githubusercontent.com/joshuaswarren/omarchy-mac/e2e-collector/scripts" + echo "not on $BASE; using the PR branch until this merges:" >&2 + echo " $FALLBACK_BASE" >&2 + fi + fetch "$FALLBACK_BASE" "$f" || { + echo "Could not fetch $f.py from either base." >&2 + echo "Set OMARCHY_MAC_RAW_BASE to a tree that carries scripts/." >&2 + exit 1 + } + fi +done +chmod 700 "$CACHE" + +exec python3 "$CACHE/collect_e2e.py" "$@" diff --git a/docs/e2e-collector-sample-submission.md b/docs/e2e-collector-sample-submission.md new file mode 100644 index 000000000000..93b38d518c1d --- /dev/null +++ b/docs/e2e-collector-sample-submission.md @@ -0,0 +1,70 @@ +## Omarchy Mac E2E evidence archive + +Tester: UNRECORDED; Test ID: UNRECORDED; SoC: UNRECORDED; model identifier: UNRECORDED +Install path: UNRECORDED; Asahi image: UNRECORDED +root_encrypted: None; boot_separate: None; fresh_marker(setup conf present): False +Installed omarchy: not recorded +Device: unknown (unknown compatible); Vulkan: probe missing (vulkaninfo not installed; this is not a GPU or driver verdict) — driver package unverified +mlx-omarchy: not installed, default device unavailable +Pinned packages: not recorded +setup conf present: False; setup sudoers present: False +Install logs present: none (an absent log is not a hardware or install failure; see install-logs.json absence_notes — some logs are only written after certain stages, and the guided-setup log is never written to file at all) +Sections unavailable: none +Redaction applied before writing: {"home_path": 10, "hostname": 402, "username": 8} + +Attach this archive to the test ID / tracking issue with the completed checklist report (submission.md carries the pre-filled template). + + +## E2E report (auto-filled where marked [auto]) + +```text +Test ID: +Tester: +Date/timezone: +Mac model / Apple identifier / SoC / RAM: / / / +Machine [auto]: unknown; board unknown; SoC unknown; Debian GNU/Linux 12 (bookworm); kernel 6.17.2-1-pve; collected 2026-09-19T20:36:55Z +macOS version: +Asahi image and filesystem: +Encryption and keymap: / +Omarchy repo / ref / installed version: / +Test command: +root_encrypted [auto]: unknown +boot_separate [auto]: None +Boot-layout stage: UNRECORDED +Encryption stage: UNRECORDED +Omarchy install stage: UNRECORDED +First login: UNRECORDED +Second login: UNRECORDED +Normal reboot: UNRECORDED +Cold boot: UNRECORDED +Hardware smoke test: UNRECORDED +Security cleanup: cleanup_conf=False cleanup_sudoers=False (interview: UNRECORDED) +Hardware features (wiki matrix; ✓ works · ! limitation · ✕ broken · ? not known · n/a not built in): + internal display: UNRECORDED (?) + HDMI display: UNRECORDED (?) + USB-C DisplayPort display: UNRECORDED (?) + USB devices: UNRECORDED (?) + Thunderbolt dock: UNRECORDED (?) + Wi-Fi: UNRECORDED (?) + Bluetooth: UNRECORDED (?) + speakers: UNRECORDED (?) + headphones: UNRECORDED (?) + microphone: UNRECORDED (?) + HDMI audio: UNRECORDED (?) + suspend: UNRECORDED (?) + camera: UNRECORDED (?) + Touch ID: UNRECORDED (?) + keyboard: UNRECORDED (?) + trackpad: UNRECORDED (?) + GPU inference: UNRECORDED (?) + Neural Engine: UNRECORDED (?) +Overall: (PASS / FAIL / BLOCKED — volunteer decides) +First failing checkpoint: +Expected: +Actual: +Reproduction steps: +Warnings / skipped packages: +Logs, photos, or video: (see archive) +Related issue/PR: +Notes and clearly labelled hypotheses: +``` \ No newline at end of file diff --git a/docs/e2e-collector.md b/docs/e2e-collector.md new file mode 100644 index 000000000000..8eb0394f607d --- /dev/null +++ b/docs/e2e-collector.md @@ -0,0 +1,99 @@ +# E2E evidence collector (`scripts/collect_e2e.py`) + +Companion to `docs/omarchy-mac-e2e-volunteer-checklist.md`. The checklist +names what a volunteer must observe; the collector gathers everything a +machine can observe, redacts identity strings, and packs the result into a +reviewable archive a volunteer attaches to their test report. + +## Why + +The checklist's report template asks for machine details, stage-by-stage +results, logs, and security-cleanup evidence. Today volunteers gather all +of that by hand and the reports arrive inconsistent (the M1 iMac E2E run +showed what that costs). The mlx-omarchy project already solved this class +of problem with consent-gated, redacted, deterministic evidence collectors; +this brings the same machinery to the Mac installer checklist. + +## What it collects + +| Section | Checklist coverage | Method | +|---|---|---| +| `identity` | §1 test assignment | interactive prompts, reused from `./e2e-identity.json` (written back after an interactive run), plus machine-recorded identity: marketing model, board and SoC from devicetree compatible strings, kernel, OS, collection date. Identity only — never a feature verdict | +| `baseline` | §3 fresh-Asahi baseline | the exact documented commands, plus derived facts: LUKS present, `/boot` separate, freshness marker | +| `mlx` | — (bonus) | the mlx-omarchy quick capability report: host/devicetree, Mesa/Vulkan, ANE devicetree, installed distributions. A missing `vulkaninfo` records `probe: missing` — it never reads as an unsupported GPU | +| `hardware` | hardware matrix evidence | presence-only records for the wiki features: DRM connectors, audio cards, USB, Thunderbolt, wireless, Bluetooth, cameras, input devices, suspend states. Presence is never converted into "working" | +| `install-logs` | §4–5 | tails of the three documented logs (a missing log records *why* it can be absent — absence is data, never a hardware failure) plus `journalctl -u omarchy-mac-setup.service`, `omarchy-mac-setup --status`, service state | +| `boot` | §5–7 | `journalctl --list-boots`, current-boot warnings, failed system and user units, `/boot` tree | +| `install-state` | §6 | omarchy version/path, pinned packages, `pacman -Dk`, `omarchy-migrate --pending` (exit semantics recorded, never interpreted), `omarchy-done` checks, swap | +| `security` | §7 | setup conf/sudoers presence, passwordless-sudo probe, sshd exposure, nft ruleset, user journal warnings | +| `macos` | §2–3 | optional: pasted macOS-side output via `--from-macos FILE` | +| `interview` | §5–9 human items + wiki hardware matrix | `--interview` walks all 34 judgment checkboxes (PASS/FAIL/SKIP/NA) and 18 per-feature hardware answers (WORKS/LIMITATION/BROKEN/UNKNOWN/NA, one per Apple-Silicon-hardware.md matrix column, with the peripheral model and connection in the note). Persisted to `./e2e-answers.json` | + +Stage verdicts in the report roll up honestly: a stage answered entirely NA +renders `NA` (the stage does not exist on a `--no-encrypt` run, for example), +and a PASS+SKIP mix renders `PARTIAL` — never `SKIP`, which would claim the +stage went untested. + +Every external command is bounded (timeout, capped output); a missing tool +or absent log is recorded as data, never a crash; partial runs keep what +finished. Every captured value passes the shared redactor (usernames, +hostnames, home paths, IPs, MACs, serials, credential-shaped strings), and +the per-kind redaction counts ship in the manifest. + +## Volunteer flow + +Before this PR merges, fetch the wrapper from the PR branch: + +```bash +curl -fsSL https://raw.githubusercontent.com/joshuaswarren/omarchy-mac/e2e-collector/bin/omarchy-mac-e2e-collect -o e2e-collect +bash e2e-collect --interview --out e2e-.tar.gz +``` + +The wrapper tries `quattro` first, falls back to this branch when the collector is not merged yet, and prints which tree served the files. After merge the same two commands work unchanged. From a checkout, `python3 scripts/collect_e2e.py --interview --out e2e-.tar.gz` runs the same collector. + +That prints a preview manifest, then writes: + +- `e2e-.tar.gz` — deterministic archive (all section JSON, the + checklist itself, the pre-filled report template with the per-feature + hardware matrix) +- `e2e-.submission.md` — paste-ready cover: machine identity, + derived storage facts, redaction summary, and the checklist report + template auto-filled where the machine could answer + +Attach both to the test ID / tracking issue. Nothing is uploaded unless +`--submit URL` is passed (community-data worker protocol, kind +`omarchy-mac-e2e`; the live worker accepts this kind as of 2026-09-18 — +sample record: +https://mlx-omarchy-community-data.joshua-s-warren.workers.dev/v1/results/ef89a1c651ce3cb599be62dc7baa49f8bacb5e76e9e3a56d41b0fddd60627ff3). + +## Provenance + +The four helpers (`collect_common.py`, `collect_submit.py`, `collect_quick.py`, and `collect_macos.py`) originate from `joshuaswarren/mlx-omarchy`. Local changes keep the macOS helper self-contained and distinguish a missing Vulkan probe from an unavailable GPU. + +## Verification + +- `python3 tests/test-collect-e2e.py` — focused stdlib-only regression + checks: stage-verdict roll-ups (all-NA → NA, PASS+SKIP → PARTIAL), the + probe-missing Vulkan summary, log-absence wording, per-feature answer + separation (old combined-question PASS never transfers to a split + feature; hand-written `ANSWER; note` values load normalized), wiki + symbol rendering, and archive/submission preservation of feature + answers. +- A real terminal interview checks all 67 prompts, persists answers, and verifies that first-run identity and feature results reach the archive. Without `--interview`, collection never prompts. These checks run on Linux x86_64; they do not establish Apple hardware compatibility. +- `bun test` (worker side, mlx-omarchy): 67/67 unit, including the new + e2e-kind schema fixture and a smoke scenario; live worker deployed and + `check_schema_identity.py` green. +- Collector exercised end to end on a non-Apple x86_64 host: every + section records (unavailability is data), redaction counts present, + archive + submission built; live submit round-tripped through the + worker and is served at the sample URL above. + +## Notes for reviewers + +- The dashboard (community-data worker) now shows a Kind column so e2e + reports are distinguishable from mlx-omarchy quick/deep rows. +- `--submit` is opt-in per run; the default writes local files only. +- The e2e payload adds six nullable summary fields + (`test_id`, `install_path`, `asahi_image`, `encryption`, + `boot_separate`, `overall`) to the community-data schema; old + collectors are unaffected and the fields are optional. diff --git a/docs/omarchy-mac-e2e-volunteer-checklist.md b/docs/omarchy-mac-e2e-volunteer-checklist.md new file mode 100644 index 000000000000..f20ed865b718 --- /dev/null +++ b/docs/omarchy-mac-e2e-volunteer-checklist.md @@ -0,0 +1,260 @@ +# Omarchy Mac — Volunteer E2E Installation Checklist + +Use this checklist for a **fresh, on-metal installation**, beginning in macOS and ending with a verified Omarchy desktop after a second login and cold boot. A successful `install.sh` exit alone is not an E2E pass. + +Mark every applicable item **PASS**, **FAIL**, **BLOCKED**, or **SKIP**. Add evidence for failures and explain every skip. Stop at the first unsafe or unexplained storage/boot failure; collect evidence before retrying, repairing, or deleting the installation. + +## 1. Test assignment + +Complete this before starting so two volunteers do not unknowingly run the same case. + +- [ ] Tester: +- [ ] Test ID / tracking issue: +- [ ] Date and timezone: +- [ ] Mac model and year: +- [ ] Apple model identifier (for example `MacBookAir10,1`): +- [ ] SoC: M1 / M1 Pro / M1 Max / M2 / M2 Pro / M2 Max: +- [ ] RAM / SSD: +- [ ] macOS version and build: +- [ ] Asahi Alarm image: **Minimal BTRFS** / Minimal ext4: +- [ ] Install path: **encrypted** / unencrypted: +- [ ] Keyboard layout: +- [ ] Omarchy repository and ref: +- [ ] Target source commit, if assigned: +- [ ] Network type: Wi-Fi / Ethernet: +- [ ] Important peripherals or external display: + +### Coverage priority + +1. **Primary:** fresh Asahi Alarm Minimal BTRFS → default encrypted guided install. +2. **Secondary:** fresh BTRFS → `--no-encrypt`. +3. **Special assignment only:** ext4 conversion, interruption/resume, unusual layouts, rollback, or recovery testing. + +## 2. Safety and preparation + +- [ ] macOS has a recent verified backup. +- [ ] Linux has at least 50 GB; 100 GB is preferred. +- [ ] The machine can be recovered from macOS if Linux fails to boot. +- [ ] Important local data has been removed from the test installation. +- [ ] The Mac is connected to power and reliable internet. +- [ ] The test will use the assigned repo/ref—not an unrecorded local modification. +- [ ] I will not run ad-hoc partition, encryption, initramfs, or bootloader repair commands before collecting failure evidence. +- [ ] I will never disable `speakersafetyd` or other speaker protection to make audio pass. + +From macOS, record: + +```bash +system_profiler SPHardwareDataType +sw_vers +diskutil list +``` + +Do not publish serial numbers. Redact them before attaching output. + +## 3. Install and verify fresh Asahi Alarm + +- [ ] Install the assigned Asahi Alarm image from macOS. +- [ ] Record the exact image/installer used and the allocated Linux size. +- [ ] Boot the untouched Asahi installation successfully before running Omarchy. +- [ ] Log in as `root` and connect using `nmtui`. +- [ ] Confirm display, built-in keyboard/trackpad or required USB input, Wi-Fi, DNS, and clock are working. +- [ ] Confirm this is genuinely fresh: Omarchy is not already installed and no earlier guided setup is resuming. + +Capture the baseline: + +```bash +uname -a +cat /etc/os-release +findmnt -rn -o TARGET,SOURCE,FSTYPE,OPTIONS --mountpoint / +findmnt -rn -o TARGET,SOURCE,FSTYPE,OPTIONS --mountpoint /boot +lsblk -f +df -h / /boot +free -h +``` + +If the fresh Asahi baseline already fails, report it separately. Do not count it as an Omarchy installer failure. + +## 4. Start the guided installer + +Use the exact command assigned by the test coordinator. For the current default branch: + +```bash +curl -fsSL https://raw.githubusercontent.com/omacom/omarchy-mac/quattro/bin/omarchy-mac-setup | bash +``` + +- [ ] Record the command, repository, branch/ref, and start time. +- [ ] Confirm the installer identifies the expected encryption choice, hostname, username, and console keymap. +- [ ] Confirm the displayed plan matches the requested path. +- [ ] Default ARM-unavailable package prompt to **No**, unless this test specifically targets AUR availability. +- [ ] Photograph or transcribe warnings and the last visible line before every reboot. +- [ ] Record the duration of every stage and reboot. + +Do not call a warning harmless merely because the installer continued. Record all skipped or unavailable packages. + +## 5. Reboot checkpoints + +### A. Boot-layout reboot — encrypted path only + +- [ ] Apple boot → m1n1 → U-Boot → Linux boot menu completes normally. +- [ ] The setup resumes automatically on tty1; no permanent blank screen or blinking cursor. +- [ ] `/boot` has moved to a separate unencrypted partition. +- [ ] The installer advances to encryption instead of repeating the boot-layout step. + +### B. Encryption reboot — encrypted path only + +- [ ] The disk-passphrase prompt is visible and accepts input. +- [ ] The configured console keymap types the intended passphrase correctly. +- [ ] `cryptsetup reencrypt` progress is visible. +- [ ] Encryption finishes without an unexplained reboot, hang, or loop. +- [ ] On the next boot, the new passphrase unlocks the root filesystem. +- [ ] The setup resumes automatically and advances to Omarchy installation. + +### C. Omarchy installation and final reboot + +- [ ] Repository clone, package build/install, system setup, and user setup complete. +- [ ] Network loss or mirror errors are clearly reported rather than appearing as a hang. +- [ ] Required package failures do not get reported merely as optional skips. +- [ ] The final reboot reaches SDDM or the desktop according to the chosen login mode. +- [ ] The first graphical boot does not conflict with the tty1 setup service. +- [ ] The guided installer does not start again after completion. + +## 6. First desktop login + +- [ ] Login succeeds with the created user. +- [ ] The desktop renders correctly, including the notch-aware layout on MacBooks. +- [ ] First-run setup completes once and does not loop. +- [ ] Menu, launcher, terminal, browser, file manager, and settings open. +- [ ] Wi-Fi and DNS work. +- [ ] Built-in keyboard, trackpad, brightness keys, and keyboard backlight work where supported. +- [ ] Audio plays at modest volume with speaker protection active; headphones and microphone work if available. +- [ ] Lock and unlock work. +- [ ] Suspend/resume works once; Wi-Fi and input recover afterward. +- [ ] Change a theme and confirm the desktop remains usable. +- [ ] Record any missing application, notification error, visual defect, or obvious performance problem. + +Note: the wiki's hardware matrix tracks one answer per feature (internal display, HDMI display, USB-C display, USB, Thunderbolt/docks, Wi-Fi, Bluetooth, speakers, headphones, microphone, HDMI audio, suspend, camera, Touch ID, keyboard, trackpad, GPU inference, Neural Engine). Running the evidence collector with `--interview` asks for each of these separately — WORKS / LIMITATION / BROKEN / UNKNOWN / n/a (not built in) — plus the peripheral model and connection you tested with. What a probe detected is never treated as proof a feature works; only your answer fills the matrix. + +Collect the installed-system state: + +```bash +omarchy version +printf '%s\n' "$OMARCHY_PATH" +readlink -f /usr/share/omarchy +pacman -Q omarchy omarchy-settings hyprland hyprtoolkit hyprland-guiutils aquamarine +pacman -Dk +systemctl --failed --no-pager +systemctl --user --failed --no-pager +omarchy-migrate --pending +omarchy-done check finalize-user +omarchy-done check first-run-user +swapon --show +findmnt -rn -o TARGET,SOURCE,FSTYPE,OPTIONS --mountpoint / +findmnt -rn -o TARGET,SOURCE,FSTYPE,OPTIONS --mountpoint /boot +``` + +Note: `omarchy-migrate --pending` exits **0 when migrations are pending** and **1 when none are pending**. Record its output; do not interpret the exit code like a normal success/failure result. + +## 7. Persistence and security checks + +- [ ] Log out and log in again: first-run prompts and notifications do not repeat. +- [ ] Reboot normally: disk unlock, login, desktop, Wi-Fi, audio protection, and required user services still work. +- [ ] Shut down fully, wait 15 seconds, then cold boot successfully. +- [ ] The created user can use `sudo` with their password. +- [ ] Temporary setup files, services, and passwordless privileges have been retired. +- [ ] Root access follows the selected `--keep-root-password` choice. +- [ ] SSH behavior matches the documented security policy; it is not silently exposed through the firewall. +- [ ] No required system or user unit has `LoadState=not-found`. + +Useful checks: + +```bash +systemctl is-enabled omarchy-mac-setup.service +test -e /etc/omarchy-mac-setup.conf; echo "setup_conf=$?" +test -e /etc/sudoers.d/01-omarchy-mac-setup; echo "setup_sudoers=$?" +systemctl --failed --no-pager +systemctl --user --failed --no-pager +journalctl -b -p warning --no-pager +journalctl --user -b -p warning --no-pager +``` + +For the `test` commands, exit status `1` is expected after cleanup because the temporary file should be absent. + +## 8. If anything fails + +Do **not** immediately rerun the installer, apply a suggested fix, or wipe Linux. First record: + +- [ ] Exact stage, local time, expected result, and actual result. +- [ ] Last visible line and a photo/video of the screen. +- [ ] Whether the machine still responds to Caps Lock, SSH, or `Ctrl`+`Alt`+`F2/F3/F4`. +- [ ] Whether it reproduces after one normal retry; do not repeatedly force power off. +- [ ] Any hypothesis is clearly labelled as a hypothesis, separate from observations. + +If a shell is reachable, collect: + +```bash +/usr/local/bin/omarchy-mac-setup --status +systemctl status omarchy-mac-setup.service --no-pager +journalctl -u omarchy-mac-setup.service -b --no-pager +journalctl -b --no-pager +journalctl --list-boots +findmnt +lsblk -f +df -h / /boot +tail -n 200 /var/log/omarchy-install.log +tail -n 200 /var/log/pacman.log +``` + +Note: the current guided installer writes no `/var/log/omarchy-mac-setup.log` (its log variable is never redirected to a file), so do not treat that file's absence as a failure — the guided-setup output is in `journalctl -u omarchy-mac-setup.service`, captured above and by the evidence collector. + +For an earlier failed boot, select the actual boot ID shown by `journalctl --list-boots`; do not assume `-1` is the failed attempt. Review logs before publishing and remove passwords, tokens, serial numbers, private hostnames, and other personal data. + +## 9. Final result + +Overall result: **PASS / FAIL / BLOCKED** + +An E2E **PASS** requires all of the following: + +- Fresh Asahi baseline worked. +- The assigned guided install path completed every stage. +- Automatic resume worked across every reboot. +- First desktop login and first-run completed. +- Second login, normal reboot, and cold boot succeeded. +- Required services, migrations, package state, storage layout, and security cleanup were verified. +- No required check was skipped. + +## Report template + +```text +Test ID: +Tester: +Date/timezone: +Mac model / Apple identifier / SoC / RAM: +macOS version: +Asahi image and filesystem: +Encryption and keymap: +Omarchy repo / ref / installed version: +Test command: + +Fresh Asahi baseline: PASS / FAIL +Boot-layout stage: PASS / FAIL / SKIP +Encryption stage: PASS / FAIL / SKIP +Omarchy install stage: PASS / FAIL +First login: PASS / FAIL +Second login: PASS / FAIL +Normal reboot: PASS / FAIL +Cold boot: PASS / FAIL +Hardware smoke test: PASS / FAIL / SKIP +Security cleanup: PASS / FAIL + +Overall: PASS / FAIL / BLOCKED +First failing checkpoint: +Expected: +Actual: +Reproduction steps: +Warnings / skipped packages: +Logs, photos, or video: +Related issue/PR: +Notes and clearly labelled hypotheses: +``` + +Keep evidence attached to the test ID or GitHub issue. “Installed successfully” without machine details, exact ref, reboot results, and logs is not a completed E2E report. diff --git a/scripts/collect_common.py b/scripts/collect_common.py new file mode 100755 index 000000000000..203edd75a853 --- /dev/null +++ b/scripts/collect_common.py @@ -0,0 +1,588 @@ +#!/usr/bin/env python3 +"""Shared helpers for the mlx-omarchy contributor collectors. + +`collect_quick.py` and `collect_deep.py` import this module. It owns the +three things both collectors must agree on: + +- PII redaction (`Redactor`): usernames, hostnames, home paths, IP + addresses, MAC addresses, serial numbers, UUIDs, and credential-shaped + strings never reach an output. Every embedded command output passes + through it, and its per-kind counts go into the manifest so a reader can + see what was removed. +- bounded external commands (`run_tool`, `run_python_probe`): a missing or + hanging tool is recorded data, never a crash, never an unbounded wait. +- deterministic packaging (`build_manifest`, `archive_bytes`): sorted + members, fixed mtime and owner, gzip mtime 0, so the previewed manifest + and the written archive agree byte for byte. + +Nothing in this module talks to the network. The collectors never upload. +""" + +import gzip +import hashlib +import io +import json +import os +import re +import shutil +import socket +import subprocess +import sys +import tarfile +import time +import getpass + +SCHEMA_VERSION = 1 + +MAX_STREAM_LINES = 400 +MAX_STREAM_CHARS = 200_000 + + +class Redactor: + """Replace personally identifying strings with typed placeholders.""" + + def __init__(self, hostname=None, username=None, home=None): + self.hostname = hostname or socket.gethostname() + try: + self.username = username or getpass.getuser() + except Exception: + self.username = os.environ.get("USER") or os.environ.get("LOGNAME") or "" + self.home = home or os.path.expanduser("~") + self.counts = {} + self._rules = self._build_rules() + + def _note(self, kind): + self.counts[kind] = self.counts.get(kind, 0) + 1 + + def _replace(self, kind, repl): + def fn(_match): + self._note(kind) + return repl + return fn + + # A dotted quad is not always an address: Vulkan reports + # `conformanceVersion = 1.4.0.0`, and Apple reports boot firmware + # versions like `iBoot-20712.1.2.0.0`, whose trailing quad is a + # continuation of a dotted version chain. Keep the quad when the + # text right before it is a version assignment or more dotted + # octets; redact every other dotted quad. + _VERSION_CONTEXT = re.compile(r"(?i)(?:version\s*[:=]\s*|\d+\.)$") + + def _ipv4_sub(self, match, field=None): + if (isinstance(field, str) and field.lower().endswith("version") + and not match.string[:match.start()].strip()): + return match.group(0) + line_start = match.string.rfind("\n", 0, match.start()) + 1 + prefix = match.string[line_start:match.start()] + if self._VERSION_CONTEXT.search(prefix): + return match.group(0) + self._note("ipv4") + return "[redacted-ip4]" + + def _build_rules(self): + rules = [] + + def rx(pattern, kind, repl, flags=0): + rules.append((re.compile(pattern, flags), self._replace(kind, repl))) + + # Cred-shaped assignments first, so a value that also matches a + # later rule is already gone. Name=NAME VALUE=VALUE keeps the name. + rx( + r"(?i)\b([A-Za-z0-9_]*(?:token|secret|passwd|password|api_?key|" + r"private_?key)[A-Za-z0-9_]*)\s*([:=])\s*(\"[^\"]*\"|\S+)", + "credential", + r"\1\2 [redacted]", + ) + # Known credential shapes without a key name. + rx(r"\bgh[pousr]_[A-Za-z0-9]{16,}\b", "credential", "[redacted]") + rx(r"\bgithub_pat_[A-Za-z0-9_]{20,}\b", "credential", "[redacted]") + rx(r"\bAKIA[0-9A-Z]{16}\b", "credential", "[redacted]") + rx(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b", "credential", "[redacted]") + rx(r"\bsk-[A-Za-z0-9_-]{20,}\b", "credential", "[redacted]") + rx(r"\bBearer\s+\S+", "credential", "Bearer [redacted]") + rx(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}\b", + "credential", "[redacted]") + # Hardware identity. + rx(r"\b(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\b", "mac", "[redacted-mac]") + rx(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-" + r"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b", "uuid", "[redacted-uuid]") + rx(r"(?i)(\"serial(?:[-_]?number)?\"\s*:\s*\")[^\"]*(\")", + "serial", r"\1[redacted]\2") + rx(r"(?i)\b(serial[-_]?number)\s*([=:])\s*(\S+)", + "serial", r"\1\2 [redacted]") + # ioreg/macOS hardware identity: "IOPlatformSerialNumber" = "C02…" + rx(r"(?i)\"?(IOPlatformSerialNumber|IOPlatformUUID|BoardID|" + r"board-id|serial-number)\"?\s*=\s*\"[^\"]*\"", + "serial", r"\1 = [redacted]") + # Bare Apple platform serial shape (e.g. C02XY9876543): a value + # that lost its key must still not survive. Requires letter + + # two digits + at least eight more alphanumerics, so model and + # version tokens like H11ANEIn or t6000 never match. + rx(r"\b[A-Z][0-9]{2}[A-Z0-9]{8,10}\b", "serial", "[redacted]") + # Network identity. IPv6 before IPv4 so embedded v4-in-v6 is gone. + rx(r"\b(?:fe80|fd[0-9a-f]{2}|fc[0-9a-f]{2})(?::[0-9a-fA-F]{0,4}){1,7}" + r"(?:%\w+)?\b", "ipv6", "[redacted-ip6]", re.IGNORECASE) + rx(r"\b(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}\b", + "ipv6", "[redacted-ip6]") + rules.append(( + re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}(?:/\d{1,3})?\b"), + self._ipv4_sub, + )) + # Home paths: this user's home first, then any user's. + if self.home and self.home != "/" and self.home != "": + rules.append(( + re.compile(re.escape(self.home)), + self._replace("home_path", "[home]"), + )) + rx(r"(?= 2: + rules.append(( + re.compile(r"(?= 2: + rules.append(( + re.compile(r"(? MAX_STREAM_LINES or len(text) > MAX_STREAM_CHARS: + out += f"\n[truncated: {total} lines, {len(text)} chars captured]" + return out + + +def redact_argv(argv, redactor): + """Record the command shape without values that could carry secrets.""" + return [redactor.apply(str(a)) for a in argv] + + +def run_tool(argv, redactor, label=None, timeout=30, cwd=None, env=None): + """Run one external command; record absence, timeout, and output. + + Returns a dict. Never raises for a missing binary or a timeout. + """ + record = { + "label": label or argv[0], + "argv": redact_argv(argv, redactor), + "available": True, + "exit_code": None, + "error": None, + "duration_ms": None, + "stdout": "", + "stderr": "", + } + if shutil.which(argv[0]) is None: + record["available"] = False + record["error"] = "not-found" + return record + started = time.monotonic() + try: + proc = subprocess.run( + argv, + capture_output=True, + text=True, + errors="replace", + timeout=timeout, + cwd=cwd, + env=env, + ) + record["exit_code"] = proc.returncode + record["stdout"] = redactor.apply(cap_stream(proc.stdout or "")) + record["stderr"] = redactor.apply(cap_stream(proc.stderr or "")) + except subprocess.TimeoutExpired: + record["error"] = f"timeout after {timeout}s" + except OSError as exc: + record["available"] = False + record["error"] = f"os-error: {exc}" + record["duration_ms"] = int((time.monotonic() - started) * 1000) + return record + + +def run_python_probe(code, redactor, label, timeout=120, env=None): + """Run a python snippet in a child interpreter, bounded.""" + return run_tool( + [sys.executable, "-c", code], + redactor, + label=label, + timeout=timeout, + env=env, + ) + + +def dump_json(obj): + """Deterministic JSON text: sorted keys, fixed indent, trailing newline.""" + return json.dumps(obj, indent=2, sort_keys=True) + "\n" + + +def json_bytes(obj): + return dump_json(obj).encode("utf-8") + + +def archive_bytes(files): + """Deterministic gzip tarball from {member name: bytes}. + + Sorted members, mtime 0, root owner, empty uname/gname, gzip mtime 0. + Same files in, same bytes out. + """ + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w", format=tarfile.GNU_FORMAT) as tf: + for name in sorted(files): + data = files[name] + info = tarfile.TarInfo(name) + info.size = len(data) + info.mtime = 0 + info.mode = 0o644 + info.uid = 0 + info.gid = 0 + info.uname = "" + info.gname = "" + info.type = tarfile.REGTYPE + tf.addfile(info, io.BytesIO(data)) + return gzip.compress(buf.getvalue(), compresslevel=9, mtime=0) + + +def build_manifest(archive_name, files, extra=None): + """Manifest describing every member except itself. + + `files` must not contain "manifest.json"; the caller adds it to the + archive after hashing the manifest bytes themselves. + """ + entries = [] + for name in sorted(files): + data = files[name] + entries.append({ + "path": name, + "bytes": len(data), + "sha256": hashlib.sha256(data).hexdigest(), + }) + manifest = { + "schema_version": SCHEMA_VERSION, + "manifest_version": 1, + "tool": "mlx-omarchy collect-deep", + "archive": archive_name, + "files": entries, + "no_network": True, + "upload": "only after explicit --submit or SUBMIT confirmation", + } + if extra: + manifest.update(extra) + return manifest + + +def is_native_macos(host, manifest): + """True when a report came from native macOS MLX rather than Linux.""" + return (host.get("system") or manifest.get("system")) == "Darwin" + + +def _cap_port_detail(port, redactor, max_bytes=64 * 1024): + """Bounded `ane_port_detail` blob for the quick PAYLOAD. + + Carries the devicetree (and the runtime block if it fits) at enough + fidelity to author the omarchy-ane overlay off-machine. The flat + `ane_port` summary string is kept for back-compat with rows that + were already stored before the detail object existed. + + Bounding rules, in order — each one marks `truncated` with the + reason so a reader knows the shape of what was dropped: + + * ane_nodes / darts / phandles: hard cap of MAX_PORT_DETAIL_NODES + each; a node beyond the cap is dropped, not truncated in place. + * pmgr_domains: hard cap of 64 (matches the source collector). + * total serialized bytes: hard cap of `max_bytes`. Drop order is + by porting value: the runtime block first, then the phandle map + (`iommus_resolved` already did that arithmetic for the reader), + then the AIC block, then DARTs; the ane nodes — the whole point + of the capture — are dropped last. + * a macOS report carries `macos` instead of `devicetree` and is + bounded at the source; if it somehow exceeds the budget the + whole block is dropped. + + `redactor` is the shared one from the collector: every string value + already passed it once during probe_ane_port; passing it again here + is a belt-and-braces pass in case a probe missed a string-shaped + value. Numeric and bool fields stay numeric and bool. + """ + if not isinstance(port, dict): + return None + + MAX_NODES = 8 # hard cap on ane_nodes / darts / phandles entries + truncated = [] + + src_devicetree = port.get("devicetree") + src_runtime = port.get("runtime") + src_macos = port.get("macos") + + def _walk(node): + """Re-redact every string leaf; keep numeric/bool/list shape.""" + if isinstance(node, dict): + return {k: _walk(v) for k, v in node.items()} + if isinstance(node, list): + return [_walk(v) for v in node] + if isinstance(node, str): + return redactor.apply(node) if redactor else node + return node + + def _size(node): + return len(json.dumps(node, separators=(",", ":"))) + + # macOS: the probe bounds its own output; carry it through and + # re-redact. The legacy Linux devicetree keys do not apply. + if src_macos is not None: + out = {"macos": _walk(src_macos)} + if truncated or _size(out) > max_bytes: + out["truncated"] = (truncated or [])[:15] + \ + ["macos:over_budget"] + if _size(out) > max_bytes: + return None + return out + + src_devicetree = src_devicetree or {} + def _bounded_dict(d, cap, name): + if not isinstance(d, dict): + return {} + keys = sorted(d.keys()) + kept = {k: _walk(d[k]) for k in keys[:cap]} + if len(keys) > cap: + truncated.append(f"{name}:{len(keys) - cap}") + return kept + + bounded = { + "ane_node_present": bool(src_devicetree.get("ane_node_present")), + "ane_nodes": _bounded_dict(src_devicetree.get("ane_nodes") or {}, + MAX_NODES, "ane_nodes"), + "darts": _bounded_dict(src_devicetree.get("darts") or {}, + MAX_NODES, "darts"), + "pmgr_domains": _walk(src_devicetree.get("pmgr_domains") or [])[:64] + if len(src_devicetree.get("pmgr_domains") or []) > 64 + else _walk(src_devicetree.get("pmgr_domains") or []), + "aic": _walk(src_devicetree.get("aic")) + if src_devicetree.get("aic") else None, + "phandles": _bounded_dict(src_devicetree.get("phandles") or {}, + MAX_NODES, "phandles"), + } + if len(src_devicetree.get("pmgr_domains") or []) > 64: + truncated.append(f"pmgr_domains:" + f"{len(src_devicetree['pmgr_domains']) - 64}") + + out = {"devicetree": bounded} + + if isinstance(src_runtime, dict): + bounded_runtime = _walk(src_runtime) + # Total budget check: include runtime only if it fits. We try + # with runtime first, then drop it if it pushes us over the cap. + candidate = dict(out) + candidate["runtime"] = bounded_runtime + if _size(candidate) <= max_bytes: + out = candidate + else: + truncated.append("runtime:over_budget") + + # Still over budget: drop by porting value. The phandle map goes + # first (iommus_resolved already did that arithmetic for the + # reader), then the AIC block, then DARTs; the ane nodes go last. + if _size(out) > max_bytes: + trimmed = out + for field, blank in (("phandles", {}), ("aic", None), + ("darts", {}), ("ane_nodes", {})): + if _size(trimmed) <= max_bytes: + break + dt = dict(trimmed["devicetree"]) + dt[field] = blank + trimmed = {"devicetree": dt} + if "runtime" in out: + trimmed["runtime"] = out["runtime"] + truncated.append(f"{field}:over_budget") + if _size(trimmed) > max_bytes: + truncated.append("devicetree:over_budget") + return None + out = trimmed + + if truncated: + out["truncated"] = truncated[:16] + return out + + +def build_payload(kind, quick, manifest, generated_at=None, benchmark=None, + redactor=None): + """Build the strict-schema JSON summary sent with the upload. + + Must match schema/payload-v1.schema.json in services/community-data: + fixed key set, schema_version pinned, every identity field nullable. + All values come from already-redacted data. `redactor` is the + collector's shared Redactor; it is used to belt-and-braces re-redact + the ane_port_detail blob in case a probe missed a string-shaped + value. New callers should pass it; existing tests that do not are + tolerated (re-redaction becomes a no-op). + """ + host = quick.get("host") or {} + dt = host.get("devicetree") or {} + gpu = (quick.get("mesa") or {}).get("gpu") or {} + mlx = quick.get("mlx") or {} + distributions = mlx.get("distributions") or {} + compatible = dt.get("compatible") or [] + # Group by SoC, not by board: an M1 MacBook Pro reports + # ["apple,j293", "apple,t8103", "apple,arm-platform"], and only + # apple,t8103 identifies the chip that every other M1 machine shares. + soc = next((c for c in compatible + if re.match(r"^apple,t\d{4}", c)), None) + host_cpu = host.get("cpu_online") + cpu = host.get("cpu") or {} + boot = host.get("boot") or {} + cmdline = host.get("cmdline") + ane_dt = (quick.get("ane") or {}).get("devicetree") or {} + ane_compatible = ane_dt.get("compatible") + ane_compat_blob = " ".join(str(t) for t in ane_compatible) \ + if isinstance(ane_compatible, list) else None + boot_chain = " ".join( + f"{key}={boot[key]}" for key in sorted(boot) + if isinstance(boot.get(key), str) and boot[key]) + present = cpu.get("present") + shortfall = host.get("core_shortfall") + # Plain wire fact: true when the report recorded an unexplained + # shortfall, false when present/online are known and equal enough, + # null when the counts needed to judge are missing. + if isinstance(shortfall, dict): + shortfall_flag = True + elif isinstance(present, int) and isinstance(host_cpu, int): + shortfall_flag = False + else: + shortfall_flag = None + # The benchmark numbers must ride in the summary, not only inside the + # archive: the read API serves summaries, so cross-machine comparison + # is impossible unless the numbers travel with them. + rows = [] + for row in (benchmark or [])[:16]: + if not isinstance(row, dict) or not isinstance(row.get("n"), int): + continue + rows.append({ + "n": row["n"], + "tflops": row.get("tflops"), + "median_ms": row.get("median_ms"), + }) + native = is_native_macos(host, manifest) + # Bounded driver-port summary: enough for fleet queries (does this + # SoC expose the ane node, how many DARTs and PMGR domains, which + # AIC) without shipping the full devicetree dump in every payload. + src_port = quick.get("ane_port") or {} + macos_port = src_port.get("macos") + if isinstance(macos_port, dict): + cores = sorted({i.get("cores") for i in + (macos_port.get("instances") or []) + if isinstance(i.get("cores"), int)}) + ane_port = ( + "native_macos=1 instances=%d cores=%s dart_ane=%d " + "firmware=%s" % ( + len(macos_port.get("instances") or []), + "+".join(str(c) for c in cores) or "?", + len(macos_port.get("dart_nodes") or []), + "loaded" if any(i.get("firmware_loaded") + for i in macos_port.get("instances") or []) + else "unknown"))[:1024] + else: + port = src_port.get("devicetree") or {} + port_parts = [ + "present=" + str(bool(port.get("ane_node_present"))).lower()] + for name, props in sorted((port.get("ane_nodes") or {}).items()): + regs = props.get("reg") if isinstance(props, dict) else None + port_parts.append(f"{name}={regs[0] if regs else 'no-reg'}") + port_parts.append(f"darts={len(port.get('darts') or {})}") + port_parts.append( + f"pmgr_domains={len(port.get('pmgr_domains') or [])}") + aic_compat = (port.get("aic") or {}).get("compatible") or [] + if aic_compat: + port_parts.append(f"aic={aic_compat[0]}") + ane_port = (" ".join(port_parts)[:1024] + if quick.get("ane_port") else None) + # Bounded full-structure port detail. Capped per-section, total + # bytes hard-bounded; truncation is recorded explicitly so a reader + # can tell which corner the cap clipped. Re-redacts every string + # leaf against the shared Redactor in case a probe missed one. + ane_port_detail = _cap_port_detail(quick.get("ane_port"), redactor) \ + if quick.get("ane_port") else None + kernel = host.get("kernel_release") + if native: + shortfall_flag = None + kernel = f"Darwin {kernel or 'unknown'} ({host.get('os') or 'macOS'})" + device = mlx.get("default_device") + if native and mlx.get("metal_available"): + device = f"Metal GPU (native macOS MLX, {device})" + return { + "schema_version": SCHEMA_VERSION, + "kind": kind, + "generated_at": generated_at or time.strftime( + "%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "arch": host.get("arch"), + "model": host.get("model") if native else dt.get("model"), + "chip": host.get("chip") if native else + soc or (compatible[0] if compatible else None), + "kernel": kernel, + "mesa_driver": gpu.get("driverName"), + "mesa_device": gpu.get("deviceName"), + "mlx_version": distributions.get("mlx-omarchy") + or mlx.get("mlx_version"), + "mlx_device": device, + "source_commit": manifest.get("source_commit"), + "repo_dirty": manifest.get("repo_dirty"), + "cpu_present": present if isinstance(present, int) else None, + "hotplug_control": cpu.get("hotplug_control") + if isinstance(cpu.get("hotplug_control"), bool) else None, + "ane_dt_node": ane_dt.get("node") + if isinstance(ane_dt.get("node"), bool) else None, + "ane_port": ane_port or None, + "ane_port_detail": ane_port_detail, + "ane_dt_compatible": ane_compat_blob[:512] if ane_compat_blob + else None, + "boot_chain": boot_chain[:512] or None, + "cmdline": cmdline[:1024] if isinstance(cmdline, str) else None, + "core_shortfall": shortfall_flag, + "cpu_online": host_cpu if isinstance(host_cpu, int) else None, + "benchmark": rows, + "redaction_summary": dict( + manifest.get("redaction_summary") or {}), + "files": [ + {key: entry[key] for key in ("path", "bytes", "sha256")} + for entry in manifest.get("files", []) + ], + } + + +def read_text(path): + try: + with open(path, "r", encoding="utf-8", errors="replace") as fh: + return fh.read() + except OSError: + return None diff --git a/scripts/collect_e2e.py b/scripts/collect_e2e.py new file mode 100755 index 000000000000..a9c756676b62 --- /dev/null +++ b/scripts/collect_e2e.py @@ -0,0 +1,1152 @@ +#!/usr/bin/env python3 +"""Collect Omarchy Mac E2E installation evidence into one reviewable archive. + +Companion to the volunteer E2E installation checklist +(docs/omarchy-mac-e2e-volunteer-checklist.md). The checklist names what a +volunteer must observe; this script gathers everything a machine can +observe on its own, bounds every command, redacts identity strings, and +packs the result into a deterministic archive the volunteer can attach to +their test report. Human-judgment checkboxes are walked in `--interview` +mode and stored as data next to the machine evidence, so a submission +carries both. + +Self-contained: stdlib only, no repository build, no network by default. +Like the mlx-omarchy collectors it borrows its plumbing from, a missing +tool or log is recorded as data, never a crash. Section results are +written as they complete, so an interrupted run keeps what finished. + +Sections (schema_version 1): + identity test assignment answers (checklist section 1), reused + across runs from e2e-identity.json in the working dir, + plus machine-recorded identity: marketing model, board + and SoC from devicetree compatible strings, kernel, + OS, collection date (identity only -- never a verdict) + baseline the fresh-Asahi baseline commands (section 3): mounts, + lsblk, df, free, plus a freshness marker + hardware presence-only hardware records for the wiki feature + matrix (DRM connectors, audio, USB, Thunderbolt, + wireless, cameras, inputs, suspend states). Presence + is never converted into a feature verdict; the + interview's per-feature answers stay the only source + install-logs omarchy-mac-setup/install/pacman log tails (with + recorded absence notes -- a missing log is data, not + a failure) and the setup service state (sections 4-5) + boot journal boot list, current-boot warnings, failed + system and user units (sections 5-7) + install-state omarchy version and path, pinned package versions, + migration and first-run state (section 6) + security cleanup and exposure checks (section 7) + mlx the mlx-omarchy quick capability report (vendored + collect_quick): host, Mesa/Vulkan, ANE devicetree, + installed mlx-omarchy distributions and default device + macos optional: pasted macOS-side output via --from-macos + interview optional: --interview walks every human-judgment + checkbox (sections 5-9, PASS/FAIL/SKIP/NA) and every + wiki hardware feature (WORKS/LIMITATION/BROKEN/ + UNKNOWN/NA, with the peripheral model and connection + in the note), persisted to ./e2e-answers.json + +Privacy: every captured value passes through the shared Redactor (names, +paths, IPs, MACs, serials, credential-shaped strings). The default run +only previews. `--out FILE` writes the deterministic archive plus a +paste-ready `FILE.submission.md` with the checklist report template +pre-filled from machine evidence. Uploading is explicit: pass +`--submit URL` (the mlx-omarchy community-data worker protocol; use a +kind-aware endpoint such as MLX_OMARCHY_SUBMIT_URL pointing at an e2e +collection worker when one exists). + +Typical volunteer flow: + python3 scripts/collect_e2e.py --out e2e-run1.tar.gz + python3 scripts/collect_e2e.py --interview --out e2e-run1.tar.gz +""" +import argparse +import getpass +import hashlib +import json +import os +import platform +import re +import shutil +import sys +import tempfile +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import collect_quick +from collect_common import ( + SCHEMA_VERSION, + Redactor, + archive_bytes, + build_manifest, + build_payload, + dump_json, + json_bytes, + read_text, + run_tool, +) + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +SECTION_TIMEOUTS = { + "identity": 10, + "baseline": 60, + "mlx": 240, + "hardware": 60, + "install-logs": 60, + "boot": 90, + "install-state": 60, + "security": 60, + "macos": 10, + "interview": 300, +} +SECTION_ORDER = ("identity", "baseline", "mlx", "hardware", "install-logs", + "boot", "install-state", "security", "macos", "interview") + +SETUP_LOGS = ( + "/var/log/omarchy-mac-setup.log", + "/var/log/omarchy-install.log", + "/var/log/pacman.log", +) + +# Why a log can be absent where that is knowable, so "never written by +# design" is distinguishable from "the install did not reach that stage" +# -- and so neither is ever read as a hardware failure. +LOG_ABSENCE_NOTES = { + "/var/log/omarchy-mac-setup.log": + "known: the current bin/omarchy-mac-setup never writes this file " + "(its $LOG variable is never a redirection target), so absence is " + "expected on every run and is NOT a failure. Guided-setup output " + "lives in journalctl -u omarchy-mac-setup.service (captured below).", + "/var/log/omarchy-install.log": + "written by the Asahi-side install; absent before that stage runs, " + "which is data about progress, not a hardware or install failure.", + "/var/log/pacman.log": + "absent before packages are installed; absence is progress data, " + "not a failure.", +} +LOG_ABSENCE_GENERIC = ("a missing log is recorded as data; absence does " + "not imply any hardware failed") + +PINNED_PACKAGES = ("omarchy", "omarchy-settings", "hyprland", "hyprtoolkit", + "hyprland-guiutils", "aquamarine") + + +def read_path(redactor, path, max_chars=60_000): + """Tail a file if present; absence is data, not an error.""" + try: + with open(path, "r", errors="replace") as fh: + data = fh.read() + except OSError as exc: + return {"present": False, "error": redactor.apply(f"{type(exc).__name__}: {exc}")} + return {"present": True, "bytes_total": None, + "tail": redactor.apply(data)[-max_chars:]} + + +def tool(argv, redactor, label, timeout=30): + return run_tool(argv, redactor, label=label, timeout=timeout) + + +def sox_field(path): + """Read one small devicetree property, NULs stripped.""" + try: + with open(path, "r", errors="replace") as fh: + return fh.read().replace("\x00", " ").strip() + except OSError: + return None + + +def machine_identity(): + """Recorded hardware/system identity from the booted system. + + Identity only: this records which machine and software versions are + under test. Nothing here implies any feature works; the wiki matrix + answers stay human-only (see FEATURE_ITEMS). + """ + dt = "/sys/firmware/devicetree/base" + compatible = [p for p in (sox_field(dt + "/compatible") or "").split() if p] + soc = next((c.split(",", 1)[1].upper() for c in compatible + if re.match(r"^apple,t\d{4}", c)), None) + board = next((c for c in compatible if re.match(r"^apple,j\d", c)), None) + os_pretty = None + try: + with open("/etc/os-release", "r", errors="replace") as fh: + for line in fh: + if line.startswith("PRETTY_NAME="): + os_pretty = line.split("=", 1)[1].strip().strip('"') + except OSError: + pass + return { + "marketing_model": sox_field(dt + "/model"), + "board_compatible": board, + "soc": soc, + "compatible": compatible, + "kernel": platform.release(), + "arch": platform.machine(), + "os": os_pretty, + "collected_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", + time.gmtime()), + "note": "identity recorded from the booted system; soc/board are " + "derived from devicetree compatible strings, the Apple " + "model identifier (Mac14,10 style) stays a human prompt", + } + + +def section_identity(redactor, answers_path): + out = {"available": True, "prompts": [], "identity_file": None} + prior = {} + if os.path.exists(answers_path): + try: + with open(answers_path, "r") as fh: + prior = json.load(fh) + out["identity_file"] = redactor.apply(answers_path) + except (OSError, ValueError): + prior = {} + prompts = [ + ("tester", "Tester name/handle"), + ("test_id", "Test ID / tracking issue"), + ("date_timezone", "Date and timezone"), + ("mac_model", "Mac model and year"), + ("model_identifier", "Apple model identifier (e.g. MacBookAir10,1)"), + ("soc", "SoC (M1/M1 Pro/M1 Max/M2/M2 Pro/M2 Max)"), + ("ram_ssd", "RAM / SSD"), + ("macos_version", "macOS version and build"), + ("asahi_image", "Asahi Alarm image (Minimal BTRFS / Minimal ext4)"), + ("install_path", "Install path (encrypted / unencrypted)"), + ("keyboard_layout", "Keyboard layout"), + ("omarchy_repo_ref", "Omarchy repository and ref"), + ("target_commit", "Target source commit, if assigned"), + ("network_type", "Network type (Wi-Fi / Ethernet)"), + ("peripherals", "Important peripherals or external display"), + ] + interactive = sys.stdin.isatty() + out["interactive"] = interactive + for key, question in prompts: + if prior.get(key): + out[key] = prior[key] + elif interactive: + try: + answer = input(f"{question}: ").strip() + except EOFError: + answer = "" + out[key] = answer or None + else: + out[key] = None + if not out.get(key): + out["prompts"].append(question) + machine = machine_identity() + out["devicetree"] = {"model": machine["marketing_model"], + "compatible": machine["compatible"]} + out["machine"] = machine + if interactive: + merged = {k: v for k, v in prior.items() if k not in ("prompts",)} + merged.update({k: out[k] for k, _ in prompts}) + try: + with open(answers_path, "w") as fh: + json.dump(merged, fh, indent=2, sort_keys=True) + fh.write("\n") + except OSError: + pass + return out + + +def lsblk_json(redactor): + rec = tool(["lsblk", "--json", "-o", "NAME,FSTYPE,SIZE,MOUNTPOINTS"], + redactor, label="lsblk json", timeout=20) + if rec["exit_code"] != 0: + return {"available": False, "error": rec["error"] or rec["stderr"][:300]} + try: + return {"available": True, "blockdevices": json.loads(rec["stdout"])} + except ValueError as exc: + return {"available": False, "error": f"unparsable: {exc}"} + + +def storage_facts(redactor): + """Derive the facts the checklist asks the volunteer to eyeball.""" + facts = {"available": True, "root_encrypted": None, "boot_separate": None, + "luks_devices": []} + data = lsblk_json(redactor) + if not data.get("available"): + return {"available": False, "error": data.get("error")} + for dev in (data["blockdevices"].get("blockdevices") or []): + stack = [dev] + while stack: + node = stack.pop() + fstype = (node.get("fstype") or "").lower() + if fstype == "crypto_luks": + facts["luks_devices"].append(node.get("name")) + stack.extend(node.get("children") or []) + rec = tool(["findmnt", "-rn", "-o", "SOURCE,FSTYPE,OPTIONS", "--mountpoint", "/"], + redactor, label="findmnt /", timeout=10) + facts["root_mount"] = rec["stdout"].strip() or None + rec = tool(["findmnt", "-rn", "-o", "SOURCE,FSTYPE,OPTIONS", "--mountpoint", "/boot"], + redactor, label="findmnt /boot", timeout=10) + boot_mount = rec["stdout"].strip() + facts["boot_mount"] = boot_mount or None + if boot_mount and facts["root_mount"]: + facts["boot_separate"] = boot_mount.split()[0] != facts["root_mount"].split()[0] + if facts["luks_devices"]: + facts["root_encrypted"] = True + rec = tool(["findmnt", "-rn", "-o", "SOURCE", "--mountpoint", "/"], + redactor, label="findmnt / source", timeout=10) + if rec["stdout"].startswith("/dev/mapper/"): + facts["root_encrypted"] = True + facts["fresh_marker"] = { + "setup_conf_present": os.path.exists("/etc/omarchy-mac-setup.conf"), + "note": "setup_conf_present=true means a guided install already ran " + "here; the checklist requires a genuinely fresh system", + } + return facts + + +def section_baseline(redactor): + out = {"available": True} + for label, argv in ( + ("uname", ["uname", "-a"]), + ("os_release", ["cat", "/etc/os-release"]), + ("findmnt_root", ["findmnt", "-rn", "-o", "TARGET,SOURCE,FSTYPE,OPTIONS", + "--mountpoint", "/"]), + ("findmnt_boot", ["findmnt", "-rn", "-o", "TARGET,SOURCE,FSTYPE,OPTIONS", + "--mountpoint", "/boot"]), + ("lsblk_f", ["lsblk", "-f"]), + ("df", ["df", "-h", "/", "/boot"]), + ("free", ["free", "-h"]), + ("swapon", ["swapon", "--show"]), + ): + out[label] = tool(argv, redactor, label=label) + out["storage_facts"] = storage_facts(redactor) + return out + + +def section_install_logs(redactor): + out = {"available": True, "logs": {}, "absence_notes": {}} + for path in SETUP_LOGS: + rec = read_path(redactor, path, max_chars=200_000) + out["logs"][path] = rec + if not rec.get("present"): + out["absence_notes"][path] = \ + LOG_ABSENCE_NOTES.get(path, LOG_ABSENCE_GENERIC) + out["setup_service_journal"] = tool( + ["journalctl", "-u", "omarchy-mac-setup.service", "-b", "--no-pager"], + redactor, label="journalctl -u omarchy-mac-setup", timeout=45) + out["setup_status"] = tool( + ["/usr/local/bin/omarchy-mac-setup", "--status"], redactor, + label="omarchy-mac-setup --status", timeout=30) + out["setup_service_enabled"] = tool( + ["systemctl", "is-enabled", "omarchy-mac-setup.service"], redactor, + label="is-enabled omarchy-mac-setup", timeout=15) + out["setup_service_status"] = tool( + ["systemctl", "status", "omarchy-mac-setup.service", "--no-pager"], + redactor, label="status omarchy-mac-setup", timeout=15) + out["install_stage_timing_note"] = ( + "per-stage wall times and pre-reboot screen tails are not machine-" + "readable today; photograph or transcribe them per checklist section 4") + return out + + +def section_boot(redactor): + out = {"available": True} + out["boot_list"] = tool(["journalctl", "--list-boots", "--no-pager"], + redactor, label="journalctl --list-boots", timeout=30) + out["current_boot_warnings"] = tool( + ["journalctl", "-b", "-p", "warning", "--no-pager"], redactor, + label="journalctl -b -p warning", timeout=60) + out["failed_units"] = tool(["systemctl", "--failed", "--no-pager"], redactor, + label="systemctl --failed", timeout=30) + out["failed_user_units"] = tool( + ["systemctl", "--user", "--failed", "--no-pager"], redactor, + label="systemctl --user --failed", timeout=30) + out["boot_tree"] = tool(["find", "/boot", "-maxdepth", "2", "-printf", + "%y %p\n"], redactor, label="find /boot", + timeout=30) + out["units_not_found"] = tool( + ["systemctl", "list-units", "--all", "--no-pager"], redactor, + label="list-units (LoadState scan)", timeout=30) + return out + + +def section_install_state(redactor): + out = {"available": True} + out["omarchy_version"] = tool(["omarchy", "version"], redactor, + label="omarchy version", timeout=15) + out["omarchy_path"] = {"env_OMARCHY_PATH": redactor.apply( + os.environ.get("OMARCHY_PATH") or "") or None, + "usr_share_symlink": None} + try: + out["omarchy_path"]["usr_share_symlink"] = redactor.apply( + os.path.realpath("/usr/share/omarchy")) + except OSError: + pass + out["pinned_packages"] = tool(["pacman", "-Q", *PINNED_PACKAGES], redactor, + label="pacman -Q pinned", timeout=30) + out["pacman_Dk"] = tool(["pacman", "-Dk"], redactor, + label="pacman -Dk", timeout=60) + # Checklist note: --pending exits 0 when migrations ARE pending and + # 1 when none are. Record, never interpret as pass/fail. + migrate = tool(["omarchy-migrate", "--pending"], redactor, + label="omarchy-migrate --pending", timeout=60) + migrate["checklist_semantics"] = ("exit 0 = migrations pending; " + "exit 1 = none pending") + out["migrations_pending"] = migrate + for check in ("finalize-user", "first-run-user"): + out[f"omarchy_done_{check}"] = tool( + ["omarchy-done", "check", check], redactor, + label=f"omarchy-done check {check}", timeout=30) + return out + + +def section_security(redactor): + out = {"available": True} + out["setup_conf_present"] = os.path.exists("/etc/omarchy-mac-setup.conf") + out["setup_sudoers_present"] = os.path.exists("/etc/sudoers.d/01-omarchy-mac-setup") + # Expected True (nonzero exit) after cleanup: passwordless sudo gone. + sudo_n = tool(["sudo", "-n", "true"], redactor, + label="sudo -n true (passwordless probe)", timeout=15) + sudo_n["expected_after_cleanup"] = "non-zero exit" + out["passwordless_sudo_probe"] = sudo_n + out["sshd_enabled"] = tool(["systemctl", "is-enabled", "sshd"], redactor, + label="is-enabled sshd", timeout=15) + out["sshd_socket_enabled"] = tool(["systemctl", "is-enabled", "sshd.socket"], + redactor, label="is-enabled sshd.socket", + timeout=15) + out["firewall"] = tool(["nft", "list ruleset"], redactor, + label="nft list ruleset", timeout=30) + out["user_journal_warnings"] = tool( + ["journalctl", "--user", "-b", "-p", "warning", "--no-pager"], redactor, + label="journalctl --user -b -p warning", timeout=60) + return out + + +def section_macos(redactor, from_file): + if not from_file: + return {"available": False, + "error": "macOS-side output is collected before install; " + "rerun with --from-macos FILE (system_profiler " + "SPHardwareDataType, sw_vers, diskutil list)"} + data = read_path(redactor, from_file, max_chars=200_000) + data["source"] = redactor.apply(from_file) + data["section"] = "pasted macOS baseline (checklist section 2/3)" + return data + + +# --- hardware presence ------------------------------------------------------ + +def section_hardware(redactor): + """Machine-observable hardware presence, one record per probe. + + Presence is NOT function. A connector, device, or node appearing here + never marks the matching wiki feature as working; the only source for + feature verdicts is the interview's hardware answers (FEATURE_ITEMS). + """ + out = {"available": True, + "note": "presence records only; feature verdicts come from the " + "interview, never from this section"} + connectors = [] + try: + for name in sorted(os.listdir("/sys/class/drm"))[:64]: + if not re.fullmatch(r"(card\d+-)?[A-Za-z]+(-[A-Za-z0-9.]+)+", name) \ + or not os.path.isdir(os.path.join("/sys/class/drm", name)): + continue + rec = {"connector": name} + try: + with open(os.path.join("/sys/class/drm", name, "status"), + "r") as fh: + rec["status"] = fh.read().strip() + except OSError: + pass + connectors.append(rec) + except OSError: + pass + out["drm_connectors"] = connectors + out["audio_cards"] = read_path(redactor, "/proc/asound/cards", + max_chars=8000) + out["usb_devices"] = tool(["lsusb"], redactor, label="lsusb", timeout=20) + tb = [] + try: + for dev in sorted(os.listdir("/sys/bus/thunderbolt/devices"))[:16]: + rec = {"device": dev} + for field in ("device_name", "vendor_name"): + val = sox_field(os.path.join( + "/sys/bus/thunderbolt/devices", dev, field)) + if val: + rec[field] = val + tb.append(rec) + except OSError: + pass + out["thunderbolt_devices"] = tb + wifi = [] + try: + for net in sorted(os.listdir("/sys/class/net"))[:16]: + if os.path.isdir(os.path.join("/sys/class/net", net, "wireless")) \ + or os.path.isdir(os.path.join("/sys/class/net", net, + "phy80211")): + wifi.append(net) + except OSError: + pass + out["wireless_interfaces"] = wifi + out["rfkill"] = tool(["rfkill", "list"], redactor, label="rfkill list", + timeout=15) + out["bluetooth"] = tool(["bluetoothctl", "show"], redactor, + label="bluetoothctl show", timeout=15) + cams = [] + try: + for vdev in sorted(os.listdir("/sys/class/video4linux"))[:16]: + name = sox_field(os.path.join("/sys/class/video4linux", vdev, + "name")) + cams.append({"device": vdev, "name": name}) + except OSError: + pass + out["cameras"] = cams + inputs = [] + try: + with open("/proc/bus/input/devices", "r", errors="replace") as fh: + for line in fh: + if line.startswith("N: Name="): + inputs.append(redactor.apply(line.split("=", 1)[1].strip())) + except OSError: + pass + out["input_names"] = inputs[:64] + out["suspend_states"] = read_path(redactor, "/sys/power/state", + max_chars=1000) + out["suspend_modes"] = read_path(redactor, "/sys/power/mem_sleep", + max_chars=1000) + return out + + +# --- interview ------------------------------------------------------------- + +# Human-judgment items from the checklist, verbatim in intent. The script +# cannot see a screen or press a key; these are answered by the volunteer. +INTERVIEW_ITEMS = [ + ("reboot-a", "Boot-layout reboot: Apple boot -> m1n1 -> U-Boot -> Linux " + "menu completed normally"), + ("reboot-a", "Setup resumed automatically on tty1 (no blank screen/cursor)"), + ("reboot-a", "/boot moved to a separate unencrypted partition"), + ("reboot-a", "Installer advanced to encryption instead of repeating " + "boot-layout"), + ("reboot-b", "Disk-passphrase prompt visible and accepted input"), + ("reboot-b", "Console keymap typed the intended passphrase correctly"), + ("reboot-b", "cryptsetup reencrypt progress was visible"), + ("reboot-b", "Encryption finished without unexplained reboot/hang/loop"), + ("reboot-b", "New passphrase unlocked root on next boot"), + ("reboot-b", "Setup resumed automatically after encryption"), + ("reboot-c", "Clone, package install, system setup, user setup completed"), + ("reboot-c", "Network loss or mirror errors were clearly reported"), + ("reboot-c", "Required package failures were not reported as optional skips"), + ("reboot-c", "Final reboot reached SDDM or desktop"), + ("reboot-c", "First graphical boot did not conflict with the tty1 setup service"), + ("reboot-c", "Guided installer did not start again after completion"), + ("desktop", "Login succeeded with the created user"), + ("desktop", "Desktop rendered correctly (notch-aware layout on MacBooks)"), + ("desktop", "First-run setup completed once, no loop"), + ("desktop", "Menu, launcher, terminal, browser, file manager, settings open"), + ("desktop", "Wi-Fi and DNS work"), + ("desktop", "Built-in keyboard, trackpad, brightness keys, backlight work"), + ("desktop", "Audio plays at modest volume with speaker protection active"), + ("desktop", "Headphones and microphone work (if available)"), + ("desktop", "Lock and unlock work"), + ("desktop", "Suspend/resume works once; Wi-Fi and input recover"), + ("desktop", "Theme change leaves the desktop usable"), + ("persist", "Second login: first-run prompts/notifications do not repeat"), + ("persist", "Normal reboot: unlock, login, desktop, Wi-Fi, audio protection OK"), + ("persist", "Cold boot after 15s power-off succeeded"), + ("persist", "sudo requires the user's password"), + ("persist", "Temporary setup files/services/passwordless privileges retired"), + ("persist", "Root access matches the --keep-root-password choice"), + ("persist", "SSH not silently exposed through the firewall"), +] + +VALID_ANSWERS = ("PASS", "FAIL", "SKIP", "NA") + +# One separate answer per wiki hardware-matrix feature +# (Apple-Silicon-hardware.md). The machine hardware section records +# presence only; only the volunteer can say a feature works, so each +# feature keeps its own human answer in the wiki's own vocabulary, and +# detected hardware is never converted into a working verdict. +FEATURE_ITEMS = ( + "internal display", "HDMI display", "USB-C DisplayPort display", + "USB devices", "Thunderbolt dock", "Wi-Fi", "Bluetooth", + "speakers", "headphones", "microphone", "HDMI audio", + "suspend", "camera", "Touch ID", "keyboard", "trackpad", + "GPU inference", "Neural Engine", +) +# Features usually exercised through a peripheral: the note field records +# what was attached (model and connection), so the wiki keeps that detail. +FEATURE_PERIPHERAL = ("HDMI display", "USB-C DisplayPort display", + "USB devices", "Thunderbolt dock", "headphones", + "microphone", "HDMI audio", "camera") +FEATURE_ANSWERS = ("WORKS", "LIMITATION", "BROKEN", "UNKNOWN", "NA") +FEATURE_SYMBOLS = {"WORKS": "✓", "LIMITATION": "!", "BROKEN": "✕", + "NA": "n/a"} + + +def feature_symbol(answer): + """Map a stored answer to the wiki symbol; unrecorded is '?', which in + the wiki means exactly 'not known yet'.""" + if not answer: + return "?" + return FEATURE_SYMBOLS.get(answer, "?") + + +def parse_answer(raw, prior, vocab): + """Split one input line into (answer, note) under `vocab`. + + 'ANSWER; note text'. Blank keeps `prior`. Returns (None, None) when + the answer is not in vocab, so the caller can reprompt. + """ + raw = (raw or "").strip() + head, _, note = raw.partition(";") + answer = head.strip().upper() or prior + if answer and answer not in vocab: + return None, None + return answer, (note.strip() or None) + + +def interview_items(): + """Every interview item as (group, item, vocab, is_feature).""" + for group, item in INTERVIEW_ITEMS: + yield group, item, VALID_ANSWERS, False + for item in FEATURE_ITEMS: + yield "hardware", item, FEATURE_ANSWERS, True + + +def _save_answers(path, answers, notes): + """Persist the merged answer set, preserving every existing key. + + Old keys (including combined-question keys from earlier collector + versions) are kept verbatim; split per-feature keys start empty and + only ever receive what the volunteer answered, so a combined PASS + from an older run never transfers to a split feature. Notes ride + along so a normalized "ANSWER; note" value round-trips. + """ + try: + with open(path, "w") as fh: + json.dump({"answers": answers, "notes": notes}, fh, + indent=2, sort_keys=True) + fh.write("\n") + except OSError: + pass + + +def section_interview(redactor, answers_path): + out = {"available": True, "interactive": False, "answers": {}, + "notes": {}} + prior_answers = {} + prior_notes = {} + if os.path.exists(answers_path): + stored = {} + try: + with open(answers_path, "r") as fh: + stored = json.load(fh) + except (OSError, ValueError): + stored = {} + prior_answers = stored.get("answers", {}) + prior_notes = {k: redactor.apply(v) for k, v in + stored.get("notes", {}).items()} + for group, item, vocab, _is_feature in interview_items(): + key = f"{group}::{item}" + raw = prior_answers.get(key) + if not isinstance(raw, str) or ";" not in raw: + continue + answer, note = parse_answer(raw, "", vocab) + if answer and note: + prior_answers[key] = answer + prior_notes[key] = redactor.apply(note) + out["answers"] = dict(prior_answers) + out["notes"] = prior_notes + if not sys.stdin.isatty(): + out["note"] = ("not a TTY; holding existing answers only. Rerun with " + "--interview on the console to record " + "PASS/FAIL/SKIP/NA per checklist item and " + "WORKS/LIMITATION/BROKEN/UNKNOWN/NA per hardware " + "feature") + return out + out["interactive"] = True + items = list(interview_items()) + print(f"\n=== E2E interview: {len(items)} items " + f"({len(INTERVIEW_ITEMS)} checklist + {len(FEATURE_ITEMS)} " + f"hardware features). Answer with the shown vocabulary, then an " + f"optional '; note'. Blank keeps the previous answer. ===\n") + for group, item, vocab, is_feature in items: + key = f"{group}::{item}" + prior = out["answers"].get(key, "") + hint = "/".join(vocab) + if is_feature and item in FEATURE_PERIPHERAL: + hint += "; note the peripheral model and connection" + while True: + try: + raw = input(f"[{group}] {item}\n {hint}" + f"{f' (now: {prior})' if prior else ''}: ") + except EOFError: + raw = "" + answer, note = parse_answer(raw, prior, vocab) + if answer is not None: + break + print(f" unrecognized {raw.strip()!r}; use one of " + f"{', '.join(vocab)} (optionally 'ANSWER; note text')") + if answer: + out["answers"][key] = answer + if note: + out["notes"][key] = redactor.apply(note) + _save_answers(answers_path, out["answers"], out["notes"]) + return out + + +# --- report ---------------------------------------------------------------- + +REPORT_TEMPLATE_ITEMS = [ + ("Fresh Asahi baseline", "auto+human"), + ("Boot-layout stage", "reboot-a"), + ("Encryption stage", "reboot-b"), + ("Omarchy install stage", "reboot-c"), + ("First login", "desktop"), + ("Second login", "persist"), + ("Normal reboot", "persist"), + ("Cold boot", "persist"), + ("Hardware smoke test", "desktop"), + ("Security cleanup", "security"), +] + + +def stage_verdict(answers, group): + have = [answers.get(f"{g}::{item}") for g, item in INTERVIEW_ITEMS if g == group] + valid = [answer for answer in have if answer in VALID_ANSWERS] + if not valid: + return "UNRECORDED" + if "FAIL" in valid: + return "FAIL" + if len(valid) != len(have): + return "PARTIAL" + effective = [answer for answer in valid if answer != "NA"] + if not effective: + return "NA" + if all(answer == "PASS" for answer in effective): + return "PASS" + if all(answer == "SKIP" for answer in effective): + return "SKIP" + return "PARTIAL" + + +def render_feature_matrix(answers, notes): + """The wiki hardware matrix, one line per feature. + + Only recorded human answers appear as verdicts; an unrecorded + feature renders '?' (the wiki's own 'not known yet') plus the + machine-presence pointer, so detection can never become 'working'. + """ + lines = ["Hardware features (wiki matrix; ✓ works · ! limitation · " + "✕ broken · ? not known · n/a not built in):"] + for feature in FEATURE_ITEMS: + key = f"hardware::{feature}" + answer = answers.get(key) + if answer not in FEATURE_ANSWERS: + answer = None + cell = feature_symbol(answer) + line = f" {feature}: {answer or 'UNRECORDED'} ({cell})" + note = notes.get(key) + if note: + line += f" — {note}" + lines.append(line) + return lines + + +def render_report_md(identity, files): + """The checklist report template, pre-filled from machine evidence.""" + state = _member(files, "install-state.json") + base = _member(files, "baseline.json") + sec = _member(files, "security.json") + interview = _member(files, "interview.json") + # Machine identity is recorded by the identity section, not the + # parent's prompt-answer hint. + machine = (_member(files, "identity.json").get("machine") + or identity.get("machine") or {}) + answers = interview.get("answers", {}) + notes = interview.get("notes", {}) + + lines = ["", "## E2E report (auto-filled where marked [auto])", ""] + lines.append("```text") + lines.append(f"Test ID: {identity.get('test_id') or ''}") + lines.append(f"Tester: {identity.get('tester') or ''}") + lines.append(f"Date/timezone: {identity.get('date_timezone') or ''}") + lines.append(f"Mac model / Apple identifier / SoC / RAM: " + f"{identity.get('mac_model') or ''} / " + f"{identity.get('model_identifier') or ''} / " + f"{identity.get('soc') or ''} / {identity.get('ram_ssd') or ''}") + lines.append(f"Machine [auto]: {machine.get('marketing_model') or 'unknown'}" + f"; board {machine.get('board_compatible') or 'unknown'}" + f"; SoC {machine.get('soc') or 'unknown'}" + f"; {machine.get('os') or 'os unknown'}" + f"; kernel {machine.get('kernel') or 'unknown'}" + f"; collected {machine.get('collected_at_utc') or 'unknown'}") + lines.append(f"macOS version: {identity.get('macos_version') or ''}") + lines.append(f"Asahi image and filesystem: {identity.get('asahi_image') or ''}") + lines.append(f"Encryption and keymap: " + f"{identity.get('install_path') or ''} / " + f"{identity.get('keyboard_layout') or ''}") + lines.append(f"Omarchy repo / ref / installed version: " + f"{identity.get('omarchy_repo_ref') or ''} / " + f"{(state.get('omarchy_version') or {}).get('stdout', '').strip() or ''}") + lines.append(f"Test command: {identity.get('target_commit') or ''}") + root_enc = (base.get("storage_facts") or {}).get("root_encrypted") + lines.append(f"root_encrypted [auto]: {root_enc if root_enc is not None else 'unknown'}") + lines.append(f"boot_separate [auto]: " + f"{(base.get('storage_facts') or {}).get('boot_separate', 'unknown')}") + for label, group in REPORT_TEMPLATE_ITEMS: + if group == "auto+human": + continue + if group == "security": + present_conf = sec.get("setup_conf_present") + present_sudo = sec.get("setup_sudoers_present") + lines.append(f"{label}: cleanup_conf={present_conf} " + f"cleanup_sudoers={present_sudo} " + f"(interview: {stage_verdict(answers, 'persist')})") + continue + lines.append(f"{label}: {stage_verdict(answers, group)}") + lines += render_feature_matrix(answers, notes) + lines.append("Overall: (PASS / FAIL / BLOCKED — volunteer decides)") + lines.append("First failing checkpoint:") + lines.append("Expected:") + lines.append("Actual:") + lines.append("Reproduction steps:") + lines.append("Warnings / skipped packages:") + lines.append("Logs, photos, or video: (see archive)") + lines.append("Related issue/PR:") + lines.append("Notes and clearly labelled hypotheses:") + lines.append("```") + for key, note in sorted(notes.items()): + lines.append(f"note [{key}]: {note}") + return "\n".join(lines) + + +def _member(files, name): + try: + return json.loads(files[name].decode("utf-8")) + except (KeyError, ValueError): + return {} + + +# --- harness --------------------------------------------------------------- + +def section_child(name, ws, args): + redactor = Redactor() + try: + if name == "identity": + data = section_identity(redactor, args.identity_file) + elif name == "baseline": + data = section_baseline(redactor) + elif name == "mlx": + data = collect_quick.collect() + data["section"] = "mlx-omarchy quick capability report (vendored)" + elif name == "hardware": + data = section_hardware(redactor) + elif name == "install-logs": + data = section_install_logs(redactor) + elif name == "boot": + data = section_boot(redactor) + elif name == "install-state": + data = section_install_state(redactor) + elif name == "security": + data = section_security(redactor) + elif name == "macos": + data = section_macos(redactor, args.from_macos) + elif name == "interview": + data = section_interview(redactor, args.answers_file) + else: + data = {"available": False, "error": f"unknown section {name}"} + except Exception as exc: + data = {"available": False, + "error": redactor.apply(f"{type(exc).__name__}: {exc}")} + data = redactor.apply_value(data) + if isinstance(data, dict): + data["_redaction"] = redactor.counts + with open(os.path.join(ws, f"{name}.json"), "wb") as fh: + fh.write(json_bytes(data)) + + +def run_sections(ws, args, redactor): + for name in SECTION_ORDER: + if name in args.skip: + continue + if args.interview and sys.stdin.isatty() and name in ("identity", "interview"): + section_child(name, ws, args) + continue + timeout = args.timeout or SECTION_TIMEOUTS[name] + rec = run_tool( + [sys.executable, os.path.abspath(__file__), "--_section", name, + "--_workspace", ws, "--_identity", args.identity_file, + "--_answers", args.answers_file, + "--_from_macos", args.from_macos or ""], + redactor, label=f"section:{name}", timeout=timeout) + if not os.path.exists(os.path.join(ws, f"{name}.json")): + with open(os.path.join(ws, f"{name}.json"), "wb") as fh: + fh.write(json_bytes({ + "available": False, + "error": rec["error"] or f"exit {rec['exit_code']}", + "stderr": rec["stderr"][-2000:], + })) + + +def assemble_files(ws, identity, redactor): + files = {} + unavailable = [] + redaction = {} + for name in SECTION_ORDER: + if name == "macos" and not identity.get("from_macos"): + continue # optional section; absent unless requested + path = os.path.join(ws, f"{name}.json") + data = read_text(path) + if data is None: + data = json_bytes({"available": False, + "error": "section produced no result"}) + unavailable.append(name) + else: + try: + parsed = json.loads(data) + if parsed.get("available") is False: + unavailable.append(name) + for kind, count in parsed.get("_redaction", {}).items(): + redaction[kind] = redaction.get(kind, 0) + count + except ValueError: + pass + files[f"{name}.json"] = data if isinstance(data, bytes) \ + else data.encode("utf-8") + # The checklist itself travels with the evidence. + checklist = os.path.join(REPO, "docs", "omarchy-mac-e2e-volunteer-checklist.md") + checklist_data = read_text(checklist) + if checklist_data is not None: + files["omarchy-mac-e2e-volunteer-checklist.md"] = \ + checklist_data if isinstance(checklist_data, bytes) \ + else checklist_data.encode("utf-8") + return files, unavailable, redaction + + +def vulkan_summary(quick): + """One honest line about the Vulkan probe. + + A missing vulkaninfo binary is a missing probe, not an unsupported + GPU: PR464 review showed 'Vulkan: unavailable' reading as a graphics + failure on a machine whose desktop rendered fine. Falls back to the + installed driver package when the probe tool is absent. + """ + mesa = quick.get("mesa") or {} + gpu = mesa.get("gpu") or {} + if gpu: + return (f"{gpu.get('deviceName') or 'unknown'} / " + f"{gpu.get('driverName') or 'unknown'}") + if not mesa: + return "not probed (no mlx section in this run)" + rec = mesa.get("vulkaninfo") or {} + if rec.get("available") is False or rec.get("error") == "not-found": + pkg = (quick.get("mesa_package") or {}).get("vulkan-asahi") or {} + driver = pkg.get("stdout", "").strip() \ + if pkg.get("exit_code") == 0 else "" + detail = f"driver package {driver}" if driver \ + else "driver package unverified" + return (f"probe missing (vulkaninfo not installed; this is not a " + f"GPU or driver verdict) — {detail}") + return "unavailable" + + +def logs_presence_line(logs): + """The install-logs cover line: absence never reads as failure.""" + tails = [p for p, rec in (logs.get("logs") or {}).items() + if rec.get("present")] + if tails: + return f"Install logs present: {', '.join(tails)}" + return ("Install logs present: none (an absent log is not a hardware " + "or install failure; see install-logs.json absence_notes — " + "some logs are only written after certain stages, and the " + "guided-setup log is never written to file at all)") + + +def build_submission(manifest, files, identity): + base = _member(files, "baseline.json") + quick = _member(files, "mlx.json") + host = quick.get("host") or {} + dt = host.get("devicetree") or {} + mlx = quick.get("mlx") or {} + logs = _member(files, "install-logs.json") + state = _member(files, "install-state.json") + sec = _member(files, "security.json") + facts = base.get("storage_facts") or {} + omarchy_v = (state.get("omarchy_version") or {}).get("stdout", "").strip() + lines = ["## Omarchy Mac E2E evidence archive", ""] + lines.append(f"Tester: {identity.get('tester') or 'UNRECORDED'}; " + f"Test ID: {identity.get('test_id') or 'UNRECORDED'}; " + f"SoC: {identity.get('soc') or 'UNRECORDED'}; " + f"model identifier: {identity.get('model_identifier') or 'UNRECORDED'}") + lines.append(f"Install path: {identity.get('install_path') or 'UNRECORDED'}; " + f"Asahi image: {identity.get('asahi_image') or 'UNRECORDED'}") + lines.append(f"root_encrypted: {facts.get('root_encrypted')}; " + f"boot_separate: {facts.get('boot_separate')}; " + f"fresh_marker(setup conf present): {facts.get('fresh_marker', {}).get('setup_conf_present')}") + lines.append(f"Installed omarchy: {omarchy_v or 'not recorded'}") + lines.append(f"Device: {dt.get('model') or 'unknown'} " + f"({dt.get('compatible') or 'unknown compatible'}); " + f"Vulkan: {vulkan_summary(quick)}") + dists = mlx.get("distributions") or {} + lines.append(f"mlx-omarchy: {dists.get('mlx-omarchy') or 'not installed'}, " + f"default device {mlx.get('default_device') or 'unavailable'}") + pinned = (state.get("pinned_packages") or {}).get("stdout", "").strip() + lines.append(f"Pinned packages: {pinned or 'not recorded'}") + lines.append(f"setup conf present: {sec.get('setup_conf_present')}; " + f"setup sudoers present: {sec.get('setup_sudoers_present')}") + lines.append(logs_presence_line(logs)) + lines.append(f"Sections unavailable: " + f"{', '.join(manifest.get('sections_unavailable', [])) or 'none'}") + lines.append(f"Redaction applied before writing: " + f"{json.dumps(manifest.get('redaction_summary', {}), sort_keys=True)}") + lines += ["", "Attach this archive to the test ID / tracking issue with the " + "completed checklist report (submission.md carries the " + "pre-filled template).", ""] + lines.append(render_report_md(identity, files)) + return "\n".join(lines) + + +def finalize(files, unavailable, redaction, archive_name, identity): + listed = {name: data for name, data in files.items() + if name not in ("manifest.json", "submission.md")} + quick = _member(files, "mlx.json") + manifest = build_manifest(archive_name, listed, extra={ + "tool_kind": "omarchy-mac-e2e", + "system": platform.system(), + "machine": platform.machine(), + "sections_unavailable": unavailable, + "redaction_summary": dict(sorted(redaction.items())), + "schema_note": "one file per section; bounded command records carry " + "argv, exit code, capped redacted output; the schema " + "does not change with the sharing path", + }) + files["submission.md"] = build_submission( + manifest, files, identity).encode("utf-8") + manifest = build_manifest(archive_name, files, extra=manifest) + files["manifest.json"] = json_bytes(manifest) + payload = build_payload("omarchy-mac-e2e", quick, manifest, + redactor=Redactor()) + facts = (files.get("baseline.json", b"{}") and + json.loads(files.get("baseline.json", b"{}").decode("utf-8") or "{}") + ).get("storage_facts") or {} + payload.update({ + "test_id": (identity.get("test_id") or None), + "install_path": (identity.get("install_path") or None), + "asahi_image": (identity.get("asahi_image") or None), + "encryption": facts.get("root_encrypted"), + "boot_separate": facts.get("boot_separate"), + "overall": None, + }) + return manifest, archive_bytes(files), payload + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--out", metavar="FILE", + help="write the archive after the preview (default: " + "preview only)") + ap.add_argument("--submit", metavar="URL", default=None, + help="upload the redacted archive to an e2e collection " + "endpoint speaking the community-data protocol") + ap.add_argument("--interview", action="store_true", + help="record identity, checklist verdicts, and hardware " + "feature results on the console") + ap.add_argument("--identity-file", default="e2e-identity.json", + help="test-assignment answers are reused from this file " + "(default: ./e2e-identity.json)") + ap.add_argument("--answers-file", default="e2e-answers.json", + help="interview answers are reused from this file " + "(default: ./e2e-answers.json)") + ap.add_argument("--from-macos", metavar="FILE", + help="pasted macOS-side output (system_profiler, sw_vers, " + "diskutil list) to include") + ap.add_argument("--workspace", metavar="DIR", + help="keep the section files in DIR instead of a temp dir") + ap.add_argument("--skip", default="", + help="comma-separated sections to skip") + ap.add_argument("--timeout", type=int, default=None, + help="override the per-section timeout in seconds") + ap.add_argument("--_section", help=argparse.SUPPRESS) + ap.add_argument("--_workspace", help=argparse.SUPPRESS) + ap.add_argument("--_identity", help=argparse.SUPPRESS) + ap.add_argument("--_answers", help=argparse.SUPPRESS) + ap.add_argument("--_from_macos", help=argparse.SUPPRESS) + args = ap.parse_args() + + if args._section: + # The parent passes real paths via the hidden flags; without + # this reconciliation the child would fall back to the defaults + # (./e2e-answers.json) and silently hold nothing when the + # volunteer used --answers-file/--identity-file/--from-macos. + if args._answers: + args.answers_file = args._answers + if args._identity: + args.identity_file = args._identity + if args._from_macos: + args.from_macos = args._from_macos + sys.stdin = open(os.devnull) + section_child(args._section, args._workspace, args) + return + + skip = {s.strip() for s in args.skip.split(",") if s.strip()} + args.skip = skip + args.from_macos = os.path.abspath(args.from_macos) if args.from_macos else None + args.identity_file = os.path.abspath(args.identity_file) + args.answers_file = os.path.abspath(args.answers_file) + + identity_hint = {"from_macos": args.from_macos} + + keep = False + if args.workspace: + os.makedirs(args.workspace, exist_ok=True) + ws = args.workspace + keep = True + else: + ws = tempfile.mkdtemp(prefix="omarchy-mac-e2e-") + + pre_redactor = Redactor() + run_sections(ws, args, pre_redactor) + files, unavailable, redaction = assemble_files(ws, identity_hint, pre_redactor) + for kind, count in pre_redactor.counts.items(): + redaction[kind] = redaction.get(kind, 0) + count + archive_name = os.path.basename(args.out) if args.out \ + else "omarchy-mac-e2e.tar.gz" + manifest, data, payload = finalize(files, unavailable, redaction, + archive_name, _member(files, "identity.json")) + print(json.dumps(manifest, indent=2, sort_keys=True)) + print(f"[preview] archive: {archive_name} bytes={len(data)} " + f"sha256={hashlib.sha256(data).hexdigest()}") + if not args.out: + print("[preview] nothing written, nothing uploaded; " + "rerun with --out FILE to write these exact bytes") + if not keep: + shutil.rmtree(ws, ignore_errors=True) + return + with open(args.out, "wb") as fh: + fh.write(data) + base = args.out.removesuffix(".tar.gz") if args.out.endswith(".tar.gz") \ + else os.path.splitext(args.out)[0] + submission = base + ".submission.md" + with open(submission, "wb") as fh: + fh.write(files["submission.md"]) + print(f"[receipt] wrote {args.out} ({len(data)} bytes, " + f"sha256={hashlib.sha256(data).hexdigest()})") + print(f"[receipt] wrote {submission} (paste-ready cover text)") + if args.submit and args.out: + import collect_submit + try: + receipt = collect_submit.submit(args.submit, data, payload, + token=collect_submit.token_from_env()) + print(f"[receipt] public URL: {receipt['url']} " + f"(deduplicated={receipt['deduplicated']})") + except collect_submit.SubmitError as exc: + print(f"[submit] FAILED: {exc}", file=sys.stderr) + print(f"[submit] local output preserved: {args.out}", file=sys.stderr) + if not keep: + shutil.rmtree(ws, ignore_errors=True) + raise SystemExit(4) + else: + print("[receipt] done; nothing was uploaded") + if not keep: + shutil.rmtree(ws, ignore_errors=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/collect_macos.py b/scripts/collect_macos.py new file mode 100644 index 000000000000..5a3ab81c03ea --- /dev/null +++ b/scripts/collect_macos.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +"""Native macOS facts for the community collectors. No MLX install required.""" + +import json +import platform + +try: + import bench_matrix +except ModuleNotFoundError: # vendored without the mlx-omarchy bench harness + bench_matrix = None +from collect_common import run_tool, run_python_probe + + +def not_applicable(): + return {"available": False, "error": "not applicable to native macOS MLX"} + + +# Runs via run_python_probe on the Mac. Read-only: ioreg queries and one +# best-effort powermetrics sample. Structured so every string that +# reaches the report has passed the Redactor back in the parent. +ANE_PROBE_CODE = r""" +import json, plistlib, re, subprocess + +out = {"available": False, "instances": [], "ane_nodes": [], + "dart_nodes": [], + "coreml": {"available": False, "compute_units": None, "error": None}, + "powermetrics": {"available": False, "power_mw": None, + "error": None}, + "truncated": []} + + +def _text(value): + if isinstance(value, bytes): + value = value.split(b"\x00")[0].decode("utf-8", "replace") + return str(value)[:128] if value is not None else None + + +def _compatible(node): + raw = node.get("compatible") + if isinstance(raw, bytes): + texts = [t.decode("utf-8", "replace") for t in raw.split(b"\x00") + if t] + return texts[:8] + return None + + +def _reg(node): + raw = node.get("reg") or node.get("IODeviceMemory") + if isinstance(raw, bytes): + if len(raw) > 64: + out["truncated"].append("reg_bytes:%s" % _text( + node.get("name"))) + raw = raw[:64] + return raw.hex() + return None + + +def _keep(node): + # Keys the payload schema whitelists; AAPL,phandle is carried as + # `phandle` below. + keys = ("name", "compatible", "reg", "IODeviceMemory", + "IOInterruptControllers", "IOInterruptSpecifiers", "IOClass") + return {k: node[k] for k in keys + if node.get(k) is not None and k != "IODeviceMemory"} + + +try: + raw = subprocess.run(["ioreg", "-a", "-rc", "H11ANEIn", "-l"], + capture_output=True, timeout=30).stdout + for node in plistlib.loads(raw): + dp = node.get("DeviceProperties") or {} + out["instances"].append({ + "name": _text(node.get("IONameMatched")), + "matched": _text(node.get("IONameMatched")), + "firmware_loaded": node.get("FirmwareLoaded") is True, + "cores": dp.get("ANEDevicePropertyNumANECores"), + "version": dp.get("ANEDevicePropertyANEVersion"), + "hw_board_type": dp.get("ANEDevicePropertyANEHWBoardType"), + "arch": _text(dp.get( + "ANEDevicePropertyTypeANEArchitectureTypeStr")), + }) + out["available"] = bool(out["instances"]) + out["instances"] = out["instances"][:8] +except Exception as exc: + out["truncated"].append("ioreg_instances:%s" % type(exc).__name__) + +try: + raw = subprocess.run(["ioreg", "-a", "-p", "IOService", "-l"], + capture_output=True, timeout=120).stdout + tree = plistlib.loads(raw) + ane_re = re.compile(r"^(ane\d*|dart-ane\d*|mapper-ane\d*)$") + stack = list(tree) if isinstance(tree, list) else [tree] + while stack: + node = stack.pop() + if not isinstance(node, dict): + continue + name = _text(node.get("name")) + if name and ane_re.match(name): + entry = _keep(node) + entry["name"] = name + entry["compatible"] = _compatible(node) + entry["reg"] = _reg(node) + for key in ("IOInterruptControllers", + "IOInterruptSpecifiers", "IOClass"): + if key in entry: + entry[key] = _text(entry[key]) + ph = node.get("AAPL,phandle") + if isinstance(ph, bytes) and len(ph) == 4: + ph = int.from_bytes(ph, "big") + entry["phandle"] = ph + (out["dart_nodes"] if name.startswith( + ("dart-", "mapper-")) else out["ane_nodes"]).append(entry) + children = node.get("IORegistryEntryChildren") + if isinstance(children, list): + stack.extend(children) + out["ane_nodes"] = out["ane_nodes"][:8] + out["dart_nodes"] = out["dart_nodes"][:8] + if len(out["ane_nodes"]) == 8 or len(out["dart_nodes"]) == 8: + out["truncated"].append("devicetree:node_cap") +except Exception as exc: + out["truncated"].append("ioreg_tree:%s" % type(exc).__name__) + +# CoreML compute-unit availability when pyobjc is present; otherwise a +# recorded miss, never a crash. +try: + import CoreML # type: ignore + from CoreML import MLComputeUnits # type: ignore + out["coreml"] = {"available": True, + "compute_units": str(MLComputeUnits.all)[:64], + "error": None} +except Exception as exc: + out["coreml"] = {"available": False, "compute_units": None, + "error": type(exc).__name__[:64]} + +# ANE power/utilization needs root; record the miss cleanly without it. +try: + proc = subprocess.run( + ["powermetrics", "--samplers", "ane_power", "-n", "1", "-i", "100"], + capture_output=True, timeout=30, text=True) + if proc.returncode != 0: + out["powermetrics"]["error"] = proc.stderr.strip()[:128] \ + or "exit %d" % proc.returncode + else: + watts = [float(m) for m in + re.findall(r"ANE Power: ([0-9.]+) mW", proc.stdout)] + out["powermetrics"] = {"available": True, + "power_mw": watts[0] if watts else None, + "error": None} +except Exception as exc: + out["powermetrics"]["error"] = type(exc).__name__[:64] + +def _plain(value): + if isinstance(value, bytes): + return _text(value) + if isinstance(value, list): + return [_plain(v) for v in value] + if isinstance(value, dict): + return {k: _plain(v) for k, v in value.items()} + return value + + +print(json.dumps(_plain(out))[:120000]) +""" + + +def probe_ane_port(redactor): + """ANE porting facts from the working macOS installation. + + The macOS equivalents of the Linux devicetree capture: the driver + instances (core count, hardware generation, firmware state), the + DT-shaped ANE provider and ANE DART/mapper nodes with their MMIO + ranges and interrupt specifiers, CoreML compute-unit availability, + and a root-gated powermetrics sample. Everything is read-only; only + powermetrics wants root, and its absence is recorded, not fatal. + """ + rec = run_python_probe(ANE_PROBE_CODE, redactor, + label="ane-port macos", timeout=180) + if rec["exit_code"] != 0 or not rec["stdout"].strip(): + return {"available": False, "macos": None, + "error": rec["error"] or rec["stderr"][:256] or + "ane probe exit %s" % rec["exit_code"]} + try: + detail = json.loads(rec["stdout"]) + except ValueError: + return {"available": False, "macos": None, "error": "bad-probe-json"} + detail = {key: detail[key] for key in + ("available", "instances", "ane_nodes", "dart_nodes", + "coreml", "powermetrics", "truncated") + if key in detail} + return {"available": bool(detail.get("available")), + "macos": redactor.apply_value(detail)} + + + +def _text(record): + return record["stdout"].strip() if record["exit_code"] == 0 else None + + +def _int(value): + return int(value) if value and str(value).isdigit() else None + + +def probe_host(redactor): + if bench_matrix is None: + return {"available": False, + "error": "bench_matrix not vendored with this collector"} + facts = bench_matrix.host_facts() + model = run_tool(["sysctl", "-n", "hw.model"], redactor, timeout=10) + active = run_tool(["sysctl", "-n", "hw.activecpu"], redactor, timeout=10) + memory = facts.get("memsize_bytes") + return { + "available": True, + "system": "Darwin", + "arch": facts.get("machine"), + "kernel_release": platform.release(), + "os": facts.get("os"), + "model": _text(model), + "chip": facts.get("chip"), + "cpu_online": _int(_text(active)), + "cpu": {"present": _int(facts.get("cores")), "hotplug_control": None}, + "memory_total_mib": memory // (1024 * 1024) if memory else None, + "gpu": facts.get("gpu"), + } + + +def measurement_context(): + if bench_matrix is None: + return {"power": None, "model_processes": None} + power = bench_matrix.power_state() + processes = bench_matrix.clean_check() + return { + "power": {key: power.get(key) for key in ("source", "percent", "charging")} + if power else None, + "model_processes": { + "status": processes["status"], + "scanned": processes["scanned"], + "matched_count": len(processes["matched"]), + }, + "limits": "Process scan covers known model tools only. Other GPU activity " + "and temperature are not measured. Timings are observations, " + "not a controlled performance comparison.", + } diff --git a/scripts/collect_quick.py b/scripts/collect_quick.py new file mode 100755 index 000000000000..545a856fdcaf --- /dev/null +++ b/scripts/collect_quick.py @@ -0,0 +1,726 @@ +#!/usr/bin/env python3 +"""Collect a fast, privacy-safe capability report for mlx-omarchy. + +The report answers the questions a maintainer asks first: which Apple +Silicon machine, which kernel, which Mesa/Honeykrisp Vulkan stack, is the +ANE visible, and which mlx-omarchy wheel is installed. It also records +the CPU topology (present cores versus online), the boot-chain firmware +identity from the devicetree /chosen node, the redacted kernel command +line, whether the booted devicetree carries an ANE node, and the full +driver-port devicetree capture (ane node, DARTs, PMGR domains, AIC) +for porting omarchy-ane to a new SoC. It finishes +in seconds, downloads nothing, and never touches the network. + +On macOS, it records native Mac, OS, and Metal facts instead of Linux +driver and devicetree diagnostics. Native MLX is optional. + +Personal data never reaches the output: every captured command output and +every free-text field passes through the shared Redactor, and the script +never reads serial numbers, machine IDs, or network configuration at all. + +Usage: + python3 scripts/collect_quick.py # JSON on stdout + python3 scripts/collect_quick.py --out f.json + +Section shape (schema_version 1): every section carries "available"; a +missing tool or an import failure is recorded data, not an error. The +script exits 0 when the report was produced, 1 on an internal failure. +""" + +import argparse +import json +import os +import platform +import re +import shutil +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import collect_macos +from collect_common import (SCHEMA_VERSION, Redactor, build_payload, + dump_json, json_bytes, run_tool) + +DT_BASE = "/sys/firmware/devicetree/base" + + +def probe_host(redactor): + if platform.system() == "Darwin": + return collect_macos.probe_host(redactor) + out = {"available": True} + info = os.uname() + out["arch"] = info.machine + out["kernel_release"] = info.release + try: + out["cpu_online"] = len(os.sched_getaffinity(0)) + except AttributeError: + out["cpu_online"] = os.cpu_count() + try: + out["page_size_bytes"] = os.sysconf("SC_PAGESIZE") + except (ValueError, OSError): + out["page_size_bytes"] = None + mem = _mem_total() + out["memory_total_mib"] = mem + out["devicetree"] = _devicetree(redactor) + out["cpu"] = _cpu_topology() + out["boot"] = _boot_chain(redactor) + out["cmdline"] = _kernel_cmdline(redactor) + out["core_shortfall"] = _core_shortfall(out["cpu"], + out["cmdline"] or "") + return out + + +def _mem_total(): + try: + with open("/proc/meminfo", "r", encoding="utf-8") as fh: + for line in fh: + if line.startswith("MemTotal:"): + return int(line.split()[1]) // 1024 + except (OSError, ValueError, IndexError): + pass + return None + + +def _devicetree(redactor): + """Machine model and chip compatible strings; never the serial.""" + out = {"model": None, "compatible": None} + model = _read_dt_file("model") + if model: + out["model"] = redactor.apply(model.strip("\x00\n")) + compat = _read_dt_file("compatible") + if compat: + parts = [p for p in compat.split("\x00") if p] + out["compatible"] = parts + return out + + +def _read_dt_file(name, base=DT_BASE): + try: + with open(os.path.join(base, name), "rb") as fh: + return fh.read().decode("utf-8", errors="replace") + except OSError: + return None + + +CPU_SYSFS = "/sys/devices/system/cpu" + + +def _read_cpu_list(path): + """(ids, raw) from a sysfs cpu list like "0-3,8"; (None, None) absent.""" + try: + with open(path, "r", encoding="utf-8") as fh: + raw = fh.read().strip() + except OSError: + return None, None + ids = [] + for part in raw.split(","): + lo, sep, hi = part.partition("-") + try: + first = int(lo) + last = int(hi) if sep else first + except ValueError: + return [], raw + if last < first or last - first > 65535: + return [], raw + ids.extend(range(first, last + 1)) + return ids, raw + + +def _cpu_topology(base=CPU_SYSFS): + """Core counts from sysfs: the machine's real size, not the taskset. + + host.cpu_online is scheduler affinity, so a contributor pinned to one + core of eight looked identical to a one-core machine. `present` says + how many cores the machine has. `hotplug_control` records whether + cpuN/online switches exist; their absence is what spin-table bringup + looks like on Apple Silicon. + """ + out = {"present": None, "possible": None, "online": None, + "offline": None, "present_list": None, "possible_list": None, + "online_list": None, "offline_list": None, + "hotplug_control": None} + for key in ("present", "possible", "online", "offline"): + ids, raw = _read_cpu_list(os.path.join(base, key)) + if raw is not None: + out[f"{key}_list"] = raw or None + out[key] = len(ids) + try: + entries = os.listdir(base) + except OSError: + return out + out["hotplug_control"] = any( + re.fullmatch(r"cpu([1-9]\d*)", name) + and os.path.exists(os.path.join(base, name, "online")) + for name in entries) + return out + + +CHOSEN_PROPERTIES = ( + # (property under chosen, report key): boot firmware identity, never + # personal. A bootloader devicetree override (GRUB's `devicetree` + # command) REPLACES the m1n1-patched tree with a frozen snapshot, so + # these strings describe whatever tree actually booted -- the + # 2026-09-03 one-core incident came from exactly that override. + ("asahi,m1n1-stage1-version", "m1n1_stage1"), + ("asahi,m1n1-stage2-version", "m1n1_stage2"), + ("asahi,iboot1-version", "iboot1"), + ("asahi,iboot2-version", "iboot2"), + ("asahi,system-fw-version", "system_fw"), + ("asahi,os-fw-version", "os_fw"), +) + + +def _boot_chain(redactor, base=DT_BASE): + """Boot firmware identity from the live /chosen node.""" + out = {} + for prop, key in CHOSEN_PROPERTIES: + raw = _read_dt_file(os.path.join("chosen", prop), base) + out[key] = redactor.apply(raw.strip("\x00\n")) if raw else None + return out + + +def _kernel_cmdline(redactor, path="/proc/cmdline"): + """The live kernel command line, redacted. + + Carries root=UUID=... (the UUID rule replaces it) and reveals + maxcpus/nosmp clamps or a custom-devicetree boot. + """ + try: + with open(path, "r", encoding="utf-8") as fh: + raw = fh.read() + except OSError: + return None + return redactor.apply(raw.strip()) or None + + +def _core_shortfall(cpu, cmdline): + """Plain fact: fewer cores running than present, unexplained. + + Recorded only when the command line carries no maxcpus=/nosmp clamp; + a clamp is a deliberate choice, not a failure. Numbers, not alarms. + """ + present = cpu.get("present") + online = cpu.get("online") + if not isinstance(present, int) or not isinstance(online, int): + return None + if present <= online: + return None + if cmdline and re.search(r"\bmaxcpus=\d+\b|\bnosmp\b", cmdline): + return None + return {"present": present, "online": online} + + +def _ane_devicetree(base=DT_BASE): + """ANE node visibility in the booted devicetree, unlike /dev/ane. + + Packaged t8103 dtbs ship no ane node; a node appears only when the + bootloader overrides the tree. This answers whether the running + kernel was even offered an ANE by its boot chain. + """ + out = {"node": False, "compatible": None} + matches = [] + for dirpath, _dirs, _files in os.walk(base): + named = bool(re.search(r"(?:^|/)ane(?:@[0-9a-f]+)?$", dirpath)) + tokens = [t for t in (_read_dt_file("compatible", dirpath) or "") + .split("\x00") if t] + hit = [t for t in tokens if t == "apple,ane" or t.endswith("-ane")] + if named or hit: + matches.extend(hit or tokens or [os.path.basename(dirpath)]) + if matches: + out["node"] = True + out["compatible"] = sorted(set(matches))[:8] + return out + +def _read_dt_raw(name, base=DT_BASE): + """Raw property bytes; None when absent.""" + try: + with open(os.path.join(base, name), "rb") as fh: + return fh.read() + except OSError: + return None + + +def _dt_strings(raw): + """Null-terminated string list from a devicetree property blob.""" + parts = [p for p in raw.split(b"\x00") if p] + try: + texts = [p.decode("utf-8") for p in parts] + except UnicodeDecodeError: + return None + if any(not t.isprintable() for t in texts): + return None + return texts + + +def _dt_u32s(raw): + """Big-endian u32 cell list from a devicetree property blob.""" + if len(raw) % 4 or not raw: + return None + return [int.from_bytes(raw[i:i + 4], "big") + for i in range(0, len(raw), 4)] + + +def _dt_reg(raw, base): + """reg as ["0xADDR/0xSIZE", ...] using the node's own cell counts.""" + cells = _dt_u32s(raw) + if cells is None: + return None + + def count(name, default): + raw_n = _read_dt_raw(name, base) + vals = _dt_u32s(raw_n) if raw_n else None + return vals[0] if vals else default + + ac = count("#address-cells", 2) + sc = count("#size-cells", 1) + width = ac + sc + out = [] + for i in range(0, len(cells) - width + 1, width): + addr = 0 + for c in cells[i:i + ac]: + addr = (addr << 32) | c + size = 0 + for c in cells[i + ac:i + width]: + size = (size << 32) | c + out.append(f"0x{addr:x}/0x{size:x}") + return out + + +def _dt_props(node_dir, redactor, cap=16): + """Every property of one devicetree node, decoded and bounded. + + Strings stay strings, reg gets address/size decoding, everything + numeric becomes a u32 cell list. + """ + out = {} + for name in sorted(os.listdir(node_dir)): + path = os.path.join(node_dir, name) + if not os.path.isfile(path): + continue + try: + with open(path, "rb") as fh: + raw = fh.read(4096) + except OSError: + continue + if name == "reg": + value = _dt_reg(raw, node_dir) + else: + value = _dt_strings(raw) + if value is not None and len(value) == 1: + value = value[0] + elif value is None: + value = _dt_u32s(raw) + if value is None: + value = raw[:64].hex() + if isinstance(value, list): + value = value[:cap] + elif isinstance(value, str): + value = redactor.apply(value[:512]) + out[name] = value + return out + + +def _ane_port_devicetree(redactor, base=DT_BASE): + """Everything a contributor needs to port omarchy-ane to this SoC. + + Captures the ane node(s) in full (MMIO reg, reg-names, IRQs, iommus, + power-domains, status, compatible), every DART node, the PMGR + power-domain children with their labels, and the AIC compatible. + A tree with NO ane node still dumps DART/PMGR/AIC: that is exactly + what authoring the overlay requires. + """ + ane_nodes = {} + darts = {} + phandles = {} + pmgr_domains = [] + aic = None + for dirpath, dirs, _files in os.walk(base): + dirs.sort() + compat = _dt_strings(_read_dt_raw("compatible", dirpath) or b"") \ + or [] + rel = os.path.relpath(dirpath, base) + ph = _dt_u32s(_read_dt_raw("phandle", dirpath) or b"") + if ph: + phandles[ph[0]] = rel + named = bool(re.search(r"(?:^|/)ane(?:@[0-9a-f]+)?$", dirpath)) + hit = [t for t in compat if t == "apple,ane" or t.endswith("-ane")] + if named or hit: + ane_nodes[rel] = _dt_props(dirpath, redactor) + # Real trees name DART nodes `iommu@` and tag them + # `apple,-dart` (t600x drops the legacy `apple,dart` + # fallback entirely), so match on the compatible suffix, not the + # node name alone. + if any(t == "apple,dart" or t.endswith("-dart") for t in compat) \ + or re.search(r"(?:^|/)dart[0-9a-f@-]", rel): + darts[rel] = _dt_props(dirpath, redactor) + if any(t == "apple,pmgr" for t in compat): + for child in sorted(os.listdir(dirpath)): + cpath = os.path.join(dirpath, child) + if not os.path.isdir(cpath): + continue + ccompat = _dt_strings( + _read_dt_raw("compatible", cpath) or b"") or [] + label = _dt_strings(_read_dt_raw("label", cpath) or b"") + pmgr_domains.append({ + "path": os.path.relpath(cpath, base), + "label": (label or [None])[0], + "compatible": ccompat[:8], + }) + # t8103 uses "apple,aic"; t600x/t602x use "apple,-aic", + # "apple,aic2". + if aic is None and any(t in ("apple,aic", "apple,aic2") + or t.endswith("-aic") for t in compat): + aic = {"path": rel, "compatible": compat[:8]} + # Resolve iommu phandles to DART paths so the contributor does not + # have to do phandle arithmetic by hand. Each entry is one phandle + # plus #iommu-cells specifiers from the target DART. + for props in ane_nodes.values(): + iommus = props.get("iommus") + if not isinstance(iommus, list): + continue + resolved = [] + i = 0 + while i < len(iommus) and len(resolved) < 8: + cell = iommus[i] + i += 1 + if not isinstance(cell, int): + continue + target = phandles.get(cell, f"phandle:{cell}") + resolved.append(target) + dart = darts.get(target) or {} + ncells = dart.get("#iommu-cells") + if isinstance(ncells, list) and ncells and \ + isinstance(ncells[0], int): + i += ncells[0] + props["iommus_resolved"] = resolved + # Ship only the phandles the porting data actually resolves: the + # iommus / power-domains cells of the ane nodes and DARTs. The full + # map runs to hundreds of entries on t600x and blew the 64 KiB + # payload budget before the DARTs it exists to explain did. + referenced = set() + for props in list(ane_nodes.values()) + list(darts.values()): + for key in ("iommus", "power-domains"): + cells = props.get(key) + if isinstance(cells, list): + referenced.update(c for c in cells + if isinstance(c, int) and c in phandles) + return { + "ane_node_present": bool(ane_nodes), + "ane_nodes": ane_nodes, + "darts": darts, + "pmgr_domains": pmgr_domains[:64], + "aic": aic, + "phandles": {str(k): phandles[k] for k in sorted(referenced)}, + } + + +def _ane_port_runtime(redactor): + """Live runtime facts about the ane driver, redacted and bounded.""" + out = {"iomem": None, "module_version": None, "srcversion": None, + "loaded": None, "dmesg": None} + try: + with open("/proc/iomem", "r", encoding="utf-8", + errors="replace") as fh: + lines = [redactor.apply(line.rstrip("\n")[:512]) + for line in fh + if re.search(r"ane|dart", line, re.I)] + out["iomem"] = lines[:32] or None + except OSError: + pass + for key, name in (("module_version", "version"), + ("srcversion", "srcversion")): + try: + with open(os.path.join("/sys/module/ane", name), + "r", encoding="utf-8") as fh: + out[key] = redactor.apply(fh.read().strip()[:128]) or None + except OSError: + pass + try: + with open("/proc/modules", "r", encoding="utf-8") as fh: + for line in fh: + if line.startswith("ane "): + out["loaded"] = redactor.apply(line.strip()[:256]) + break + except OSError: + pass + dmesg = run_tool(["sh", "-c", + "dmesg 2>/dev/null | grep -iE 'ane|dart|pmgr' " + "| tail -n 64"], + redactor, label="dmesg ane/dart/pmgr", timeout=15) + if dmesg["exit_code"] == 0 and dmesg["stdout"].strip(): + out["dmesg"] = [redactor.apply(line[:512]) + for line in dmesg["stdout"].splitlines()[-64:]] + return out + + +def probe_ane_port(redactor): + """Driver-port capture: devicetree plus live ane driver facts.""" + if platform.system() == "Darwin": + return collect_macos.probe_ane_port(redactor) + out = {"available": True} + out["devicetree"] = _ane_port_devicetree(redactor) + out["runtime"] = _ane_port_runtime(redactor) + return out + + +def _device_blocks(text): + """Split `vulkaninfo --summary` into one dict per GPUn: block.""" + devices = [] + current = None + for line in text.splitlines(): + if re.match(r"^GPU\d+:$", line.strip()): + current = {} + devices.append(current) + continue + if current is None or "=" not in line: + continue + key, _, value = line.partition("=") + key = key.strip() + if key and " " not in key: + current[key] = value.strip() + return devices + + +def _primary_device(devices): + """The device that actually matters for this project. + + A host with Honeykrisp also enumerates llvmpipe, and llvmpipe is + listed last. Reporting it would make every submission useless for + driver work, so prefer the real GPU: Honeykrisp first, then any + non-CPU device, and only then whatever came first. + """ + if not devices: + return {} + for dev in devices: + if "HONEYKRISP" in dev.get("driverID", "").upper(): + return dev + for dev in devices: + if dev.get("deviceType", "") != "PHYSICAL_DEVICE_TYPE_CPU": + return dev + return devices[0] + + +def probe_mesa(redactor): + """Vulkan stack identity from `vulkaninfo --summary`. + + `probe` states the probe's own fate so a missing binary is never + read as an unsupported GPU: "missing" (tool not installed), + "failed" (tool ran but errored), "ok" (parsed). + """ + if platform.system() == "Darwin": + return collect_macos.not_applicable() + out = {"available": False, "probe": None, "properties": {}, "summary": None} + rec = run_tool(["vulkaninfo", "--summary"], redactor, + label="vulkaninfo --summary", timeout=30) + out["vulkaninfo"] = rec + if not rec["available"]: + out["probe"] = "missing" + return out + if rec["exit_code"] != 0: + out["probe"] = "failed" + return out + devices = _device_blocks(rec["stdout"]) + primary = _primary_device(devices) + out["devices"] = devices + out["device_count"] = len(devices) + out["properties"] = primary + known = ("deviceName", "driverName", "driverVersion", "apiVersion", + "vendorID", "deviceID", "deviceType", "conformanceVersion", + "driverID", "driverInfo") + out["gpu"] = {k: primary[k] for k in known if k in primary} + out["available"] = bool(out["gpu"]) + out["probe"] = "ok" if out["available"] else "failed" + return out + + +def probe_mesa_package(redactor): + """Mesa package version as a cross-check; distro-specific and optional. + + Each query is gated on its package manager actually existing, so an + Arch host does not carry a pointless dpkg not-found record. + """ + if platform.system() == "Darwin": + return collect_macos.not_applicable() + out = {} + if shutil.which("pacman"): + out["pacman"] = run_tool(["pacman", "-Q", "mesa"], redactor, + label="pacman -Q mesa", timeout=15) + out["vulkan-asahi"] = run_tool(["pacman", "-Q", "vulkan-asahi"], + redactor, label="pacman -Q vulkan-asahi", + timeout=15) + if shutil.which("dpkg-query"): + out["dpkg"] = run_tool( + ["dpkg-query", "-W", "-f=${Package} ${Version}\\n", "mesa"], + redactor, label="dpkg-query mesa", timeout=15) + return out + +def probe_ane(redactor): + """Apple Neural Engine visibility: device node and libane.""" + if platform.system() == "Darwin": + return collect_macos.not_applicable() + node = os.path.exists("/dev/ane") + out = {"available": node, "device_node": node} + out["devicetree"] = _ane_devicetree() + lib = run_tool(["sh", "-c", "ldconfig -p 2>/dev/null | grep -i libane"], + redactor, label="ldconfig libane", timeout=15) + out["libane"] = lib["stdout"].strip() if lib["exit_code"] == 0 else None + out["libane_probe"] = lib + pkg = run_tool(["pkg-config", "--modversion", "libane"], redactor, + label="pkg-config libane", timeout=15) + out["libane_version"] = pkg["stdout"].strip() \ + if pkg["exit_code"] == 0 else None + out["pkgconfig"] = pkg + return out + + +MLX_PROBE_CODE = r""" +import json +out = {"distributions": {}, "import_ok": False, "import_error": None, + "info_tool": None, "default_device": None, "mlx_version": None} +import importlib.metadata +for dist in ("mlx-omarchy", "mlx"): + try: + out["distributions"][dist] = importlib.metadata.version(dist) + except Exception: + pass +import pathlib +try: + import mlx.core as mx + out["import_ok"] = True + import platform + if platform.system() == "Darwin": + out["metal_available"] = mx.metal.is_available() + if out["metal_available"]: + mx.set_default_device(mx.gpu) + out["default_device"] = str(mx.default_device()) + out["mlx_version"] = getattr(mx, "__version__", None) + # mlx is a namespace package (mlx.__file__ is None); anchor on the + # extension module, which lives beside the shipped bin/ directory. + cand = pathlib.Path(mx.__file__).resolve().parent / "bin" / "mlx-omarchy-info" + if cand.exists(): + out["info_tool"] = str(cand) +except Exception as exc: + out["import_error"] = f"{type(exc).__name__}: {exc}" +print(json.dumps(out)) +""" + + +def probe_mlx(redactor): + """Installed wheel identity plus the shipped capability tool.""" + rec = run_tool([sys.executable, "-c", MLX_PROBE_CODE], redactor, + label="mlx import probe", timeout=90) + out = {"available": False, "probe": rec, "info": None, + "capabilities": None} + if not rec["available"] or rec["exit_code"] != 0: + return out + try: + found = json.loads(rec["stdout"].strip().splitlines()[-1]) + except (ValueError, IndexError): + return out + out["available"] = bool(found.get("import_ok")) + for key in ("distributions", "import_error", "default_device", + "mlx_version", "info_tool", "metal_available"): + out[key] = found.get(key) + tool = found.get("info_tool") + if tool: + cap = run_tool([tool, "--json"], redactor, + label="mlx-omarchy-info --json", timeout=60) + out["info"] = cap + if cap["exit_code"] == 0: + try: + out["capabilities"] = json.loads(cap["stdout"]) + except ValueError: + out["capabilities"] = None + return out + + +def _strip_volatile(value): + """Drop run-to-run noise so equal machine state gives equal output.""" + if isinstance(value, dict): + return {k: _strip_volatile(v) for k, v in value.items() + if k != "duration_ms"} + if isinstance(value, list): + return [_strip_volatile(v) for v in value] + return value + + +DEFAULT_PROBES = { + "host": probe_host, + "mesa": probe_mesa, + "mesa_package": probe_mesa_package, + "ane": probe_ane, + "ane_port": probe_ane_port, + "mlx": probe_mlx, +} + + +def collect(probes=None): + """Build the report dict. `probes` overrides sections for tests.""" + active = dict(DEFAULT_PROBES) + if probes: + active.update(probes) + redactor = Redactor() + report = { + "report": "mlx-omarchy-quick", + "schema_version": SCHEMA_VERSION, + } + for name in sorted(active): + try: + report[name] = redactor.apply_value(active[name](redactor)) + except Exception as exc: + report[name] = { + "available": False, + "error": redactor.apply(f"{type(exc).__name__}: {exc}"), + } + return _strip_volatile(report) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--out", metavar="FILE", + help="also write the JSON report to FILE") + ap.add_argument("--submit", metavar="URL", default=None, + help="publish this report to the community endpoint " + "after printing it") + args = ap.parse_args() + report = collect() + text = dump_json(report) + if args.out: + with open(args.out, "wb") as fh: + fh.write(json_bytes(report)) + print(f"[receipt] wrote {args.out} ({len(json_bytes(report))} bytes)") + print(text, end="" if text.endswith("\n") else "\n") + raise SystemExit(maybe_submit(args, report)) + + +def maybe_submit(args, report): + """Publish only after the report was shown and consent was given. + + The import is local so that a plain run of this script loads no + network module at all. + """ + import collect_submit + + endpoint = collect_submit.endpoint_from_args(args) + if endpoint is None: + return 0 + payload = build_payload("quick", report, {}, redactor=Redactor()) + digest = collect_submit.sha256_hex( + json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()) + if not args.submit and not collect_submit.confirm_interactive( + endpoint, "quick report", digest): + print("[submit] declined; nothing was uploaded") + return 0 + try: + receipt = collect_submit.submit_payload( + endpoint, payload, token=collect_submit.token_from_env()) + except collect_submit.SubmitError as exc: + print(f"[submit] FAILED: {exc}", file=sys.stderr) + return 4 + print(f"[receipt] public URL: {receipt['url']} " + f"(deduplicated={receipt['deduplicated']})") + return 0 + + +if __name__ == "__main__": + main() diff --git a/scripts/collect_submit.py b/scripts/collect_submit.py new file mode 100755 index 000000000000..e0e9fd0393e2 --- /dev/null +++ b/scripts/collect_submit.py @@ -0,0 +1,342 @@ +#!/usr/bin/env python3 +"""Upload path for the mlx-omarchy contributor diagnostics archive. + +The only network code in the collectors lives here. `collect_quick.py` +never imports this module; `collect_deep.py` imports it lazily, only +after the user has seen the preview and asked to submit explicitly. + +Wire protocol (the Cloudflare Worker in services/community-data/): + + POST /v1/submit + body: {"schema_version", "kind", "content_sha256", "payload", + "archive": {"total_bytes", "chunk_bytes", "chunk_count", + "chunk_sha256": [...]} | null, + "pow": {"nonce", "difficulty"}} + 200 -> {"status": "awaiting_chunks"|"stored"|"duplicate", + "content_sha256", "missing_chunks": [...], "receipt_url"} + POST /v1/submit//chunk/ body: one raw chunk + 200 -> {"status": "stored"|"duplicate", "idx", + "missing_chunks": [...]} + POST /v1/submit//complete + 200 -> {"status": "stored"|"duplicate", "receipt_url"} + 409 -> {"error": "incomplete", "missing_chunks": [...]} + GET /v1/submit/ dedup probe + 200 -> {"status": "duplicate"}; 404 -> not present + +Only the already-redacted payload and archive are sent. Uploads are +resumable: a re-run repeats the initiate call and uploads only the +chunks the server reports as missing. The proof-of-work nonce is bound +to the archive hash, so a token cannot be reused for other content. + +A custom User-Agent is required: workers.dev fronting 403s the default +Python-urllib user agent. + +Every failure raises SubmitError. The caller keeps the local archive +and prints the error; a failed submit never destroys local output. +""" + +import hashlib +import json +import os +import sys +import urllib.error +import urllib.request + +DEFAULT_TIMEOUT = 60 + +# Must mirror services/community-data/src/caps.ts. +CHUNK_BYTES = 768 * 1024 +MAX_ARCHIVE_BYTES = 8 * 1024 * 1024 +MAX_PAYLOAD_BYTES = 256 * 1024 +POW_DIFFICULTY = 18 + +USER_AGENT = "mlx-omarchy-collector/1" + + +class SubmitError(RuntimeError): + pass + + +def _request(urlopen, req, timeout): + try: + with urlopen(req, timeout=timeout) as resp: + body = resp.read() + return resp.status, body + except urllib.error.HTTPError as exc: + return exc.code, exc.read() + except (urllib.error.URLError, OSError, TimeoutError) as exc: + raise SubmitError(f"endpoint unreachable: {exc}") from exc + + +def sha256_hex(data): + return hashlib.sha256(data).hexdigest() + + +def leading_zero_bits(hex_digest): + bits = 0 + for ch in hex_digest: + nibble = int(ch, 16) + if nibble == 0: + bits += 4 + continue + if nibble < 2: + bits += 3 + elif nibble < 4: + bits += 2 + elif nibble < 8: + bits += 1 + break + return bits + + +def solve_pow(content_sha256, difficulty=POW_DIFFICULTY): + """Find a nonce so sha256(":") has >= difficulty zero bits.""" + nonce = 0 + while True: + digest = hashlib.sha256(f"{content_sha256}:{nonce}".encode()).hexdigest() + if leading_zero_bits(digest) >= difficulty: + return str(nonce) + nonce += 1 + + +def chunk_archive(data, chunk_bytes=CHUNK_BYTES): + """Deterministic split; returns [(idx, bytes, sha256), ...].""" + chunks = [] + for idx, off in enumerate(range(0, len(data), chunk_bytes)): + piece = data[off:off + chunk_bytes] + chunks.append((idx, piece, sha256_hex(piece))) + return chunks + + +def _decode(body): + try: + return json.loads(body.decode("utf-8")) + except (ValueError, UnicodeDecodeError): + return {} + + +def _headers(token, extra=None): + headers = { + "User-Agent": USER_AGENT, + "Authorization": f"Bearer {token}", + } if token else {"User-Agent": USER_AGENT} + if extra: + headers.update(extra) + return headers + + +def submit(endpoint, data, payload, timeout=DEFAULT_TIMEOUT, urlopen=None, + token=None): + """Submit one archive; returns {"url", "deduplicated", "status"}. + + `urlopen` is injectable for tests. Resumable: re-invoking after a + mid-upload failure re-initiates and sends only the missing chunks. + """ + if len(data) > MAX_ARCHIVE_BYTES: + raise SubmitError( + f"archive too large for the public endpoint: {len(data)} > " + f"{MAX_ARCHIVE_BYTES} bytes; it stays local") + if urlopen is None: + opener = urllib.request.build_opener() + urlopen = opener.open + base = endpoint.rstrip("/") + digest = sha256_hex(data) + chunks = chunk_archive(data) + + status, body = _request( + urlopen, + urllib.request.Request( + f"{base}/v1/submit/{digest}", headers=_headers(token)), + timeout) + if status == 200: + return _receipt(_decode(body), deduplicated=True, status=status) + if status != 404: + raise SubmitError(f"dedup probe failed with HTTP {status}") + + difficulty = POW_DIFFICULTY + for attempt in range(2): + initiate = { + "schema_version": payload.get("schema_version", 1), + "kind": payload.get("kind", "deep"), + "content_sha256": digest, + "payload": payload, + "archive": { + "total_bytes": len(data), + "chunk_bytes": CHUNK_BYTES, + "chunk_count": len(chunks), + "chunk_sha256": [c[2] for c in chunks], + }, + "pow": { + "nonce": solve_pow(digest, difficulty), + "difficulty": difficulty, + }, + } + status, body = _request( + urlopen, + urllib.request.Request( + f"{base}/v1/submit", + data=json.dumps(initiate).encode("utf-8"), + headers=_headers(token, {"Content-Type": "application/json"}), + method="POST"), + timeout) + decoded = _decode(body) + if status == 403 and decoded.get("error") == "pow_invalid": + wanted = (decoded.get("detail") or {}).get("min_difficulty") + if isinstance(wanted, int) and wanted > difficulty: + difficulty = wanted + continue + break + + if status != 200: + raise SubmitError( + f"initiate failed with HTTP {status}: {decoded.get('error')}") + + if decoded.get("status") == "duplicate": + return _receipt(decoded, deduplicated=True, status=status) + if decoded.get("status") == "stored": + return _receipt(decoded, deduplicated=False, status=status) + + for idx in decoded.get("missing_chunks", []): + piece = chunks[idx][1] + cstatus, cbody = _request( + urlopen, + urllib.request.Request( + f"{base}/v1/submit/{digest}/chunk/{idx}", + data=piece, + headers=_headers(token, + {"Content-Type": "application/octet-stream"}), + method="POST"), + timeout) + cdecoded = _decode(cbody) + if cstatus != 200: + raise SubmitError( + f"chunk {idx} failed with HTTP {cstatus}: " + f"{cdecoded.get('error')}; re-run to resume") + + fstatus, fbody = _request( + urlopen, + urllib.request.Request( + f"{base}/v1/submit/{digest}/complete", + data=b"", + headers=_headers(token), + method="POST"), + timeout) + fdecoded = _decode(fbody) + if fstatus == 409 and fdecoded.get("error") == "incomplete": + raise SubmitError( + f"server still misses chunks {fdecoded.get('missing_chunks')}; " + f"re-run to resume") + if fstatus != 200: + raise SubmitError( + f"complete failed with HTTP {fstatus}: {fdecoded.get('error')}") + return _receipt(fdecoded, deduplicated=False, status=fstatus) + + +def submit_payload(endpoint, payload, timeout=DEFAULT_TIMEOUT, urlopen=None, + token=None): + """Publish a payload-only report: no archive, one round trip. + + The quick report is small and self-describing, so the endpoint takes + `archive: null` and publishes at initiate. Content is addressed by + the sha256 of the canonical payload bytes, so re-running an unchanged + machine deduplicates instead of adding a row. + """ + if urlopen is None: + opener = urllib.request.build_opener() + urlopen = opener.open + base = endpoint.rstrip("/") + body = json.dumps(payload, sort_keys=True, + separators=(",", ":")).encode("utf-8") + if len(body) > MAX_PAYLOAD_BYTES: + raise SubmitError( + f"report too large for the public endpoint: {len(body)} > " + f"{MAX_PAYLOAD_BYTES} bytes; it stays local") + digest = sha256_hex(body) + + status, raw = _request( + urlopen, + urllib.request.Request( + f"{base}/v1/submit/{digest}", headers=_headers(token)), + timeout) + if status == 200: + return _receipt(_decode(raw), deduplicated=True, status=status) + if status != 404: + raise SubmitError(f"dedup probe failed with HTTP {status}") + + difficulty = POW_DIFFICULTY + decoded = {} + for _attempt in range(2): + initiate = { + "schema_version": payload.get("schema_version", 1), + "kind": payload.get("kind", "quick"), + "content_sha256": digest, + "payload": payload, + "archive": None, + "pow": { + "nonce": solve_pow(digest, difficulty), + "difficulty": difficulty, + }, + } + status, raw = _request( + urlopen, + urllib.request.Request( + f"{base}/v1/submit", + data=json.dumps(initiate).encode("utf-8"), + headers=_headers(token, {"Content-Type": "application/json"}), + method="POST"), + timeout) + decoded = _decode(raw) + if status == 403 and decoded.get("error") == "pow_invalid": + wanted = (decoded.get("detail") or {}).get("min_difficulty") + if isinstance(wanted, int) and wanted > difficulty: + difficulty = wanted + continue + break + + if status != 200: + raise SubmitError( + f"submit failed with HTTP {status}: {decoded.get('error')}") + return _receipt(decoded, + deduplicated=decoded.get("status") == "duplicate", + status=status) + + +def _receipt(body, deduplicated, status): + url = body.get("receipt_url") + if not url: + raise SubmitError("endpoint returned no receipt URL") + return {"url": url, "deduplicated": deduplicated, "status": status} + + +DEFAULT_ENDPOINT = "https://mlx-omarchy-community-data.joshua-s-warren.workers.dev" + + +def endpoint_from_args(args): + """Resolve the endpoint: --submit flag first, then the environment.""" + if getattr(args, "submit", None): + return args.submit + return os.environ.get("MLX_OMARCHY_SUBMIT_URL") or None + + +def token_from_env(): + return os.environ.get("MLX_OMARCHY_SUBMIT_TOKEN") or None + + +def sys_stdin_isatty(): + return os.environ.get("MLX_OMARCHY_ASSUME_YES") != "1" and \ + sys.stdin.isatty() + + +def confirm_interactive(endpoint, archive_name, digest): + """Ask for the exact word SUBMIT on a terminal; anything else declines.""" + if not sys_stdin_isatty(): + return False + print(f"[submit] endpoint: {endpoint}") + print(f"[submit] archive: {archive_name} sha256={digest}") + print("[submit] only redacted report data and any attached archive are sent. " + "Type SUBMIT to upload, anything else to keep it local:") + try: + answer = input().strip() + except (EOFError, KeyboardInterrupt): + return False + return answer == "SUBMIT" diff --git a/tests/test-collect-e2e.py b/tests/test-collect-e2e.py new file mode 100755 index 000000000000..a9c772fd32ac --- /dev/null +++ b/tests/test-collect-e2e.py @@ -0,0 +1,376 @@ +#!/usr/bin/env python3 +"""Focused regression checks for the Mac E2E collector (stdlib only). + +Run: python3 tests/test-collect-e2e.py + +Covers the behaviours reviewers actually caught on PR464 and the wiki +feature-matrix contract: + +- stage verdicts: all-NA renders NA, PASS+SKIP renders PARTIAL (never SKIP) +- Vulkan summary: a missing vulkaninfo probe says "probe missing", not + "unavailable" +- install-log absence notes say absence is not a hardware failure +- the interview keeps one answer per wiki hardware feature, preserves + persisted old answers (including combined-question keys from older + collectors), and never transfers an old combined PASS to a split feature +- feature answers render as the wiki matrix symbols with their + peripheral/connection notes, and unrecorded features stay '?' +- machine identity records model/board/SoC/kernel/date without crashing + off-Apple, and the archive/submission carry the feature answers +""" + +import builtins +import json +import os +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), + "..", "scripts")) + +import collect_e2e # noqa: E402 +import collect_quick # noqa: E402 +from collect_common import Redactor # noqa: E402 + +FAILURES = [] + + +def check(name, fn, tmp=None): + try: + fn(tmp) + except AssertionError as exc: + FAILURES.append(f"{name}: {exc}") + print(f"✗ {name}: {exc}") + except Exception as exc: # noqa: BLE001 + FAILURES.append(f"{name}: unexpected {type(exc).__name__}: {exc}") + print(f"✗ {name}: unexpected {type(exc).__name__}: {exc}") + else: + print(f"✓ {name}") + + +def answers_for(mapping): + return {f"{g}::{i}": a for (g, i), a in mapping.items()} + + +def group_items(group): + return [i for g, i in collect_e2e.INTERVIEW_ITEMS if g == group] + + +# The wiki hardware matrix columns, verbatim from +# Apple-Silicon-hardware.md; the collector must cover every one. +WIKI_FEATURES = [ + "internal display", "HDMI display", "USB-C DisplayPort display", + "USB devices", "Thunderbolt dock", "Wi-Fi", "Bluetooth", + "speakers", "headphones", "microphone", "HDMI audio", + "suspend", "camera", "Touch ID", "keyboard", "trackpad", + "GPU inference", "Neural Engine", +] + + +def test_stage_verdicts(_=None): + v = collect_e2e.stage_verdict + # PR464 case 1: --no-encrypt run, encryption stages all NA -> NA. + all_na = {("reboot-b", i): "NA" for i in group_items("reboot-b")} + assert v(answers_for(all_na), "reboot-b") == "NA", \ + "all-NA stage must be NA, not PARTIAL" + # PR464 case 2: 10 PASS + 1 SKIP -> PARTIAL, never SKIP. + desktop = group_items("desktop") + mixed = {("desktop", i): "PASS" for i in desktop[:-1]} + mixed[("desktop", desktop[-1])] = "SKIP" + assert v(answers_for(mixed), "desktop") == "PARTIAL", \ + "PASS+SKIP mix must be PARTIAL, not SKIP" + # FAIL dominates; all PASS passes; all SKIP stays SKIP; NA among + # passes is ignored; nothing recorded is UNRECORDED. + full_pass = {("desktop", i): "PASS" for i in desktop} + first = {("desktop", desktop[0])} + assert v(answers_for({**full_pass, ("desktop", desktop[0]): "FAIL"}), + "desktop") == "FAIL" + assert v(answers_for(full_pass), "desktop") == "PASS" + assert v(answers_for({("desktop", i): "SKIP" for i in desktop}), + "desktop") == "SKIP" + assert v(answers_for({**full_pass, next(iter(first)): "NA"}), + "desktop") == "PASS" + assert v({}, "desktop") == "UNRECORDED" + + +def test_parse_answer_vocabularies(_=None): + parse = collect_e2e.parse_answer + got = parse("WORKS; Dell U2723QE via USB-C", "", + collect_e2e.FEATURE_ANSWERS) + assert got == ("WORKS", "Dell U2723QE via USB-C") + # A stage answer is not valid for a feature and vice versa. + assert parse("PASS", "", collect_e2e.FEATURE_ANSWERS) == (None, None) + assert parse("WORKS", "", collect_e2e.VALID_ANSWERS) == (None, None) + # Blank keeps the prior answer; case and whitespace tolerated. + assert parse("", "LIMITATION", collect_e2e.FEATURE_ANSWERS) == \ + ("LIMITATION", None) + assert parse(" works ", "", collect_e2e.FEATURE_ANSWERS) == ("WORKS", None) + + +def test_feature_contract(_=None): + assert list(collect_e2e.FEATURE_ITEMS) == WIKI_FEATURES, \ + "collector features must match the wiki hardware matrix exactly" + assert set(collect_e2e.FEATURE_PERIPHERAL) <= set(WIKI_FEATURES) + + +def test_split_answers_preserve_old_and_transfer_nothing(tmp): + """Persisted old answers survive; the old combined PASS does not + become a split feature's answer.""" + path = os.path.join(tmp, "e2e-answers.json") + combined = ("desktop::Audio plays at modest volume with speaker " + "protection active") + with open(path, "w") as fh: + json.dump({"answers": {combined: "PASS", + "some-future-key": "kept-verbatim", + "hardware::headphones": + "WORKS;Sennheiser HD 560S via 3.5mm jack"}}, + fh) + real_stdin, real_input = sys.stdin, builtins.input + + class FakeTTY: + def isatty(self): + return True + + # 34 checklist items accept blank; then the first feature gets an + # invalid stage answer (reprompt) then BROKEN; the second gets + # WORKS plus a peripheral note; the rest stay blank. + script = iter([""] * len(collect_e2e.INTERVIEW_ITEMS) + + ["PASS", "BROKEN", + "WORKS;AOC U27P2CA via USB-C DP"] + [""] * 100) + sys.stdin = FakeTTY() + builtins.input = lambda *a, **k: next(script) + try: + out = collect_e2e.section_interview(Redactor(), path) + finally: + sys.stdin, builtins.input = real_stdin, real_input + answers = out["answers"] + assert answers[combined] == "PASS", "old combined answer must survive" + assert answers["some-future-key"] == "kept-verbatim", \ + "unknown keys must be preserved, not pruned" + assert answers["hardware::internal display"] == "BROKEN" + assert answers["hardware::HDMI display"] == "WORKS" + # Old combined PASS never leaks into the split features. + assert "hardware::speakers" not in answers, \ + "split feature must start unanswered, not inherit the combined PASS" + # A hand-written "ANSWER; note" value loads normalized, not verbatim. + assert answers["hardware::headphones"] == "WORKS" + assert out["notes"]["hardware::headphones"] == \ + "Sennheiser HD 560S via 3.5mm jack" + # Peripheral model/connection note retained. + assert out["notes"]["hardware::HDMI display"] == \ + "AOC U27P2CA via USB-C DP" + # Write-back preserves everything, including keys this version + # does not know. + with open(path) as fh: + saved = json.load(fh)["answers"] + assert saved[combined] == "PASS" + assert saved["some-future-key"] == "kept-verbatim" + + +def test_feature_matrix_render(_=None): + answers = {"hardware::speakers": "WORKS", + "hardware::suspend": "LIMITATION", + "hardware::Touch ID": "BROKEN", + "hardware::HDMI display": "NA", + "hardware::microphone": "UNKNOWN"} + notes = {"hardware::HDMI display": "Dell U2723QE via HDMI 2.0"} + text = "\n".join(collect_e2e.render_feature_matrix(answers, notes)) + assert "speakers: WORKS (✓)" in text + assert "suspend: LIMITATION (!)" in text + assert "Touch ID: BROKEN (✕)" in text + assert "HDMI display: NA (n/a) — Dell U2723QE via HDMI 2.0" in text + assert "microphone: UNKNOWN (?)" in text + # Unrecorded renders '?' (not known), never a machine-derived verdict. + assert "Wi-Fi: UNRECORDED (?)" in text + assert "camera: UNRECORDED (?)" in text + + +def test_vulkan_probe_missing_reads_honest(_=None): + missing = {"mesa": {"available": False, "probe": "missing", + "vulkaninfo": {"available": False, + "error": "not-found"}}} + line = collect_e2e.vulkan_summary(missing) + assert "probe missing" in line, "absent tool must say probe missing" + assert "not a GPU or driver verdict" in line + # Driver-package fallback gives real signal when the tool is absent. + fallback = {"mesa": missing["mesa"], + "mesa_package": {"vulkan-asahi": { + "exit_code": 0, "stdout": "vulkan-asahi 1:26.2.3-1"}}} + assert "vulkan-asahi 1:26.2.3-1" in collect_e2e.vulkan_summary(fallback) + ok = {"mesa": {"gpu": {"deviceName": "Apple M2 Pro (G13C)", + "driverName": "Honeykrisp"}}} + line = collect_e2e.vulkan_summary(ok) + assert "Apple M2 Pro (G13C)" in line and "Honeykrisp" in line + + +def test_log_absence_is_not_failure(_=None): + empty = {"logs": {p: {"present": False} + for p in collect_e2e.SETUP_LOGS}} + line = collect_e2e.logs_presence_line(empty) + assert "not a hardware" in line and "absence_notes" in line + some = {"logs": {"/var/log/pacman.log": {"present": True}, + "/var/log/omarchy-mac-setup.log": {"present": False}}} + assert collect_e2e.logs_presence_line(some) == \ + "Install logs present: /var/log/pacman.log" + # The never-written setup log carries its own why-note in the section. + assert "never writes this file" in collect_e2e.LOG_ABSENCE_NOTES[ + "/var/log/omarchy-mac-setup.log"] + + +def test_machine_identity_anywhere(_=None): + ident = collect_e2e.machine_identity() + for key in ("marketing_model", "board_compatible", "soc", "compatible", + "kernel", "os", "collected_at_utc"): + assert key in ident + # Off-Apple this host has no apple,t* / apple,j* strings; None is + # data, not a crash. + assert ident["soc"] is None or ident["soc"].startswith("T") + assert ident["collected_at_utc"].endswith("Z") + + +def test_collect_quick_probe_state(_=None): + # collect() accepts probe overrides; the missing-tool state must be + # explicit so downstream never calls it "unsupported". + report = collect_quick.collect(probes={ + "mesa": lambda redactor: { + "available": False, "probe": "missing", + "vulkaninfo": {"available": False, "error": "not-found"}}}) + assert report["mesa"]["probe"] == "missing" + + +def test_report_and_submission_carry_features(tmp): + answers = {"hardware::speakers": "WORKS", + "hardware::suspend": "LIMITATION", + "hardware::Touch ID": "BROKEN"} + notes = {"hardware::suspend": "resumes, Wi-Fi needs rmmod/modprobe"} + interview = {"available": True, "answers": answers, "notes": notes, + "interactive": True} + identity = {"test_id": "T-1"} + files = {"interview.json": json.dumps(interview).encode(), + "identity.json": json.dumps({"available": True, "machine": { + "marketing_model": + "Apple MacBook Pro (16-inch, M2 Pro, 2023)", + "board_compatible": "apple,j416s", "soc": "T6020", + "os": "Arch Linux", "kernel": "6.17.0", + "collected_at_utc": "2026-09-19T00:00:00Z"}}).encode(), + "baseline.json": json.dumps( + {"storage_facts": {"root_encrypted": True}}).encode(), + "install-state.json": b"{}", + "security.json": b"{}", + "mlx.json": json.dumps({ + "host": {"devicetree": {"model": "Apple MacBook Pro"}}, + "mesa": {"available": False, "probe": "missing", + "vulkaninfo": {"available": False, + "error": "not-found"}}}).encode()} + report = collect_e2e.render_report_md(identity, files) + for needle in ("speakers: WORKS (✓)", "suspend: LIMITATION (!)", + "Touch ID: BROKEN (✕)", + "Wi-Fi: UNRECORDED (?)", + "note [hardware::suspend]: resumes, Wi-Fi needs " + "rmmod/modprobe", + "apple,j416s", "T6020", "Machine [auto]:"): + assert needle in report, f"report must carry {needle!r}" + submission = collect_e2e.build_submission({}, files, identity) + assert "probe missing" in submission + assert "speakers: WORKS (✓)" in submission, \ + "submission.md must preserve feature answers" + + +def test_connector_names(_=None): + import io + from unittest.mock import patch + + names = ["card0", "renderD128", "card0-HDMI-A-1", "card0-DP-1", "card0-eDP-1"] + with patch.object(collect_e2e.os, "listdir", side_effect=lambda path: names if path == "/sys/class/drm" else []), \ + patch.object(collect_e2e.os.path, "isdir", return_value=True), \ + patch("builtins.open", side_effect=lambda *args, **kwargs: io.StringIO("connected")), \ + patch.object(collect_e2e, "tool", return_value={}): + result = collect_e2e.section_hardware(Redactor()) + assert {row["connector"] for row in result["drm_connectors"]} == set(names[2:]) + + +def test_invalid_or_missing_answers_do_not_pass(_=None): + keys = [f"desktop::{item}" for item in group_items("desktop")] + answers = dict.fromkeys(keys, "PASS") + answers[keys[0]] = "WORKS" + assert collect_e2e.stage_verdict(answers, "desktop") == "PARTIAL" + assert collect_e2e.stage_verdict({keys[0]: "garbage"}, "desktop") == "UNRECORDED" + assert collect_e2e.stage_verdict({keys[0]: "PASS"}, "desktop") == "PARTIAL" + text = "\n".join(collect_e2e.render_feature_matrix({"hardware::speakers": "PASS"}, {})) + assert "speakers: UNRECORDED (?)" in text + + +def test_console_interview_reaches_archive(tmp): + import pty + import select + import subprocess + import tarfile + import time + + master, slave = pty.openpty() + archive = os.path.join(tmp, "console.tar.gz") + command = [sys.executable, collect_e2e.__file__, "--interview", "--out", archive, + "--identity-file", os.path.join(tmp, "console-identity.json"), + "--answers-file", os.path.join(tmp, "console-answers.json"), + "--skip", ",".join(s for s in collect_e2e.SECTION_ORDER + if s not in ("identity", "interview"))] + process = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=slave) + os.close(slave) + pending = b"" + prompts = 0 + deadline = time.monotonic() + 20 + try: + while process.poll() is None and time.monotonic() < deadline: + if not select.select([master], [], [], 0.1)[0]: + continue + try: + pending += os.read(master, 65536) + except OSError: + break + if pending.endswith(b": "): + if prompts == 0: + answer = "ConsoleTester" + elif prompts == 1: + answer = "CONSOLE-464" + elif b"[hardware] speakers" in pending: + answer = "WORKS; built-in speakers" + elif prompts >= 15: + answer = "NA" + else: + answer = "" + os.write(master, (answer + "\n").encode()) + prompts += 1 + pending = b"" + assert process.wait(timeout=2) == 0 + assert prompts == 67, f"expected visible identity and interview prompts, got {prompts}" + with tarfile.open(archive) as tar: + cover = tar.extractfile("submission.md") + answers = tar.extractfile("interview.json") + assert cover is not None and answers is not None + submission = cover.read().decode() + interview = json.load(answers) + assert "CONSOLE-464" in submission + assert "ConsoleTester" in submission + assert interview["answers"]["hardware::speakers"] == "WORKS" + assert "speakers: WORKS" in submission + finally: + if process.poll() is None: + process.kill() + process.wait() + os.close(master) + + +def main(): + with tempfile.TemporaryDirectory() as tmp: + for name in sorted(n for n in globals() if n.startswith("test_")): + check(name, globals()[name], tmp) + print() + if FAILURES: + print(f"{len(FAILURES)} check(s) failed") + return 1 + print("all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test-collect-e2e.sh b/tests/test-collect-e2e.sh new file mode 100644 index 000000000000..defcbb06dc1d --- /dev/null +++ b/tests/test-collect-e2e.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +python3 "$(dirname -- "${BASH_SOURCE[0]}")/test-collect-e2e.py"