commit 2432b4f29afb8cc9a4194f54a41ad4dfa14bde9a Author: Pavel Isaev Date: Fri Nov 6 00:09:39 2026 +0300 Record native desktop delivery and release integration work in progress diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a757ea6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +*.pyc +/runs/ +/artifacts/ +/cache/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..06219cc --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,25 @@ +# Лаборатория Archipelago + +По указанию пользователя от 2026-11-05 временные сборки и VM-проверки перенесены +на `yabloko` (Tailscale SSH, sudo без пароля). Репозитории, архив результатов, +ISO, OSTree repo и портал остаются на `terra`. Передавать большие файлы напрямую +между хостами, без промежуточной передачи через машину пользователя. +Это временное уточнение размещения исполнителей относительно D-071 ниже. + +После D-071 новые инфраструктурные сборки/проверки выполнять на `terra` через +Tailscale SSH. Уже запущенный ISO №14 на `superserv1` завершается там; исторические +результаты не переносить и не объявлять результатами terra. + +Исторический лабораторный профиль: компиляции, функциональные проверки и тесты на `superserv1` по +Tailscale SSH. Рабочий каталог — `/hdd/archipelago`; результаты и временные файлы +хранить там же. Локально редактировать и просматривать исходники. + +Не считать smoke-тест QMP доказательством загрузки гостевой ОС. Каждый эксперимент +должен различать проверенную гипотезу, наблюдение и ещё не доказанное свойство RFC. +Код лаборатории не фиксирует язык продукта или стабильные схемы. + +Стенд домашний и ограничен по ресурсам: держать запущенной только необходимую +тестовую VM; предыдущие завершённые проверки штатно выключать, сохраняя диски +и evidence до согласованной очистки. Не выключать посторонние инфраструктурные VM. +При запуске подготовки через systemd отделять installed QEMU от сборочного unit +через `gnome_vm_prepare.py --vm-unit`, иначе cleanup unit завершит VM. diff --git a/CLOCK-TRUST-PROBE-2026-11-05.md b/CLOCK-TRUST-PROBE-2026-11-05.md new file mode 100644 index 0000000..999e8bb --- /dev/null +++ b/CLOCK-TRUST-PROBE-2026-11-05.md @@ -0,0 +1,42 @@ +# Installed hardware: clock, pacman trust and Flatpak TLS + +Image base: `14bcd04f6057042e45961a4ee325bbf646dcc167ad2859905ac7c729bfe7035d` +(published GNOME `20261105T164634Z`). This probe was explicitly requested after +installation on the user's hardware; it is not a hardware certification gate. + +## Reproduced + +- `archipelago extension add chromium` failed while populating the staging pacman + keyring. GnuPG reported the packaged distribution key was created 19 days in the + future, skipped it, and could not locally sign it. +- `flatpak install --system --noninteractive flathub com.google.Chrome` failed to + retrieve the Flathub summary with TLS error 60. An independent verified `curl` + request reported that the certificate was not yet valid/system clock incorrect. +- CA bundle and standard OpenSSL symlinks were present. The system clock was + 2026-10-17, RTC 2026-10-01; actual date was 2026-11-05. +- `systemd-timesyncd` was installed but disabled/inactive, with no boot journal. + The image builder explicitly enabled networking but omitted time synchronization. + +## Repair and implementation + +`timedatectl set-ntp true` synchronized both system time and RTC through the normal +Arch NTP configuration. `NTPSynchronized=yes` was observed at 2026-11-05 19:22 UTC. +The existing keyring is repopulated by restarting `archipelago-keyring.service`; +there is no need to delete trust databases or disable cryptographic verification. + +Builder changes enable `systemd-timesyncd` for Core and inherited GNOME, order +keyring and initial Flatpak seeding after `time-set.target`, and retry failed +keyring initialization every 30 seconds. `time-set.target` is only a local clock +ordering point, not proof of NTP synchronization. Retry handles a later network +time correction; no unbounded online synchronization prerequisite is added to boot. + +Actual Chromium extension and Chrome Flatpak installation retries are running as +`archipelago-browser-check.service` on the installed machine. Until results are +recorded below, only reproduction and clock synchronization are established. +No reboot is performed automatically; successful extension staging selects the +new deployment for the next explicit boot. + +Private diagnostics are collected on yabloko under +`/opt/archipelago/evidence/laptop-20261105/` and subsequently archived on terra. +These changes still require a new image and a skewed-RTC VM regression check; +the published ISO bytes are unchanged. diff --git a/CONTROL-LAYER-RESULTS.md b/CONTROL-LAYER-RESULTS.md new file mode 100644 index 0000000..068f861 --- /dev/null +++ b/CONTROL-LAYER-RESULTS.md @@ -0,0 +1,30 @@ +# Control layer: первые проверки + +Дата: 2026-11-04. Дизайн: [installer/CONTROL-LAYER.md](../installer/CONTROL-LAYER.md). + +В `system` реализована чистая модель выбора шага onboarding. Все сборки и тесты +выполнены на `superserv1`, Rust 1.90.0, offline, с одной build job. + +- `cargo test --offline --locked`: PASS, 5 тестов. +- `cargo build --offline --locked --release`: PASS. +- Логи и SHA-256 входов: `/hdd/archipelago/runs/control-layer-gtt47ctq/summary.json` + и соседние stdout/stderr. + +Проверенные сценарии **модели**, не фактических загрузок: + +1. Live → первый installed boot → прерывание создания аккаунта → продолжение → complete. +2. Настроенный Core получает desktop frontend без повторного создания аккаунта. +3. Отсутствующий native adapter выдаёт отдельный результат, без молчаливого fallback. +4. Ложное completion или конфликт аккаунта требуют диагностики. +5. Полный перебор 32 комбинаций context/completion/account/availability: следующий + normal deployment разрешён только для installed + complete + consistent account. + +Наблюдения состояния передаёт вызывающая сторона. Реальные account/PAM/home adapters, +UI, units и блокировки не реализованы; модель пока не ограничивает реальные команды ОС. + +Также на superserv1 сохранена текущая extra.db зеркала и найдены версии GNOME/GDM, +Plasma Login Manager и SDDM; `plasma-setup` отсутствует в просмотренной базе. +Результаты: `/hdd/archipelago/runs/control-layer-research/packages.json`. +Исходники Plasma Setup исследованы на commit +`18c00272d25b3f5d937ec56a1e67bb70eb8b469b`; детали и ссылки — в дизайне. +Desktop-сеансы, установка на диск и пользовательская аутентификация ещё не проверены. diff --git a/CORE-ISO-RESULTS.md b/CORE-ISO-RESULTS.md new file mode 100644 index 0000000..19860af --- /dev/null +++ b/CORE-ISO-RESULTS.md @@ -0,0 +1,145 @@ +# Экспериментальный Core ISO: результат 2026-11-04 + +## core-iso-14: DKMS и накопительные extensions — passed + +Последний уже запущенный прогон на `superserv1` завершился успешно: +`/hdd/archipelago/runs/core-iso-14/acceptance.log`, `passed: true`. +SHA-256 ISO: `82768ebfcf4cc8305fb67677ea651484badd340ef90939e684786c1a1a6cf86b`. +Проверены все накопительные сценарии №12, затем staging v4l2loopback-dkms, +идемпотентность и сохранение pending при неизвестном пакете, reboot, совпадение +vermagic, modprobe и `/dev/video0`, выгрузка модуля, module provenance, отсутствие +headers в явном requested set и build-state в live /var. После добавления strace +и следующего reboot снова прошли modprobe, self-check и status. +Это подтверждение одного DKMS-пакета на VM, не всего оборудования, Secure Boot, +обновления на другое ядро или public release gates. Новые инфраструктурные проверки +выполняются на terra по D-071. Корневой локальный ISO пока остаётся №10. + +## core-iso-12: накопительные repository-backed extensions + +Приёмка `--extensions-sequence` завершилась с `passed: true`: + +- Логи: `/hdd/archipelago/runs/core-iso-12/acceptance.log`. +- VM: `/hdd/archipelago/vms/core-acceptance-cmnlvsxs/`. +- SHA-256: `51fff844b42f846970186f157ece7922b03c8b3c60991cdeea7c79747e20246b`. +- Подтверждены последовательные `nano` → `mc htop` до reboot, зависимости + `gpm/slang/pcre`, повторный запрос без изменения pending и сохранение pending + при неизвестном пакете. После активации добавлен `tree`, затем проверены все + четыре утилиты, Managed Overlay и self-check после следующего reboot. +- Это serial-приёмка; отдельный повтор VGA-приёмки №12 не выполнялся. + +Результат №12 не подтверждает DKMS. +Локальная копия ISO в корне рабочего пространства пока соответствует №10. + +## core-iso-13: DKMS candidate, приёмка не пройдена + +Сборка завершена, обычная накопительная extension-последовательность прошла. +Первый DKMS-запрос отклонён до установки: `linux-headers` содержит +`usr/lib/modules//vdso/*.so`, отсутствовавшие в разрешённом kernel-header +payload. Дополнительно проверен архив: ему принадлежит ссылка `/usr/src/linux`. +В адаптер внесены оба уточнения; повторная проверка ещё требуется. + +- VM: `/hdd/archipelago/vms/core-acceptance-vj2yeohe/`. +- Лог: `/hdd/archipelago/runs/core-iso-13/acceptance.log`, `passed: false`. +- ISO SHA-256: `3f3972bfd55fae8caa0ec262c2ef7ee6d756ebe8f4e157e579c847493b2e1e07`. +- Ошибка отражена в `installed.serial` и сохранённой generation + `1793819914538923291-531`; успешная сборка/загрузка DKMS этим прогоном не доказана. + +## Изолированный DKMS-адаптер: положительный и отрицательные тесты + +На `superserv1` полный staging-прогон завершился успешно: +`/hdd/archipelago/runs/dkms-adapter-final.log`. Проверены установка из закреплённой +базы, точные headers, сборка/установка `v4l2loopback 0.15.4` для ядра +`7.2.14-arch1-1`, vermagic, сохранность базовых модулей, depmod и initramfs. +Headers учитываются как автоматически добавленная зависимость, отдельно от intent. + +`/hdd/archipelago/runs/dkms-failure-01.log` подтверждает два отрицательных сценария: +неверный kernel.release в headers и принудительный отказ make. Оба блокируют +финализацию с ненулевым результатом; checksums существующих модулей сохраняются. +Это изолированные проверки, не доказательство boot/modprobe или сохранения pending +при реальной ошибке DKMS в установленной VM. Полная VM-приёмка запущена для №14. + +## Актуальный локальный образ: core-iso-10, tty1 и ttyS0 + +Образ `/hdd/archipelago/runs/core-iso-10/output/archipelago-core-latest.iso` прошёл +две полные приёмки на `superserv1`: + +- Serial: `/hdd/archipelago/runs/core-iso-10/acceptance.log`, VM + `/hdd/archipelago/vms/core-acceptance-qftvvumz/`, `passed: true`. +- VGA: `/hdd/archipelago/runs/core-iso-10/acceptance-tty1-final.log`, VM + `/hdd/archipelago/vms/core-acceptance-npyjeax2/`, `passed: true`, + завершение 2026-11-04 16:28:20 UTC. +- SHA-256 ISO: `07a0857df87c59e48bed4b115d26e4fb1121b4e96a059818ca9bbbe4b8886b41`. + +На tty1 пользователь создан через эмулируемую клавиатуру; одновременный Enter +на ttyS0 получает ожидание блокировки. Проверены `/etc/archipelago/provision-console`, +единственность аккаунта, активные getty обеих консолей и фактический login на tty1. +В обоих сценариях затем проходят проверки служб, read-only `/usr`, пакета и прав, +активация Managed Overlay и nano Host Extension после явных перезагрузок. + +Предыдущие VGA-прогоны были неуспешны из-за ненадёжного тестового ввода по таймеру +и OCR мелкого шрифта. Итоговый тест ожидает экранных приглашений с масштабированием +и инверсией изображения; исправления harness не меняли сам ISO №10. +Пользователь затем сообщил об успешном завершении ручных проверок этого образа. +Это пользовательское подтверждение; отдельные аппаратные логи в стенд не переданы. + +## Предыдущая подтверждённая база: core-iso-09 + +Прогон `core-iso-09` на `superserv1` завершил сборку и полную приёмку +`probes/core_iso_acceptance.py`: `passed: true`, 13 гостевых команд с кодом 0, +событие `acceptance-passed` в 15:01:57 UTC. + +## Артефакты на superserv1 + +- ISO: `/hdd/archipelago/runs/core-iso-09/output/archipelago-core-latest.iso`. +- SHA-256: `f66e488f8dec40a13b6439e627814c41181d4e63d8633e483ea1f3d3ab848327`. +- Подписанный пакет и репозиторий: `/hdd/archipelago/runs/core-iso-09/output/packages/`. +- Версия пакета: `archipelago 0.0.0.f653c612533b5d15c0dee3ac-1`. +- Рецепт, checksums входов, mtree, публичный ключ и пакетные журналы: + `/hdd/archipelago/runs/core-iso-09/evidence/`. +- Сборочный журнал и журнал приёмки: `driver.log`, `acceptance.log` в каталоге прогона. +- VM: `/hdd/archipelago/vms/core-acceptance-6qxo1s5v/`; + доказательства: `summary.json`, `events.jsonl`, `live.serial`, `installed.serial`. + +## Подтверждено + +1. Rust-бинарник собирает ISO через Arch nspawn на AlmaLinux; рабочий ext4-образ + хранится на ZFS в `/hdd`. +2. `archipelago` и его runtime-инфраструктура устанавливаются пакетом pacman в + Core и live. В обоих rootfs проходят `pacman -Qkk` и manifest прав. +3. Live загружается в Q35/KVM/OVMF VM; установщик размечает новый диск GPT, + создаёт FAT32 ESP/ext4 root, устанавливает systemd-boot и OSTree deployment. +4. Установленная система загружается без ISO, создаёт основного пользователя; + вход по паролю и сохранение home работают. +5. `systemd-networkd`, `systemd-resolved`, `sshd` активны; `/usr` read-only, + попытка записи отклонена. +6. Managed Overlay `test-marker` подготавливается без изменения текущего `/usr` + и активируется после явной перезагрузки. +7. Подписанный nano fixture устанавливается offline через nspawn staging; + после явной перезагрузки nano запускается, marker overlay сохраняется, + базовые службы активны. +8. `archipelago self-check` проходит в live, после первого installed boot, + после overlay и после nano: принадлежность бинарника пакету, `pacman -Qkk`, + `0755 root:root` для бинарника, `0644 root:root` для регулярных данных пакета. +9. Отрицательный live-тест снимает `+x`, получает отказ self-check через копию + бинарника в `/run`, восстанавливает права и повторно успешно проходит проверку. + +## Исправленные интеграционные дефекты + +- Прямая вставка бинарника в archiso заменена пакетом с явными правами. +- Для соответствия OSTree mtime используется `SOURCE_DATE_EPOCH=0` при makepkg; + mtree проверяется до установки. Одного `touch` в `package()` недостаточно: + makepkg затем нормализует время самостоятельно. +- Публичный лабораторный ключ поставляется в пакете; target keyring создаётся + штатным pacman-key. Приватный ключ сборщика в образ не переносится. +- Добавлена стандартная ссылка `/ostree` на `sysroot/ostree`. +- Перед Host Extension транзакцией выполняется systemd-sysusers для временного + staging, включая пользователя `alpm`; staging identities не переносятся в commit. + +## Границы результата + +Это успешная функциональная приёмка узкого экспериментального Core-only профиля +с фиксированными fixtures. Побитовая воспроизводимость, публичные release gates, +общие схемы слоёв/lockfile/package DB и публичная signing policy не доказаны этим +прогоном. Реализация использует Bash-адаптеры, встроенные в Rust-бинарник. +Исходники пока содержат незакоммиченные изменения; package evidence фиксирует +checksums бинарника и runtime-входов, но не заменяет полный source provenance. diff --git a/E00-RESULTS.md b/E00-RESULTS.md new file mode 100644 index 0000000..ca94518 --- /dev/null +++ b/E00-RESULTS.md @@ -0,0 +1,41 @@ +# E00: проверка стенда superserv1 + +Дата: 2026-11-04. Статус: частично выполнен — KVM/QMP проверен, Arch/nspawn ещё нет. + +## Входы и результаты + +- Код: `probes/kvm_smoke.py`. +- SHA-256 исходника: `a3dc145a17524805de64c1347aa4e096b593618e43d12ab9c2659f04c8909b70`. +- Хост: superserv1, AlmaLinux 9.8 x86_64. +- QEMU: `/usr/libexec/qemu-kvm`, пакет `qemu-kvm-10.1.0-17.el9_8.alma.1`. +- OVMF: `/usr/share/edk2/ovmf/OVMF_CODE.fd` и отдельная временная копия VARS; + пакет `edk2-ovmf-20241117-8.el9.noarch`. +- Фактические хеши QEMU/прошивок, QMP-ответы, команды и stderr сохранены в отчёте. +- Отчёты: `superserv1:/hdd/archipelago/runs/e00-86voj7dl/`. + +| Проверка | Результат | +|---|---| +| Компиляция Python через py_compile на superserv1 | PASS | +| Q35, 1 vCPU, 256 MiB, OVMF, без сети и системного диска | Процесс создан без sudo | +| QMP query-kvm | present=true, enabled=true; TCG не использован | +| QMP cont/query-status/stop/query-status/quit | running → paused → exit 0 | +| Отсутствующая прошивка | Ожидаемый exit 1, JSON-ошибка; QEMU не запущен | +| Timeout: управляемая подмена QEMU зависающим процессом | Через 15 секунд exit 1; дочерний PID завершён | +| Очистка временного NVRAM после успеха и timeout | Остаточных kvm-smoke каталогов нет | + +Подмена процесса в timeout-сценарии проверяет механизм ограничения harness, +а не утверждает моделирование зависания гостевого ядра. Загрузка OVMF/Linux, +systemd-boot, OSTree deployment, пользовательский вход и сборочная изоляция +этими результатами не доказаны. + +## Зеркало и следующий gate + +На superserv1 проверен доступ к `https://mirror.nw-sys.ru/archlinux/` (HTTP 200). +В корневом индексе обнаружены core/extra/multilib и testing/staging репозитории, +pool, images, iso и latest. В `iso/` перечислены 2026.09.01, 2026.10.01 и 2026.11.01. +Это наблюдение индекса, не загрузка или проверка подписей содержимого. + +Датированный ISO/bootstrap не доказывает наличия полного неизменяемого пакетного +snapshot той же даты. Архив пакетных баз/содержимого нужно уточнить перед E01 либо +согласовать локальную заморозку выбранного набора. Не подменять общий snapshot +использованием rolling mirror или смешением ISO-окружения с latest пакетами. diff --git a/E01-RESULTS.md b/E01-RESULTS.md new file mode 100644 index 0000000..c7f8cee --- /dev/null +++ b/E01-RESULTS.md @@ -0,0 +1,62 @@ +# E01: Rust и первый запуск Arch bootstrap + +Дата: 2026-11-04. Статус: частично выполнен. +Все исполнения и сборки выполнены на `superserv1` в `/hdd/archipelago`. + +## Rust + +- Rust 1.90.0, commit `1159e78c4747b02ef996e55082b704c09b970588`, LLVM 20.1.8. +- Установлен minimal toolchain через `https://sh.rustup.rs`, без изменения PATH профиля. +- `RUSTUP_HOME=/hdd/archipelago/cache/rustup`. +- `CARGO_HOME=/hdd/archipelago/cache/cargo`. +- `CARGO_TARGET_DIR=/hdd/archipelago/cache/target`, `CARGO_BUILD_JOBS=1`. +- `TMPDIR=/hdd/archipelago/tmp`. +- `contracts` содержит внутренние типы, `composer` — чистую проверку заголовков. + Внешние схемы и идентичность snapshot этим не фиксируются. +- Временная сборка использует соседние репозитории через path dependency. +- `cargo test --offline --locked`: PASS, 5 интеграционных тестов. +- `cargo build --offline --locked --release`: PASS, обе библиотеки. +- Логи, версия rustc и SHA-256 исходников: `runs/e01-rust/` на стенде. + +Тесты покрывают Core-only, необязательный Purpose, неправильную кардинальность, +порядок категорий, смешение snapshots/архитектур и пустую идентичность. +Нет реализации слияния payload, package DB, ABI-проверок или CLI. + +## Bootstrap + +Источник: +`https://mirror.nw-sys.ru/archlinux/iso/2026.11.01/archlinux-bootstrap-2026.11.01-x86_64.tar.zst` + +- SHA-256: `655bc99849b80859173fa39338a6c910185e952173f6a1a61526cfa34ab8339c`. +- Подпись из соседнего `.sig`: GnuPG GOODSIG и VALIDSIG, exit 0. +- Полный fingerprint: `3E80CA1A8B89F69CBA57D98A76A5EF9054449A5C`. +- Личность Pierre Schmitz сверена с `https://archlinux.org/people/developers/` + по HTTPS; ключ получен с keyserver.ubuntu.com по полному fingerprint. + Это лабораторный trust bootstrap, не согласованная release trust policy. +- Keyring проверки: `cache/bootstrap/gnupg`; GnuPG показывает TRUST_UNDEFINED, + поскольку локальная web-of-trust не настраивалась. +- Архив/подпись: `cache/bootstrap/`; логи и inputs.json: `runs/e01-bootstrap/`. +- Rootfs: `tmp/e01-arch/root.x86_64`. + +Запуск через `sudo -n timeout 60 systemd-nspawn` с `--settings=no`, +`--register=no`, `--private-network`, `--read-only` прошёл (exit 0). +Внутри: Arch IMAGE_VERSION=2026.11.01, pacman 7.1.0, libalpm 16.0.1. +Запись в `/usr` отклонена; `/hdd/archipelago`, `/run/host/var` и +`/run/systemd/private` отсутствуют в контейнере. + +Это smoke-проверки видимости и read-only mount, не доказательство изоляции +произвольных пакетных скриптов. Установки пакетов и загрузки гостевой ОС пока нет. + +## Выявленные особенности и следующий шаг + +1. GNU tar при первой распаковке пропустил два заголовка + `LIBARCHIVE.xattr.security.capability`. Этот rootfs годится только для проведённого + smoke. Перед сборками нужна повторная распаковка с сохранением capabilities + и проверка метаданных, предпочтительно через libarchive/bsdtar. +2. На ZFS `hdd`: `xattr=on`, `acltype=off`. Поддержку метаданных staging нужно + проверить отдельно; свойства общего dataset не менялись. +3. nspawn сообщил об отсутствующем `/etc/localtime` при bind mount, но команда + завершилась успешно. Окружение времени нужно явно закрепить для сборок. +4. Следующий gate: исправленная распаковка, writable изолированный staging, + пакетный keyring, фиксация баз/пакетов текущего зеркала и инвентаризация hooks. + Ежемесячный snapshot service по D-063 остаётся отложенным. diff --git a/GNOME-PROBE-2026-11-05.md b/GNOME-PROBE-2026-11-05.md new file mode 100644 index 0000000..8a8a78b --- /dev/null +++ b/GNOME-PROBE-2026-11-05.md @@ -0,0 +1,354 @@ +# Private GNOME probe — 2026-11-05 + +This is integration evidence, not Desktop acceptance or publication approval. +Execution host: `terra` (D-071). + +## Candidate and target + +- Run: `/opt/archipelago/data/private/gnome/20261104T221558Z/`. +- ISO: `build/output/archipelago-gnome-probe.iso`. +- ISO SHA-256: `d8b54dc5327069c99122f3cd212f814af8e8d6f2a6cb122c72a463ccbe55a1ae`. +- Source archive and binary identities: `source.sha256`, `binary.sha256`. +- VM: `vms/gnome-6uhhht2q/`; fresh 48 GiB disk, UEFI, 6 GiB RAM, + virtio graphics, QEMU user networking. No account was injected into the image. +- `preparation.json` only records installation/startup; its + `acceptance_passed: false` must not be treated as a completed acceptance run. + +## Observed results + +1. Live installation succeeded; the installed deployment booted without the ISO. +2. GDM launched GNOME Initial Setup. The graphical wizard selected English/US, + Europe/Moscow and created `coretest`. Authenticated `gdm-password` Wayland + session, UID 1000, wheel membership and home were observed. +3. The packaged onboarding observer failed on scalar `busctl get-property` JSON. + The Rust fix passed nine system tests. A separately copied diagnostic binary + `/var/tmp/archipelago-desktop-check` then reconciled the real authenticated + session and wrote the marker. **This is a modified test target; the original + ISO does not contain the fix.** A clean rebuilt ISO must repeat onboarding. +4. Native subordinate UID/GID allocation supplied `100000:65536`; `podman info` + reported rootless operation and overlay storage on ext4. +5. All nine approved stable Flathub apps installed. Logs report GPG verification + of summary and commits. `flatpak update` succeeded with nothing to update; + an actual newer app revision was not exercised. +6. Removing Text Editor and rerunning seeding preserved its absence + (`REMOVAL_PRESERVED`). It was explicitly reinstalled afterwards. This does not + yet prove persistence over an OS update/rollback. +7. Calculator displayed in the Wayland session; screen lock/unlock worked. + The subsequent calculation interaction did not produce a verified visible + result and remains unresolved. PipeWire, WirePlumber and GNOME portal units + were active; this does not prove audio hardware or all portal functionality. + +## Toolbx investigation + +- Toolbx 0.3 rejects the configured `image = "…@sha256:…"` while deriving its + default container name, before processing an explicit CLI container name. + Both plain and explicitly named creation failed before downloading an image. +- A proposed diagnostic local alias uses the same pinned image, not a replacement + mutable upstream tag. It is not yet a shipping default adapter. +- Direct rootless Podman pull exceeded 20 minutes. A bounded debug retry and + another with HTTP/2 disabled also timed out. Manifest retrieval and the start + of gzip layer streams succeeded; the cause is not established. +- Curl range requests retrieved 1 MiB of a layer via both HTTP/1.1 and HTTP/2 + in under one second. This does not demonstrate successful full-layer transfer. +- Docker on terra pulled the exact manifest successfully. Its saved OCI archive + was transferred to the guest for a separate import/runtime probe. Archive SHA-256 + verification and rootless import succeeded. The subsequent inspection used the + wrong identity (Docker's manifest ID rather than the imported config ID) and + failed before creating a container. The corrected runtime probe passed: + Toolbx created `arch-toolbox-probe`, `toolbox run` reported `ID=arch`, UID/GID + 1000, a writable home and the expected host Purpose marker under `/run/host`. + This used a user-local `localhost/arch-toolbox:probe` alias for the imported + pinned image; the shipped digest-based default remains broken. Container + package installation ran `pacman -Syu` and installed working `tree`; a home + marker was shared, Wayland/D-Bus sockets existed inside, and a container `/usr` + marker was absent on the host. The host CLI checksum remained unchanged. + However, systemd post-transaction hooks failed despite pacman's zero exit: + `systemd-detect-virt --chroot` could not inspect host PID 1 in the rootless + shared PID namespace and systemctl tried an unavailable system manager. + Therefore the package transaction is not fully accepted. An explicit + `SYSTEMD_OFFLINE=1` reinstall of systemd/tree suppressed the systemctl operations + but **still failed tmpfiles hooks** on shared `/run/systemd`, `/tmp`, `/dev`, + `/var/lib/systemd/coredump` and `/var/log/journal` paths. The diagnostic shell + returned zero incorrectly: `! grep ...` is exempt from `set -e`, and the final + `tree --version` succeeded. The retained + `toolbox-offline-hooks-result.json` explicitly records failure. Future assertions + must use `if grep ...; then exit 1; fi` or parse logs outside the guest shell; + neither pacman's nor this probe's zero exit proves hook success. + No default adapter is proven. Runtime manager actions and operations on shared + host paths need separate treatment from container-local cache/account actions. + Socket presence alone does not prove graphical applications from the container. + OS update/rollback persistence is still untested. + +### Container hook adapter follow-up + +`probes/toolbox-systemd-hook.sh` and `toolbox-install-hook-probe.sh` were installed +only into the disposable Toolbx container. They preserve container-local +sysusers/catalog/hwdb/update actions, skip system manager/device runtime operations +and exclude reviewed shared host paths from tmpfiles. Unknown actions fail closed. +Reinstalling systemd/tree with only these overrides still exposed systemctl calls +in the package install scriptlet (`toolbox-adapted-hooks.log`, failed). + +Combining the adapter with explicit `sudo env SYSTEMD_OFFLINE=1 pacman ...` passed +the reinstall and the corrected log assertion, with `ADAPTED_OFFLINE_TRANSACTION_PASS` +in `toolbox-adapted-offline.log`. This demonstrates a viable private adaptation for +the inspected systemd 262.1-1 actions, not a shipped default or exhaustive package +compatibility. Automatic integration into a new container image/package, changed +upstream hook handling and clean-container verification remain outstanding. +- Distinguish OCI manifest digest `3e574107…` from config/image digest `1a89f6de…`. + Docker's containerd-backed image ID here reports the manifest identity; that is + not necessarily the Podman image ID after archive import. + +Evidence is retained beside the VM: `onboarding-diagnostics.log`, +`reconcile-patched.log`, `session-diagnostics.log`, `flatpak-seed-check.log`, +`flatpak-lifecycle.log`, `calculator-*.png`, `calculator-diagnostics.log`, +`toolbox-*.log`, `quay-blob-transport.log`, `podman-storage-diagnostics.log`. +Host image/archive evidence is under `/opt/archipelago/evidence/gnome/`. +The private VM credential file is not publication material. + +## Clean package candidate follow-up + +Candidate `20261105T085910Z` on terra produced ISO SHA-256 +`77583b3f40d3e5d7651ff9c342adce5631d63e77bebcd8f794d1870480723959`. +Its installed VM is `vms/gnome-g4mtw83d` under that private GNOME run. +Native GIS created `coretest`, and the packaged onboarding observer automatically +wrote `/etc/archipelago/provisioned` without replacing the installed binary. +However, strict `archipelago self-check` failed: the empty immutable +`gnome-firstboot` marker acquired deployment-time mtime. The builder now emits a +nonempty marker; clean-image verification of this fix remains pending. + +The private `toolbox 0.3-2.1` package installed successfully. Its binary SHA-256 is +`1c3e56b03da2ac497975965c62a8a40b9ddccdad0441bdf2a589a40c0b368de8`. +`pacman -Qkk toolbox` also reports deployment configuration differences in `/etc`; +the binary identity check alone is not a full package-integrity acceptance. +Normal `toolbox create` correctly resolved `arch-toolbox` and the pinned upstream +digest, but timed out after 600 seconds during blob copying (exit 124). +An already imported image worked in the earlier diagnostic VM; that does not +establish normal first-use registry download. + +The following rebuild, `20261105T093057Z`, failed before ISO creation because the +shared cache held a signature from a previous run's private signing key. A +run-local archive/signature cache now precedes the shared cache in both Core and +live builds, retaining required signature checks and recording archive checksums. +Retry `20261105T093423Z` completed the ISO build and VM installation harness. +ISO SHA-256: `70e1fc4ca0b2ac06d2b846fdb581481426b1c6ae573c4ab210735bd987fe2cad`. +The fresh VM `vms/gnome-s0di9gs0` booted the installed system and completed native +GIS with `coretest` and Europe/Moscow. The packaged observer automatically recorded +onboarding after authenticated user login. `clean-onboarding-self-check.log` +contains `CLEAN_ONBOARDING_SELF_CHECK_PASS`: strict self-check reports 49 files, +zero altered files, correct ownership/permissions; the nonempty marker and patched +Toolbx binary checksum also passed. No diagnostic binary replacement was used. + +Evidence in the completed candidate VM: `clean-onboarding-check.log`, +`marker-integrity-diagnostics.log`, and `clean-toolbox-default.log`. Failed-run +build logs and signing-key evidence remain in their respective run directories. + +The subsequent 120-second `podman-direct-debug.log` timed out, but showed successful +manifest/config retrieval, gzip detection for all three blobs and `Applying tar` +before termination. Thus the earlier copy-stage timeout is not evidence of a +complete network stall. Terra simultaneously showed high load and active swapping +(about 18 GiB swap used), with two 6 GiB GNOME VMs plus the builder. An ACPI +power-off request was sent to the older diagnostic VM, preserving its disk and +logs. The longer direct pull also timed out after 1800 seconds (exit 124), so +create/run were not reached (`podman-direct-extended.log`). Resource pressure +remains a hypothesis, not an established root cause. The separate full-blob +transport probe verified the 11,961-byte blob by size and SHA-256, then timed out +on the 320,480,148-byte blob before completing its first 1 MiB read +(`full-blob-transport.log`). This reproduces a transfer problem outside Podman; +zero completed reads does not establish zero bytes received on the wire. A +comparison of ranged and full responses also timed out in the guest +(`blob-range-comparison.log`): both ranges returned valid HTTP 206 headers and the +full request HTTP 200, but no first 16 KiB read completed for the initial range or +full response; the range at offset 16 MiB completed only one 16 KiB read. The +probe's exit zero means its diagnostic loop completed, not that transfers passed. +The equivalent terra-host comparison succeeded: both ranges and the first 1 MiB +of the full response transferred in 1.29–1.49 seconds +(`/opt/archipelago/evidence/gnome/terra-blob-range-comparison.log`). The difference +points to the guest network path, without yet identifying the failing component. +The temporary guest-only MTU 1280 probe also timed out reading the body +(`blob-mtu1280.log`); its EXIT trap restores the original MTU 1500. This does not +support lowering guest MTU as a fix. TCP diagnostics confirmed restoration to +1500 and showed an established connection with 32,928 received bytes, no queued +application data and a nonzero receive window. Disabling TCP window scaling also +timed out; the original value 1 was restored (`blob-no-window-scaling.log`). + +Guest and terra resolved `cdn01.quay.io` to different addresses. A guest Python +probe directed that hostname to terra's observed `96.16.53.153`, retaining normal +TLS hostname verification and changing no system DNS, but still timed out +(`blob-terra-cdn-address.log`). Thus this address difference alone does not explain +the failure. A diagnostic restart with e1000 completed, and the guest confirmed +the e1000 driver; the transfer still timed out (`blob-e1000.log`). The original +QEMU arguments are retained in `qemu-before-e1000.json`. This is a +lab-network experiment, not a change to the distribution's network defaults. + +At the user's request, further Toolbx network diagnostics are deferred. The lab is +in Russia, where CDN access can be unreliable; the user plans to repeat this test +outside Russia. The root cause remains unconfirmed and direct download remains +unverified. Independent GNOME overlay, Host Extension and persistence acceptance +continues. + +## Outstanding acceptance + +### Full GNOME candidate: deployment checks + +On `20261105T093423Z/vms/gnome-s0di9gs0`, `test-marker` was staged as commit +`97aea32f017bba4bdd5010557bfa1f845bd87857ab369af425c09d2591675f18` from booted +base `9d524ac7223334c144f9531be6291b7b89760dc977a7395b560fe589b2b969a1`. +The running `/usr` remained unchanged until an explicit test reboot. After reboot, +the overlay marker and strict self-check passed; the passwd record, onboarding +marker and user-owned home marker were preserved. GDM, NetworkManager, +systemd-resolved and sshd were active. Evidence: `gnome-overlay-stage.log` and +`gnome-overlay-reboot.log` (`GNOME_OVERLAY_ACTIVATION_PERSISTENCE_PASS`). Native +application packages are present and `systemctl --failed` listed zero failed +units (`gnome-post-reboot-inventory.log`); this is not application interaction +acceptance. Nano staging produced commit +`cf88677aa2d065be04087131b639097850e158c6eb8b975119e11312ab378592`, but the combined +staging/negative-request SSH harness timed out after 1200 seconds. The success +sentinel was not reached. Subsequent inspection found no active composition +process and confirmed that the staged nano deployment still matched the saved +pending-state JSON (`gnome-nano-timeout-diagnostics.log`). This is not a completed +negative-package acceptance. The separate systemd-supervised retry passed in +4 minutes 32 seconds: pacman rejected the nonexistent package, the pending-state +JSON remained identical, and strict self-check passed +(`gnome-negative-extension-retry.log`, `GNOME_NANO_FAILURE_PRESERVATION_PASS`). +Nano activation and persistence checks passed after an explicit reboot +(`gnome-nano-activation.log`, `GNOME_NANO_ACTIVATION_PERSISTENCE_PASS`). The booted +commit is `cf88677aa2d065be04087131b639097850e158c6eb8b975119e11312ab378592`; +`nano 9.3-1` runs, the overlay marker remains present, strict self-check reports +49 files with no alterations, and the account, home marker and GUI-selected dark +theme persist. Required GNOME/network/SSH services are active. Status reports +the booted Host Extension composition as unsupported. +The implementation checks out the full base before +running package resolution, which adds substantial work even for invalid names. + +After the overlay reboot, native GDM login restored a Wayland session for +`coretest` (`gnome-overlay-session.log`). Settings rendered its Network panel +with the wired connection active, then the Appearance panel. Selecting Dark via +the GUI changed `org.gnome.desktop.interface color-scheme` to `prefer-dark`, +verified in `gnome-gui-theme.log` (`GNOME_GUI_THEME_CHANGE_PASS`). Screenshots: +`settings-selected.png`, `appearance-ready.png`, `appearance-dark.png`. +Persistence of this preference across nano activation passed as recorded above. + +### Remaining gates + +Explicit rollback using native `ostree admin set-default 1` followed by a test +reboot failed: the readiness harness timed out and the initramfs entered emergency +mode. `installed.serial` reports that `ostree-prepare-root` could not find the +selected `/ostree/boot.1/archipelago/.../0` root. This was not an Archipelago CLI +rollback command (none is implemented yet). The current ESP copy adapter runs +only through `ostree-finalize-staged.service` ExecStopPost; immediate boot-order +changes may therefore leave ESP entries stale. The attempted live read-only +comparison using a temporary QEMU disk snapshot did not reach the live shell: +`rollback-live-inspection.log` shows the installed OSTree boot path and the same +emergency-mode failure. Existing UEFI boot selection apparently took precedence +over the requested CD boot; this needs verification with fresh recovery NVRAM. +After the reported network interruption, SSH to terra worked at 2026-11-05 +11:57 UTC; no QEMU process for this VM remained. No ESP comparison or repair was +completed. Do not count rollback as passed. + +The retry with fresh OVMF variables reached the live shell and completed a +read-only inspection (`rollback-live-inspection-retry.log`, exit 0). Root's active +BLS entries use `/ostree/boot.0/...`, while ESP entries still use `/ostree/boot.1/...`; +only `boot.0 -> boot.0.1` exists. This confirms stale ESP entries after the immediate +`set-default` operation. ESP repair from the active root entries, with the previous +loader directory backed up at ESP `/archipelago-pre-rollback-repair/`, completed +successfully (`rollback-esp-repair.log`). Disk-only boot reached the selected +overlay deployment; nano is absent, the overlay, account/home and dark preference +are preserved, strict self-check and required services pass +(`rollback-repaired-check.log`, `REPAIRED_ROLLBACK_PERSISTENCE_PASS`). This result +includes a manual ESP repair, not an unassisted rollback pass. + +The builder now adds a vendor multi-user target dependency on the native +`ostree-finalize-staged.service`. This keeps its existing successful-finalization +ESP-sync hook active on ordinary installed boots, including boots where only +`set-default` is used. The native `ostree-booted` condition excludes live boot. +Generated Core/GNOME shell tests passed on terra. The equivalent dependency was +enabled in the diagnostic VM via `/etc/systemd/system/multi-user.target.wants/`; +the native finalization service starts successfully with no pending deployment. +A two-way boot-selection test without manual ESP copying passed +(`boot-sync-roundtrip.log`, `BOOT_SYNC_ROUNDTRIP_PASS`). Both exact selected +commits booted, ESP entries matched root BLS entries, strict self-check passed, +and the account/home/dark preference persisted. Nano was present only in its +extension deployment. On return to the overlay deployment, the native finalizer +was already active through the added dependency. A fresh packaged-image check +is still required; the existing VM contains diagnostic `/etc` dependencies. + +Fresh candidate `20261105T120938Z` completed ISO construction and the installation +harness under `archipelago-gnome-boot-sync-rebuild.service` (exit 0). +ISO SHA-256: `d209eaeee4ef37630815e5346c69c133e97218590007a5d445b3a0c63f1f1d79`. +VM: `vms/gnome-3n6ya3pm`. The rebuild unit's cleanup terminated the daemonized +QEMU child, so the installed disk was restarted under the independent +`archipelago-gnome-clean-vm.service` (Type=forking, QEMU PIDFile). Installation +success does not yet prove clean onboarding or the packaged boot-sync fix. + +Native GIS completed in this fresh VM, but `clean-packaged-overlay.log` failed +strict self-check before overlay staging: the packaged vendor dependency symlink +had a deployment-time mtime differing from MTREE (51 files, one altered). +`packaged-symlink-diagnostics.log` confirmed that the native finalizer was active; +the VM was then powered off. No integrity check was relaxed. + +The builder replaces that symlink with the regular vendor drop-in +`multi-user.target.d/20-archipelago-boot-sync.conf`, containing +`Wants=ostree-finalize-staged.service`. Generated shell tests and the locked offline +CLI release build passed on terra. A new ISO/install run is started under +`archipelago-gnome-boot-sync-dropin.service`; clean acceptance remains pending. +The harness now accepts `--vm-unit` to launch installed QEMU in a separate +Type=forking systemd service instead of losing it during build-unit cleanup. + +Candidate `20261105T131221Z` completed the rebuilt ISO and fresh installation. +VM `vms/gnome-sfyobspe` runs independently as `archipelago-gnome-dropin-vm.service`. +Native GIS completed with `coretest` and Moscow selected. A combined strict +self-check, vendor drop-in dependency check and overlay staging test is running +(`clean-dropin-overlay.log`). No diagnostic `/etc` boot-service dependency has +been added to this VM. Older test VMs are powered off to conserve terra resources. + +### Clean packaged boot-sync acceptance on yabloko + +At the user's request, VM `gnome-sfyobspe` was shut down cleanly and transferred +directly from terra to yabloko. The interrupted terra overlay attempt had no +pending deployment. Disk and UEFI variables SHA-256 matched after transfer. +The original VM remains stopped on terra. + +On yabloko the overlay transaction passed in 2m59s without swap, producing +`fa3be3310a36d28744c49e9dc524dce971d9213c2f2847756d46b20b4547094d`. +An explicit reboot loaded that exact commit. Native `ostree admin set-default 1` +and another explicit reboot returned to base +`542f6482a38eb99a19104a50bbde6c5422d0e6313f3f12c52c0aa22f70c1519d`. +Both boots passed strict self-check (51 files, zero alterations), active packaged +finalizer, equality of root/ESP BLS entries, account identity and home marker +preservation. The overlay marker was present only in the overlay deployment. +No diagnostic boot-service dependency or manual ESP repair was used. + +Evidence: `yabloko-overlay.log` and `yabloko-boot-roundtrip.log`, copied directly +back to the candidate's VM directory on terra. This passes the clean packaged +boot-sync/rollback regression; it does not establish full Desktop release +acceptance or installed-host registry update support. + +Host Extension `nano` then staged successfully on yabloko in 4m00s without swap. +After explicit reboot, the booted checksum was +`e08fa3cd573ec0528b4388d9df74d7bd51ee9969a7e13da40d3ab37dd64bd1bf`. +Nano 9.3-1, strict self-check (51 files, zero alterations), active finalizer, +root/ESP BLS equality, account identity and home marker all passed. +Requesting `archipelago-nonexistent-acceptance-package` failed as expected; +before/after deployment status JSON was identical. Evidence +`yabloko-nano-stage.log` and `yabloko-nano-acceptance.log` is archived beside +the candidate's other VM evidence on terra. + +After the nano boot, native GDM password login opened an active Wayland session. +System and user failed-unit lists were empty; GDM and NetworkManager were active. +All nine approved Flatpak application IDs were installed system-wide. Calculator +launched from that installation and native QMP keyboard input computed `2-1 = 1`. +Evidence `desktop-inventory.log`, `desktop-login-check.log` and +`calculator-verified.png` was copied directly to terra. This checks Calculator +interaction, not all functionality of the nine applications. + +The pinned builder tools image and bootstrap were transferred directly from terra +to yabloko with matching identities. The offline locked CLI release build on +yabloko passed in 1m48s. Artifact repositories/publication remain on terra. + +Working default Arch Toolbx creation and container +package/home/session/update persistence; full GNOME native/Flatpak interaction; +inherited Core overlay/extension scenarios on this candidate; authenticated CLI +and GNOME Software whole-image updates; reproducibility and publication gates. +The probe still masks stock PackageKit ALPM and supplies no OS GUI update backend. +Public portal artifacts, scheduled builds and automatic retention are not enabled +by these partial results. diff --git a/IMPLEMENTATION-PLAN.md b/IMPLEMENTATION-PLAN.md new file mode 100644 index 0000000..71bb457 --- /dev/null +++ b/IMPLEMENTATION-PLAN.md @@ -0,0 +1,272 @@ +# План реализации и экспериментальной проверки RFC v0 + +Статус: рабочий инженерный план, не новое принятое архитектурное решение. +Основа: RFC-0001–0007 и D-001–D-065. Цель — проверять наиболее рискованные +интеграционные контракты до разрастания CLI и продуктового кода. + +## 1. Организация исходников + +Созданы самостоятельные Git-репозитории на ветке `main`, без remotes и начальных +коммитов, с identity `Pavel Isaev `: + +| Репозиторий | Ответственность | +|---|---| +| `cli` | Единый бинарник `archipelago`, команды трёх контекстов, представление ошибок/status/diff | +| `contracts` | Версионированные схемы артефактов, канонизация, валидация, fixtures совместимости | +| `builder` | Snapshot, изолированные Arch-сборки, инвентаризация hooks, layer commits | +| `composer` | Пакетный план, владение и конфликты, сборка DB/дерева, finalizers, image commit | +| `system` | Desired/pending/booted state, Host Extensions, staged updates, retention, явный rollback | +| `installer` | Подготовка целевого диска, OSTree stateroot, пользователь, systemd-boot | +| `registry` | Публикация/получение артефактов, refs, подписи, каналы, доступность и GC roots | +| `manifests` | Исходные определения Core/Purpose/overlays, профили и рецепты собственных пакетов | +| `test-lab` | Исследования, harness, VM fixtures, отрицательные сценарии и доказательства | + +Разделение репозиториев не означает отдельные daemons или обязательные сетевые +сервисы. Реализация библиотек/адаптеров должна собираться в единый CLI по RFC-0001. +Rust принят D-062; способ межрепозиторной сборки ещё нужно уточнить. Интеграционный +набор должен закреплять точные revisions, а не собирать произвольные HEAD модулей. +Первым наполнен `test-lab`; продуктовый код начинается с внутренних типов `contracts` +и проверки входов `composer`, без стабилизации внешних схем. + +## 2. Стенд и исходные наблюдения + +Все исполнения, компиляции и тесты — на `superserv1`, Tailscale SSH без пароля. +Рабочий каталог `/hdd/archipelago` на существующем ZFS; не использовать корневой +том для образов, rootfs, пакетов или toolchain caches. Использовать отдельные +каталоги `src/`, `cache/`, `tmp/`, `runs/`, `artifacts/`, `vms/`. + +Наблюдения при проверке 2026-11-04: + +- AlmaLinux 9.8, x86_64, QEMU 10.1, OVMF и systemd-nspawn установлены. +- `/dev/kvm` доступен текущему пользователю; QMP подтверждает `enabled: true`. +- Пробная Q35/UEFI VM с 1 vCPU и 256 MiB запущена, остановлена и завершена. + Это ещё не загрузка гостевой ОС. +- На ZFS доступно около 719 GiB; свободно/доступно около 7.8 GiB RAM, swap занят. + Начинать с одной VM, лимитировать RAM и параллельность, замерять ресурсы перед запуском. +- Предыдущий кандидат `weights-t800`: на `/` около 1 GiB, нет прямого доступа + пользователя к KVM и ряда инструментов; текущий стенд перенесён на `superserv1`. +- `https://mirror.nw-sys.ru/archlinux/` отвечает HTTP 200 с `superserv1`. + +Предупреждения virt-host-validate о passthrough IOMMU и confidential guests не +являются требованиями первого VM-профиля. Проверку cgroups/изоляции нужно провести +отдельно для nspawn; не считать успешный KVM smoke доказательством сборочной изоляции. + +## 3. Правила экспериментов + +Для каждого эксперимента фиксировать: + +1. Гипотезу, связанные D/RFC и открытые вопросы. +2. Точные входы, ревизии исходников, версии среды/инструментов, команды и хеши. +3. Положительный сценарий, отрицательные сценарии и наблюдаемые критерии успеха. +4. Exit codes, stdout/stderr, дерево/DB diff и сохраняемые артефакты. +5. Итог: подтверждено / опровергнуто / не проверено; прототипное допущение отдельно. + +Ошибка гипотезы вызывает уточнение контракта или обсуждение RFC, а не скрытый обход +инвариантов. Изменения принятых решений согласуются явно и синхронизируются в EN/RU. +Воспроизводимость проверять с первых малых артефактов, не откладывать до релиза. + +## 4. Последовательность работ + +### E00 — Исполнимый лабораторный стенд + +Репозиторий: `test-lab`. + +- Проверить SSH, диски, KVM, OVMF, версии, доступы и ограничение ресурсов. +- Сохранить повторяемый QMP smoke probe; исключить незаметный fallback на TCG. +- Проверить ошибку отсутствующей прошивки, timeout/cleanup процесса и временного NVRAM. +- Затем проверить nspawn на отдельном Arch rootfs: пакетный скрипт не должен получать + доступ к host service manager, host ESP или записываемому host `/usr`/`/var`. + +Выход: воспроизводимый способ запускать эксперименты и записи результатов. +Связь: RFC-0003 §2–3, RFC-0005 §6. KVM smoke не закрывает остальные проверки E00. + +### E01 — Неизменяемые пакетные входы и bootstrap Arch + +Репозитории: `contracts`, `builder`, `test-lab`. + +- Уточнить snapshot-профиль: x86_64, порядок репозиториев, необходимые базы, + ключи/проверка подписей, хранение package checksums и доступность пакетов. +- Исследовать зеркало пользователя: наличие датированных snapshots/архива и + bootstrap-артефакта. Rolling mirror — транспорт, не immutable identity. +- До появления ежемесячных snapshots по D-063 сохранять точные базы и выбранные + пакеты каждого эксперимента; проверять совпадение пакета с базой, повторять захват при гонке. +- Bootstrap и пакетные операции выполнять в отдельном Arch rootfs, без pacman + на live AlmaLinux. Не использовать latest/mutable URL как доказательство pinning. +- Повреждённый пакет, неверная подпись, отсутствующий locked artifact и смена базы + зеркала должны приводить к явной ошибке, без подстановки свежей версии. + +Выход: проверенный экспериментальный snapshot и повторное создание Arch-среды. +Контракты до реализации: snapshot schema/canonicalization/trust; вопросы 17–19, 47. +Связь: D-023, D-035, D-042/D-043. Схемы прототипа не объявляются стабильными. + +### E02 — Главный риск: пакетный payload, владение и pacman DB + +Репозитории: `builder`, `composer`, `contracts`. + +- Собрать независимо два малых слоя с одной общей зависимостью из одного snapshot. +- Записать payload и индекс в layer commits; выбрать пакеты из этих commits без + повторной установки из Package Registry при композиции. +- Сопоставить альтернативы сборки DB со штатными pacman/libalpm: какие записи можно + переносить, где нужна адаптация desc/files/mtree/backup/install reason. +- Проверить `pacman -Q`, владение файлов и согласованность DB с итоговым деревом; + отделить ожидаемые объявленные overrides от настоящих ошибок целостности. +- Отдельно проверить `/etc -> /usr/etc`, генерируемые файлы, usr-merge aliases, + xattrs/capabilities, non-root UID/GID и `/opt -> /var/opt`. +- Негативные случаи: разные snapshots, конкурирующие владельцы, несовместимая замена, + изменение типа без разрешения, override через симлинк, неразрешённая рекурсия удаления. +- Удаление слоя-владельца общей зависимости сохраняет пакет и переназначает владельца. +- Сравнить содержимое общей зависимости из независимых сборок: scriptlets и локальные + build-ID не должны делать одинаковую package identity неоднозначной. + +Выход: RFC реализации package index/DB, реальные fixtures и доказательства. +Это gate до полноценной композиции ОС, а не место для собственного пакетного менеджера. +Связь: D-024–D-026, D-038–D-044, D-054; вопросы 1–8, 46, 50–55, 61–62. + +### E03 — Hooks, finalizers и ранняя воспроизводимость + +Репозитории: `builder`, `composer`. + +- Инвентаризировать фактические `.INSTALL` и ALPM hooks выбранных пакетов. +- Реализовать минимальный проверенный набор адаптеров с явными фазами/выходами. +- Доказать, что ошибка PostTransaction блокирует результат даже при успехе pacman. +- Проверить общий кэш из двух слоёв и исчезновение записей при удалении одного. +- Зафиксировать порядок: модули/подпись → depmod → mkinitcpio; настройки библиотек + перед потребителями. Не генерировать machine-id/host keys в публикуемом образе. +- Выполнить две чистые сборки без общего output cache, варьируя рабочий путь и время; + сравнить дерево, метаданные и коммит. Уточнить timestamp/parent и отделить runtime logs + и аттестации от канонической идентичности. +- Проверить, что finalizers не изменяют общие OSTree objects через hardlinks. + +Выход: классификация snapshot hooks, граф finalizers, отчёт о недетерминизме. +Связь: D-027, D-050, D-058/D-059; вопросы 52–56, 70. + +### E04 — Первый загружаемый Core-only образ + +Репозитории: `manifests`, `builder`, `composer`, `installer`, `test-lab`. + +- Выбрать пакетные дополнения к `base` + `linux` и экспериментальный VM storage profile. +- D-065 согласовал GPT/FAT32 ESP/ext4 root, UEFI/systemd-boot без шифрования/Secure Boot. + Сквозная приёмка: binary/nspawn → ISO → live-разметка/установка → disk boot → + provisioning/login/services → staged Managed Overlay → staged nano Host Extension. + Harness: `probes/core_iso_acceptance.py`; изменения ОС выполняются только в новой VM. +- Проверить именно Arch-пакет OSTree и его mkinitcpio hook, не писать дубликат заранее. +- Создать полный image commit из Core, отдельно от layer commit, с нулём Purpose. +- Control layer проектируется с начала E04: [дизайн установки и onboarding](../installer/CONTROL-LAYER.md). + Lab создаёт файл диска; live `archipelago` подготавливает target и устанавливает ОС. +- Установить на отдельный образ виртуального диска, один stateroot `archipelago`, + systemd-boot/OVMF, штатные persistence-симлинки и `/usr/etc` defaults. +- Отложить создание основного пользователя до первого boot установленной ОС: + CLI onboarding Core, затем проверенный login; следующие deployments — после завершения. + Проверить прерывания установки/создания аккаунта, повтор и отсутствие повторного мастера. +- Загрузить ОС, проверить локальный вход, booted commit, immutable `/usr`, persistence, + sysusers/tmpfiles и запросы пакетной DB. Тест входа — аутентификация, не просто getty. +- Проверить неисправный initramfs/boot entry и понятную диагностику. + +Выход: bootable Core-only fixture, serial log и проверяемый отчёт. +Контракты: диски/ESP, boot artifacts, создание пользователя; вопросы 23–28, 48, 57, 63–64. +Связь: D-030–D-036, D-055. Core-only — этап снижения рисков перед полным профилем D-053. + +### E05 — Overlays и Host Extensions на реальном deployment + +Репозитории: `composer`, `system`, `cli`. + +- Применить managed overlay, активировать новый deployment, проверить объявленный эффект. +- Добавить пакет Host Extension по имени из snapshot и отдельно из локального файла; + проверить функциональность после активации, а не только exit CLI. +- Проверить явную замену базового пакета, отмену override, удаление расширения и + сохранение данных/истории. Desired, pending и booted состояния должны различаться. +- Ошибка одного расширения отвергает весь набор; чистый upstream остаётся доступен, + boot selection не меняется, fallback только по явной команде. +- Статус текущего deployment отражает фактическое происхождение изменений для issue. + +Выход: полный функциональный gate Core по D-051/D-055; поколения и правильная DB. +Связь: D-017, D-037/D-038, D-054–D-057; вопросы 29–36, 61, 68. + +### E06 — Purpose и наследуемые проверки + +Репозитории: `manifests`, `system`, `composer`, `test-lab`. + +- До этапа выбрать один конкретный Purpose для D-053, его службы, defaults и пробы. +- По D-064 проверить native onboarding GNOME/KDE: создание пользователя до обычного + входа, completion, cleanup временного autologin и переход с уже настроенного Core. + Подходящие кандидаты — gnome-initial-setup и plasma-setup; точные адаптеры открыты. +- Из Core-only выбрать Purpose; второй Purpose отклоняется. Данные сохраняются. +- На полном Core + Purpose повторить boot/login/Host Extension/Managed Overlay, + затем проверить реальную функцию всех целевых служб в чистой среде. +- Проверить несовместимый overlay, administrator enablement, socket/oneshot lifecycle, + отсутствие запуска будущих служб на текущем хосте во время подготовки. + +Выход: первый сквозной Core + Purpose профиль. Связь: D-041, D-048, D-051–D-055. + +### E07 — Обновление, откат и сбои + +Репозитории: `system`, `installer`, `test-lab`. + +- Подготовить второй snapshot/образ и staged deployment; проверить позднее изменение + `/etc` до shutdown, финализацию и идентичность реально загруженного коммита. +- Boot checks привязаны к deployment и текущему boot; старый успех не разрешает GC. +- При провале checks нет изменения default entry/reboot; только диагностика и команда. +- Проверить ручной rollback, сохранение primary user/home, допустимое исчезновение + позднего пользователя и восстановление исходных UID/GID без подмены данных. +- Проверить retention booted/previous/pending/pinned, низкое место, сбой питания на + стадиях подготовки и финализации, повтор после прерывания, конкурирующие операции. +- Проверить историю Host Extensions и сохранение её refs после удаления deployment. +- Миграции данных приложений не считать автоматически обратимыми откатом ОС. + +Выход: fault-injection matrix и recovery-инструкции. Связь: D-032, D-034, D-036, +D-046–D-049, D-056/D-060; вопросы 25, 28, 57–59, 65, 69. + +### E08 — Реестры и публикация без скрытых гонок + +Репозитории: `registry`, `contracts`, `test-lab`. + +- Начать с штатного OSTree-транспорта и простого тестового реестра; отдельно определить + доверие к пакетам, слоям, образам, метаданным релиза и ротацию ключей. +- Опубликовать объекты/обязательные метаданные до продвижения ref; инъекция ошибки + между шагами не должна оставлять опубликованный канал с недоступными входами. +- Testing → stable с тем же commit ID; проверить retention входов, pull, недоступный + объект и неверную подпись. Staging ограничивается доступом, а не именем ref. + +Выход: проверенный протокол публикации и восстановления; вопросы 15–18, 22, 66. +До прохождения всех gates использовать только закрытый экспериментальный namespace. + +### E09 — Доказательство публичной готовности + +Репозитории: все, оркестрация в `test-lab`. + +- Согласовать охват побитового сравнения: layer/image commits, initramfs, установочные + артефакты; правила для подписей, аттестаций, generated UUID и timestamps. +- Независимые чистые пересборки по одинаковым manifest/lock; выявленные различия + объясняются и устраняются, а не заменяются утверждением «входы закреплены». +- Выполнить полный функциональный набор на Core-only и каждом выпускаемом Purpose, + обязательные скрипты и поддерживаемые upgrade/rollback переходы. +- Зафиксировать матрицу поддерживаемых сред; успех VM не объявляет поддержку всего железа. +- Только после этих доказательств разрешать testing/stable по D-050–D-052. + +## 5. Ближайшие решения перед продуктовым кодом + +1. Rust принят D-062. Для первых экспериментов закрепляем toolchain 1.90.0, + edition 2024; это инженерный pin, не вечная версия языка. Сборки только на superserv1. +2. D-063: snapshots будут ежемесячными, ZFS-инфраструктура на зеркале отложена до + рабочего `archipelago-core-latest.iso`. Прототип использует текущее зеркало с + фиксацией точных полученных баз/пакетов/checksums каждого прогона. Локальный набор + входов эксперимента не объявляется готовым сервисом snapshots или публичным релизом. + Точный bootstrap и проверку его подписи нужно завершить до исполнения Arch-среды. +3. Минимальные draft-схемы snapshot/package-index/manifest/lock: сначала fixtures + и правила ошибок, затем реализация; не стабилизировать по одному happy path. +4. Профиль VM-диска и конкретный Purpose выбрать до E04/E06 соответственно. + +## 6. Текущий прогресс + +- Репозитории созданы без remotes/коммитов; identity скопирована из `rfc`. +- Доступ к обоим хостам и зеркалу проверен; выбран superserv1 и `/hdd` по указанию пользователя. +- QMP/KVM smoke выполнен непосредственно на superserv1; повторяемый код добавлен в lab. +- Повторный запуск из `/hdd/archipelago` прошёл вместе с проверками отсутствующей + прошивки и timeout/cleanup. Отчёт: [E00-RESULTS.md](E00-RESULTS.md). +- Rust toolchain установлен на `/hdd`; первые `contracts`/`composer` проходят + пять тестов и release-сборку на superserv1. +- Подпись Arch bootstrap проверена, read-only запуск nspawn прошёл; обнаружены + вопросы сохранения capability-xattrs и ACL staging. См. [E01-RESULTS.md](E01-RESULTS.md). +- Пакетная композиция, сборка ISO и загрузка гостевой ОС пока не выполнены. +- D-064 отражён в control-layer дизайне. Чистая модель onboarding в `system` + прошла пять тестов и release-сборку; результаты — [CONTROL-LAYER-RESULTS.md](CONTROL-LAYER-RESULTS.md). diff --git a/README.md b/README.md new file mode 100644 index 0000000..458d07d --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# Archipelago test lab + +Стенд инженерных экспериментов и интеграционных проверок RFC v0. + +- План: [IMPLEMENTATION-PLAN.md](IMPLEMENTATION-PLAN.md). +- Первый отчёт: [E00-RESULTS.md](E00-RESULTS.md). +- Bootstrap и Rust: [E01-RESULTS.md](E01-RESULTS.md). +- Модель первой настройки: [CONTROL-LAYER-RESULTS.md](CONTROL-LAYER-RESULTS.md). +- Core ISO, пакет и полная VM-приёмка: [CORE-ISO-RESULTS.md](CORE-ISO-RESULTS.md). +- Выполнение: `superserv1` через Tailscale SSH. +- Рабочее дерево, диски VM, кэши и результаты: `/hdd/archipelago` (ZFS). +- Зеркало пакетов: `https://mirror.nw-sys.ru/archlinux/`. +- Python здесь — инструмент лаборатории, а не выбор языка продукта. + +## Проверка KVM/UEFI + +На **удалённом** хосте, из копии этого репозитория: + +```sh +python3 probes/kvm_smoke.py --workdir /hdd/archipelago/tmp +``` + +Проверка создаёт VM Q35 с одним vCPU и 256 MiB RAM, без сети и системного диска, +с отдельной временной копией OVMF VARS. Через QMP проверяет KVM, запуск, остановку +и штатное завершение. Timeout ограничивает процесс; временные данные удаляются. +На stdout выдаётся JSON с версиями, входами, хешами прошивок и результатами. + +Успех доказывает создание/управление VM с аппаратным ускорением и конфигурацией +UEFI, но не успешную загрузку прошивки, Linux, OSTree или systemd-boot. + +## Правила результатов + +### Наблюдение за Core ISO и VM-приёмкой + +Текущий прогон обозначается ссылкой `superserv1:/hdd/archipelago/runs/current-core`. +Для потокового просмотра: + +```sh +ssh superserv1 'tail -F /hdd/archipelago/runs/current-core/driver.log /hdd/archipelago/runs/current-core/acceptance.log' +``` + +После успешной сборки автоматически запускается `probes/core_iso_acceptance.py`. +В `acceptance.log` публикуются JSON-события этапов и путь `run` к новому каталогу VM. +В нём находятся `events.jsonl`, `live.serial`, `installed.serial` и итоговый +`summary.json`. `acceptance-passed` означает завершение проверок; наличие ISO или +события `live-shell-ready` само по себе не является прохождением приёмки. +`--provision-console tty1` проверяет мастер через эмулируемую VGA-клавиатуру QMP, +конкурирующий запрос на serial, фактическую консоль создания пользователя и login +на tty1. На стенде требуется `tesseract` с английской моделью: тест ждёт приглашений +на VGA-экране перед вводом, а не полагается на фиксированную задержку создания +аккаунта. Пароли не включаются в QMP/event logs. По умолчанию мастер проверяется +через ttyS0. Оба режима затем выполняют +полную приёмку overlays/Host Extensions. Для двойного прогона журнал второго режима +сохраняется отдельно как `acceptance-tty1.log`. +`--extensions-sequence` расширяет приёмку: повторные `add` до reboot, зависимости +mc, no-op дубликатов, ошибка разрешения при существующем pending и дальнейшее +добавление tree после активации. Сверяются OSTree JSON status, сохранение marker, +явный набор отдельно от зависимостей и история поколений. +Файл `credential` доступен только владельцу стенда и нужен для диагностики guest; +его содержимое нельзя включать в отчёты или stdout. + +Сохранять stdout, stderr и код завершения каждого эксперимента в отдельном каталоге +`/hdd/archipelago/runs/`. Не включать диски VM, пакеты и кэши в Git. В будущих +интеграционных прогонах записывать ревизии всех репозиториев, включая хеши локальных +незакоммиченных входов, snapshot/lock, команды, версии инструментов и сравнения. +Отрицательные проверки должны подтверждать ожидаемую ошибку и сохранность состояния, +а не просто завершаться ненулевым кодом. diff --git a/UPDATE-PROBE-2026-11-05.md b/UPDATE-PROBE-2026-11-05.md new file mode 100644 index 0000000..15ff809 --- /dev/null +++ b/UPDATE-PROBE-2026-11-05.md @@ -0,0 +1,82 @@ +# Hardware-test update probe — 2026-11-05 + +This is incremental update-adapter evidence, not completed update acceptance. + +## Completed hardware-test rollout + +Run `20261105T164634Z` completed and published both updated ISOs. The initial +validator stopped on incorrect shell quoting in its Wayland detection command, +after successful update/boot and persistence checks. The corrected validator +resumed the recorded candidate, confirmed native Wayland login and passed explicit +rollback. Evidence and the original failure are retained on terra under +`/opt/archipelago/data/private/update-rollout/20261105T164634Z/`. + +GNOME candidate base: +`14bcd04f6057042e45961a4ee325bbf646dcc167ad2859905ac7c729bfe7035d`. +Updated local deployment with nano: +`37d15a7c53f72278804194cb8af4372fd6465d2b7985a68f2fb78c79e2ed36fa`. +Rollback returned to +`e08fa3cd573ec0528b4388d9df74d7bd51ee9969a7e13da40d3ab37dd64bd1bf`. +The final binary includes the post-stage journal/cleanup correction mentioned +in the earlier work notes below. Core ISO acceptance passed; fresh native GIS +installation of the new GNOME ISO was not repeated in this rollout. +Publication and HTTPS checks passed; external catalog identities were confirmed +from yabloko. This remains hardware-test, not full testing/stable acceptance. + +- D-078 approves a separate terra-only signing key. Public fingerprint: + `CF0FED7A412E57010527CD68BFAA5E80EEEACCA2`. +- Both existing published layer/image repositories were republished with signed + commits and summaries, keeping ISO bytes and image identities unchanged. +- Real disposable OSTree tests on yabloko passed signed publication/republication, + signature-verified pull, rejection of a corrupted summary signature and the + existing retention/failure-preservation checks. +- New Rust CLI provides `update check`, `update plan`, `update apply --plan HASH`. + It verifies summary/commit signatures, binds the selected commit and current + deployment state into a hashed plan, shares the host mutation lock, and uses + native staging. Named Host Extensions are reapplied as a full set against the + new base. Pending deployments and custom managed overlays are rejected rather + than discarded. General CLI envelopes, cancellation/resume, update policy, + PackageKit integration and production release formats are not completed. +- Rust system tests (10) and locked offline CLI release compilation passed. +- Existing GNOME VM `gnome-sfyobspe` on yabloko executed the candidate binary from + `/var/tmp/archipelago-updater`, leaving its packaged `/usr` unchanged. +- Signed HTTPS check/plan selected the published GNOME base. Apply correctly + returned no-op for that base while retaining requested `nano` and identical + deployment status. Corrupted-plan and changed-state preconditions were rejected. +- The guest's Arch OSTree successfully downloaded and verified the real published + commit signature, not just the tools-container implementation. + +Evidence beside the VM: `update-invalid-plan.log`, `update-signed-check.log`, +`update-plan-preconditions.log`, `update-signed-commit.log`. The first three are +already archived on terra alongside the original GNOME candidate. + +Historical build note (completed by the rollout above): Core/GNOME ISO builds +with the embedded updater/public key were started under +`archipelago-update-enabled-builds.service` on yabloko. Their initial frozen binary +predates a subsequent change which reports post-stage journal/cleanup failures as +warnings rather than falsely claiming that staging failed. Final publication must +include that correction. The completed rollout above records subsequent new-base +update, full extension reapplication, activation and rollback verification. + +## Configurable bindings and autonomous acceptance follow-up + +The newer updater successfully performed signed `file:///` repository check/plan +inside `unshare --net` on the retained GNOME guest; packaged integrity still passed. +Temporary `/etc/archipelago/update.json` was removed afterward. Evidence is +`offline-binding-test.log` beside `gnome-sfyobspe` on yabloko. This verifies offline +discovery, not a complete air-gap update/build/install. + +`gnome_native_acceptance.py` now drives a fresh ISO installation and native GIS +without an LLM or operator. Fixed-profile QMP inputs are followed by guest checks; +UI drift or timeout is a failed run. Reboot checks compare guest boot identities. +The harness and clean baseline-to-candidate integration are undergoing validation; +their existence does not yet establish unattended end-to-end acceptance. + +The first clean run (`20261105T182338Z`) failed before authenticated guest checks: +GIS had no suggested keyboard selected, so Next remained disabled on Typing. No +publication followed. Diagnostics are archived on terra under +`/opt/archipelago/evidence/native-acceptance/20261105T182338Z/`. The harness now +explicitly selects English (US) through the native selector and distinguishes +short authentication timeouts from long extension-build timeouts. A fresh retry +uses a frozen copy of its probe sources; interactive diagnosis of the failed VM +is not counted as acceptance. diff --git a/probes/build-toolbox-patched.sh b/probes/build-toolbox-patched.sh new file mode 100644 index 0000000..2a45e26 --- /dev/null +++ b/probes/build-toolbox-patched.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Private binary probe. Run in the recorded Arch build container on terra. +# Compile against target shadow headers: Toolbx embeds libsubid's exact ABI name. +# Source: upstream 0.3 with the separately recorded digest-name patch. +set -eu +cd /source/src +mkdir -p /source/probe-output +go build -trimpath \ + -ldflags "-extldflags '-Wl,-dynamic-linker,/run/host/usr/lib/ld-linux-x86-64.so.2 -Wl,-rpath,/run/host/usr/lib -Wl,--export-dynamic -Wl,--unresolved-symbols=ignore-in-object-files' -linkmode external -X github.com/containers/toolbox/pkg/version.currentVersion=0.3-archipelago-probe" \ + -o /source/probe-output/toolbox +sha256sum /source/probe-output/toolbox > /source/probe-output/toolbox.sha256 diff --git a/probes/core_iso_acceptance.py b/probes/core_iso_acceptance.py new file mode 100644 index 0000000..b7e10ca --- /dev/null +++ b/probes/core_iso_acceptance.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +"""Destructive only to a newly-created lab VM disk. New runs execute on terra.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import secrets +import shlex +import shutil +import socket +import subprocess +import tempfile +import time +from datetime import datetime, timezone + +import pexpect + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--iso", required=True, type=Path) + parser.add_argument("--workdir", default="/hdd/archipelago/vms", type=Path) + parser.add_argument("--provision-console", choices=["ttyS0", "tty1"], default="ttyS0") + parser.add_argument("--extensions-sequence", action="store_true") + parser.add_argument("--dkms", action="store_true", help="Build and activate reviewed v4l2loopback DKMS extension") + parser.add_argument("--firmware", action="store_true", help="Require D-074 firmware in live and installed systems") + parser.add_argument("--ovmf-code", default="/usr/share/edk2/ovmf/OVMF_CODE.fd") + parser.add_argument("--ovmf-vars", default="/usr/share/edk2/ovmf/OVMF_VARS.fd") + parser.add_argument("--qemu", default="qemu-system-x86_64") + args = parser.parse_args() + run = Path(tempfile.mkdtemp(prefix="core-acceptance-", dir=args.workdir)) + disk = run / "core.qcow2" + variables = run / "OVMF_VARS.fd" + shutil.copyfile(args.ovmf_vars, variables) + subprocess.run(["qemu-img", "create", "-f", "qcow2", str(disk), "20G"], check=True) + password = secrets.token_hex(18) + # Private retained credential allows diagnosis of a failed guest, never in logs. + fd = os.open(run / "credential", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w") as stream: + stream.write(password) + results = {"iso": str(args.iso.resolve()), "run": str(run), + "provision_console": args.provision_console, "checks": []} + def event(stage, **details): + record = {"time": datetime.now(timezone.utc).isoformat(), "stage": stage, **details} + with (run / "events.jsonl").open("a") as stream: + stream.write(json.dumps(record) + "\n") + print(json.dumps(record), flush=True) + + event("started", run=str(run), iso=str(args.iso)) + with args.iso.open("rb") as stream: + digest = hashlib.sha256() + for chunk in iter(lambda: stream.read(4 * 1024 * 1024), b""): + digest.update(chunk) + results["iso_sha256"] = digest.hexdigest() + child = None + log = None + + def boot(live): + nonlocal child, log + event("boot-live" if live else "boot-installed") + command = ["-machine", "q35,accel=kvm", "-cpu", "host", "-smp", "2", + "-m", "2048", "-display", "none", "-serial", "stdio", "-monitor", "none", + "-drive", f"if=pflash,format=raw,readonly=on,file={args.ovmf_code}", + "-drive", f"if=pflash,format=raw,file={variables}", + "-drive", f"if=virtio,format=qcow2,file={disk}", + "-nic", "user,model=virtio-net-pci"] + if live: + command += ["-cdrom", str(args.iso.resolve()), "-boot", "order=d"] + else: + command += ["-qmp", f"unix:{run}/qmp.sock,server=on,wait=off"] + log = (run / ("live.serial" if live else "installed.serial")).open("w") + child = pexpect.spawn(args.qemu, command, encoding="utf-8", + codec_errors="replace", timeout=300) + child.logfile_read = log + + def command(text, privileged=False): + if privileged: + child.sendline("sudo -v") + index = child.expect([r"\[sudo\] password for coretest:", r"coretest@.*[\$] "]) + if index == 0: + child.sendline(password) + child.expect(r"coretest@.*[\$] ") + guest_command = ("sudo " if privileged else "") + "/bin/bash -ec " + shlex.quote(text) + child.sendline(guest_command + "; printf '\\n__ARCHIPELAGO_RESULT=%s__\\n' \"$?\"") + child.expect(r"__ARCHIPELAGO_RESULT=(\d+)__", timeout=2400 if args.dkms else 600) + code = int(child.match.group(1)) + results["checks"].append({"command": text, "exit_code": code}) + event("command-result", command=text, exit_code=code) + if code: + raise RuntimeError(f"Guest command failed ({code}): {text}") + child.expect(r"(?:root|coretest)@[^\r\n]*[#$] ") + + def login(): + event("waiting-for-login") + child.expect("login:", timeout=300) + child.sendline("coretest") + child.expect("Password:") + child.sendline(password) + child.expect(r"coretest@.*[\$] ") + event("login-passed") + + def reboot(): + event("explicit-reboot") + child.sendline("sudo systemctl reboot") + login() + + def keyboard_setup(login_only=False): + # Real emulated keyboard input on the VGA console, never a guest shell + # backdoor. Credentials are not included in the QMP/event logs. + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: + connection.settimeout(10) + connection.connect(str(run / "qmp.sock")) + with connection.makefile("rwb") as stream: + json.loads(stream.readline()) + + def qmp(method, arguments=None): + stream.write((json.dumps({"execute": method, "arguments": arguments or {}}) + "\n").encode()) + stream.flush() + while True: + response = json.loads(stream.readline()) + if "error" in response: + raise RuntimeError(f"QMP {method} failed") + if "return" in response: + return response["return"] + + def keys(*codes): + qmp("send-key", {"keys": [{"type": "qcode", "data": code} for code in codes], + "hold-time": 50}) + time.sleep(0.08) + + def line(text): + for character in text: + keys(character) + keys("ret") + time.sleep(1) + + def screen_prompt(expected): + deadline = time.monotonic() + 90 + while time.monotonic() < deadline: + image = run / "tty1-current.ppm" + qmp("screendump", {"filename": str(image)}) + # Tiny light-on-dark console glyphs need inversion and + # nearest-neighbour scaling for reliable prompt OCR. + with image.open("rb") as source: + assert source.readline().strip() == b"P6" + width, height = map(int, source.readline().split()) + assert source.readline().strip() == b"255" + gray = source.read()[::3].translate(bytes(reversed(range(256)))) + rows = [b"".join(bytes([pixel]) * 3 for pixel in gray[y*width:(y+1)*width]) + for y in range(height)] + scaled = image.with_suffix(".pgm") + scaled.write_bytes(f"P5\n{width*3} {height*3}\n255\n".encode() + + b"".join(row * 3 for row in rows)) + text = subprocess.run(["tesseract", str(scaled), "stdout", "--psm", "6"], + capture_output=True, text=True, check=True).stdout + lines = [line.strip().lower().replace("passuord", "password") + .replace("usernane", "username") + for line in text.splitlines() if line.strip()] + if lines and expected in lines[-1]: + return + time.sleep(0.5) + raise RuntimeError(f"VGA console did not reach prompt: {expected}") + + qmp("qmp_capabilities") + keys("ctrl", "alt", "f1") + time.sleep(2) + if login_only: + screen_prompt("login:") + line("coretest") + screen_prompt("password:") + line(password) + return + qmp("screendump", {"filename": str(run / "tty1-before.ppm")}) + screen_prompt("press enter") + line("") + screen_prompt("username:") + # Compete on serial after tty1 owns the lock: it must wait. + child.sendline("") + child.expect("Setup is active on another console", timeout=30) + event("second-console-blocked") + line("coretest") + screen_prompt("new password:") + line(password) + screen_prompt("retype new password:") + line(password) + + try: + boot(True) + child.expect(r"root@.*[#] ", timeout=300) + event("live-shell-ready") + command("archipelago self-check") + if args.firmware: + command("pacman -Q linux-firmware; test -n \"$(find /usr/lib/firmware -type f -print -quit)\"") + command("cp /usr/bin/archipelago /run/archipelago-check; " + "trap 'chmod 0755 /usr/bin/archipelago; rm -f /run/archipelago-check' EXIT; " + "chmod 0644 /usr/bin/archipelago; " + "if /run/archipelago-check self-check; then exit 1; fi; " + "chmod 0755 /usr/bin/archipelago; archipelago self-check") + command("test -e /run/archipelago-live; archipelago install /dev/vda --erase") + event("installation-passed") + child.sendline("systemctl poweroff") + child.expect(pexpect.EOF, timeout=90) + child.close() + log.close() + boot(False) + child.expect("Press Enter to begin Core setup on this console.", timeout=300) + event("provisioning", console=args.provision_console) + if args.provision_console == "tty1": + keyboard_setup() + else: + child.sendline("") + child.expect("Username:", timeout=300) + child.sendline("coretest") + child.expect("New password:") + child.sendline(password) + child.expect("Retype new password:") + child.sendline(password) + child.expect("ARCHIPELAGO_PROVISION_COMPLETE") + event("provisioning-passed") + login() + command("test -e /run/ostree-booted; id; test -d /var/home/coretest") + command("archipelago self-check", True) + if args.firmware: + command("pacman -Q linux-firmware; test -n \"$(find /usr/lib/firmware -type f -print -quit)\"", True) + command(f"test \"$(cat /etc/archipelago/provision-console)\" = /dev/{args.provision_console}; " + "systemctl is-active getty@tty1 serial-getty@ttyS0; " + "test \"$(getent passwd coretest | wc -l)\" = 1", True) + if args.provision_console == "tty1": + keyboard_setup(login_only=True) + command("who | grep -E '^coretest +tty1 '") + event("tty1-login-passed") + command("archipelago status; systemctl is-active systemd-networkd systemd-resolved sshd; " + "findmnt -n -o OPTIONS /usr | grep -w ro; ! touch /usr/.write-test", True) + command("archipelago overlay apply test-marker; test ! -e /usr/share/archipelago/test-marker", True) + reboot() + command("grep 'Archipelago managed overlay test' /usr/share/archipelago/test-marker") + command("archipelago self-check", True) + command("archipelago extension add nano; ! command -v nano", True) + if args.extensions_sequence: + command("archipelago extension add mc htop; ! command -v mc; ! command -v htop", True) + command("ostree admin status --json > /run/pending-before; " + "archipelago extension add nano mc; " + "ostree admin status --json > /run/pending-after; " + "cmp /run/pending-before /run/pending-after", True) + command("if archipelago extension add archipelago-nonexistent-package; then exit 1; fi; " + "ostree admin status --json > /run/pending-after; " + "cmp /run/pending-before /run/pending-after; archipelago status", True) + reboot() + command("nano --version; grep 'Archipelago managed overlay test' /usr/share/archipelago/test-marker") + command("archipelago self-check", True) + command("archipelago status; pacman -Q nano; systemctl is-active systemd-networkd systemd-resolved sshd", True) + if args.extensions_sequence: + command("mc --version; htop --version; pacman -Q gpm slang pcre; " + "! grep -qx gpm /usr/lib/archipelago/host-extensions") + command("archipelago extension add tree; ! command -v tree", True) + reboot() + command("tree --version; mc --version; htop --version; nano --version; " + "grep 'Archipelago managed overlay test' /usr/share/archipelago/test-marker") + command("archipelago self-check; archipelago status; " + "test \"$(wc -l < /usr/lib/archipelago/host-extensions)\" = 4; " + "test \"$(find /var/lib/archipelago/host-extensions/generations -name staged | wc -l)\" = 3; " + "test \"$(find /var/lib/archipelago/host-extensions/generations -name failure | wc -l)\" = 1", True) + if args.dkms: + command("archipelago extension add v4l2loopback-dkms; " + "! modinfo v4l2loopback; ! test -e /dev/video0", True) + command("ostree admin status --json > /run/dkms-pending; " + "archipelago extension add v4l2loopback-dkms; " + "ostree admin status --json > /run/dkms-pending-after; " + "cmp /run/dkms-pending /run/dkms-pending-after; " + "if archipelago extension add archipelago-nonexistent-dkms; then exit 1; fi; " + "ostree admin status --json > /run/dkms-pending-after; " + "cmp /run/dkms-pending /run/dkms-pending-after", True) + reboot() + command("archipelago self-check; " + "test \"$(modinfo -F vermagic v4l2loopback | cut -d' ' -f1)\" = \"$(uname -r)\"; " + "modprobe v4l2loopback; test -c /dev/video0; " + "grep '^v4l2loopback ' /proc/modules; modprobe -r v4l2loopback; " + "test -s /usr/lib/archipelago/dkms-modules.tsv; " + "! grep -q -- '-headers' /usr/lib/archipelago/host-extensions; " + "test ! -d /var/lib/dkms/v4l2loopback; nano --version", True) + command("archipelago extension add strace; ! command -v strace", True) + reboot() + command("strace --version; modprobe v4l2loopback; test -c /dev/video0; " + "modprobe -r v4l2loopback; archipelago self-check; archipelago status", True) + child.sendline("sudo systemctl poweroff") + child.expect(pexpect.EOF, timeout=90) + results["passed"] = True + event("acceptance-passed") + except Exception as error: + results.update(passed=False, error=str(error)) + event("acceptance-failed", error=str(error)) + finally: + if child is not None and child.isalive(): + child.terminate(force=True) + if log is not None: + log.close() + (run / "summary.json").write_text(json.dumps(results, indent=2) + "\n") + print(json.dumps(results, indent=2)) + return 0 if results.get("passed") else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/probes/dkms_failure_acceptance.sh b/probes/dkms_failure_acceptance.sh new file mode 100644 index 0000000..74eb8cc --- /dev/null +++ b/probes/dkms_failure_acceptance.sh @@ -0,0 +1,47 @@ +#!/bin/bash +# Run as root on superserv1 against a disposable successful DKMS adapter fixture. +# Never point this at an installed deployment. Evidence directories must be fresh. +set -euo pipefail +root=$(realpath "$1") +finalizer=$(realpath "$2") +evidence=$(realpath -m "$3") +[[ $root == /hdd/archipelago/runs/*/dkms-probe/root ]] +[[ -f $root/usr/lib/archipelago/dkms-modules.tsv && -d $root/usr/etc ]] +[[ ! -e $evidence ]] +mkdir -p "$evidence/headers" "$evidence/build" +for scenario in headers build; do + systemd-nspawn --settings=no --register=no --private-network --resolv-conf=off \ + -D "$root" --bind-ro="$finalizer:/finalizer.sh" --bind="$evidence/$scenario:/evidence" \ + /bin/bash -euo pipefail -c ' + scenario=$1 + # Fixture-only staging setup; preserve the successful module payload. + mkdir -p /etc + cp -a /usr/etc/. /etc/ + releases=(/usr/lib/modules/*/build/include/config/kernel.release) + [[ ${#releases[@]} == 1 ]] + header=${releases[0]} + cp "$header" /run/original-kernel.release + cp /usr/bin/make /run/original-make + trap '\''cp /run/original-kernel.release "$header"; cp /run/original-make /usr/bin/make; rm -rf /etc'\'' EXIT + find /usr/lib/modules -type f -name "*.ko*" -exec sha256sum {} + > /evidence/before.sha256 + # Only fixture-local disposable DKMS state is removed between cases. + rm -rf /var/lib/dkms + if [[ $scenario == headers ]]; then + printf "wrong-kernel\n" > "$header" + else + printf "#!/bin/sh\nexit 42\n" > /usr/bin/make + chmod 755 /usr/bin/make + fi + if /bin/bash /finalizer.sh > /evidence/failure.log 2>&1; then + echo "Injected $scenario failure was ignored" >&2; exit 1 + fi + test "$(cat /evidence/dkms/exit-status)" != 0 + sha256sum -c /evidence/before.sha256 > /evidence/preserved.log + if [[ $scenario == headers ]]; then + grep -F "Wrong headers" /evidence/failure.log + else + grep -Ei "bad return status|build.*failed|error.*build" /evidence/failure.log + fi + printf "PASS: %s failure blocks finalization and preserves existing modules\n" "$scenario" + ' fixture "$scenario" +done diff --git a/probes/gnome_native_acceptance.py b/probes/gnome_native_acceptance.py new file mode 100644 index 0000000..ebbfbbd --- /dev/null +++ b/probes/gnome_native_acceptance.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Deterministic native-GIS fixture creation. No LLM, OCR or operator prompts. + +Coordinates bind the reviewed 1280x800 GNOME profile. UI drift/timeout fails the +run; screenshots are diagnostics, never an implicit acceptance decision. +""" +import argparse +import json +import os +from pathlib import Path +import pexpect +import secrets +import re +import shlex +import subprocess +import time + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument('--iso', type=Path, required=True) +p.add_argument('--workdir', type=Path, required=True) +p.add_argument('--ovmf-code', required=True) +p.add_argument('--ovmf-vars', required=True) +p.add_argument('--ssh-port', type=int, default=22296) +p.add_argument('--unit', default='archipelago-native-gnome-vm') +p.add_argument('--rtc-base') +p.add_argument('--require-time-sync', action='store_true') +args = p.parse_args() +scripts = Path(__file__).resolve().parent +args.workdir.mkdir(parents=True, exist_ok=True) +result = {'passed': False, 'scope': 'native-gis-and-extension-baseline'} +vm = None +try: + with (args.workdir / 'prepare.log').open('w') as log: + subprocess.run(['python3', str(scripts / 'gnome_vm_prepare.py'), '--iso', str(args.iso), + '--workdir', str(args.workdir), '--vm-unit', args.unit, '--ovmf-code', args.ovmf_code, + '--ovmf-vars', args.ovmf_vars] + (['--rtc-base', args.rtc_base] if args.rtc_base else []), + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=1800) + prepared = list(args.workdir.glob('gnome-*/preparation.json')) + if len(prepared) != 1: raise RuntimeError('Ambiguous VM preparation') + vm = prepared[0].parent + result.update(vm=str(vm), ssh_port=args.ssh_port, + iso_sha256=json.loads(prepared[0].read_text())['iso_sha256']) + subprocess.run(['python3', str(scripts / 'qmp_command.py'), str(vm / 'qmp.sock'), + 'human-monitor-command', json.dumps({'command-line': f'hostfwd_add tcp:127.0.0.1:{args.ssh_port}-:22'})], check=True) + password = secrets.token_hex(18) + with os.fdopen(os.open(vm / 'credential', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w') as f: + f.write(password) + def ui(label, *commands): + subprocess.run(['python3', str(scripts / 'gnome_vm_input.py'), str(vm), *commands, + '--screen', label + '.png'], check=True) + time.sleep(10) + time.sleep(30) + ui('01-language', '--click', '500', '388') + ui('02-typing', '--click', '1095', '55') + # This locale has no suggested layout; expand the native XKB selector and + # explicitly choose English (US), rather than clicking a disabled Next. + ui('02a-layouts', '--click', '640', '383') + ui('02b-us-search', '--click', '500', '330', '--text', 'english us') + ui('02c-us-selected', '--click', '500', '478') + ui('03-privacy', '--click', '1095', '55') + ui('04-timezone', '--click', '1095', '55') + ui('05-city', '--click', '500', '326', '--text', 'moscow') + ui('06-city-selected', '--click', '500', '362') + ui('07-account', '--click', '1095', '55') + ui('08-name', '--text', 'coretest') + ui('09-password', '--click', '1095', '55') + ui('10-password-entered', '--text-file', str(vm / 'credential')) + ui('11-confirmed', '--click', '550', '492', '--text-file', str(vm / 'credential')) + ui('12-complete', '--click', '1095', '55') + ui('13-session', '--click', '640', '572') + def guest(script, timeout=300, disconnect=False): + c = pexpect.spawn('ssh', ['-tt', '-o', 'ConnectTimeout=5', '-o', 'StrictHostKeyChecking=accept-new', '-o', + 'UserKnownHostsFile=' + str(vm / 'known_hosts'), '-p', str(args.ssh_port), + 'coretest@127.0.0.1', 'sudo -p SUDO_AUTH: bash -ec ' + shlex.quote(script)], encoding='utf-8', timeout=timeout) + try: + c.expect('[Pp]assword:', timeout=15); c.sendline(password) + auth = c.expect(['SUDO_AUTH:', 'Permission denied', '[Pp]assword:'], timeout=15) + if auth != 0: raise RuntimeError('Native account authentication rejected') + c.sendline(password) + with (args.workdir / 'guest.log').open('a') as log: + c.logfile_read = log; c.expect(pexpect.EOF) + text = c.before + c.close() + if c.exitstatus != 0 and not (disconnect and c.exitstatus == 255): + raise RuntimeError('Guest check failed: ' + str(c.exitstatus)) + return text + finally: + if c.isalive(): c.close(force=True) + deadline = time.monotonic() + 180 + while time.monotonic() < deadline: + try: + guest('true', timeout=15) + break + except (pexpect.ExceptionPexpect, RuntimeError): + time.sleep(3) + else: + raise RuntimeError('Native onboarding did not provide authenticated SSH/sudo within 180 seconds') + if args.require_time_sync: + guest('''set -e +systemctl is-enabled systemd-timesyncd.service +systemctl is-active systemd-timesyncd.service +timeout 180 bash -c 'until [ "$(timedatectl show -p NTPSynchronized --value)" = yes ]; do sleep 3; done' +timeout 90 bash -c 'until systemctl is-active --quiet archipelago-keyring.service; do sleep 3; done' +''', timeout=290) + result['clock_regression'] = {'rtc_base': args.rtc_base, 'synchronized': True} + guest('''set -e +timeout 180 sh -c 'until test -f /etc/archipelago/provisioned; do sleep 2; done' +test "$(cat /etc/archipelago/provisioned)" = coretest +archipelago self-check +systemctl is-active gdm NetworkManager ostree-finalize-staged.service +runuser -u coretest -- sh -c 'echo "clean dropin candidate" > /var/home/coretest/.archipelago-clean-persistence' +archipelago extension add nano +''', timeout=1800) + wayland = '''until loginctl list-sessions --no-legend | awk '$3=="coretest" {print $1}' | xargs -r -n1 loginctl show-session -p Type --value | grep -qx wayland; do sleep 3; done''' + guest('timeout 120 bash -c ' + shlex.quote(wayland), timeout=150) + def boot_id(): + text = guest('printf "BOOT_ID="; cat /proc/sys/kernel/random/boot_id', timeout=15) + match = re.search(r'BOOT_ID=([0-9a-f-]{36})', text) + if not match: raise RuntimeError('Missing guest boot identity') + return match.group(1) + old_boot = boot_id() + guest('systemctl reboot', disconnect=True) + deadline = time.monotonic() + 360 + while time.monotonic() < deadline: + try: + new_boot = boot_id() + if new_boot != old_boot: + break + except (pexpect.ExceptionPexpect, RuntimeError): + pass + time.sleep(3) + else: + raise RuntimeError('Guest did not complete reboot within 360 seconds') + guest('''set -e +nano --version +archipelago self-check +pacman -Q epiphany gnome-calculator gnome-calendar gnome-contacts gnome-text-editor loupe papers gnome-clocks gnome-weather gnome-characters gnome-font-viewer gnome-connections file-roller simple-scan +''', timeout=960) + result['passed'] = True +except BaseException as error: + result['error'] = str(error) + raise +finally: + (args.workdir / 'native-acceptance.json').write_text(json.dumps(result, indent=2) + '\n') + if not result['passed'] and vm is not None: + subprocess.run(['python3', str(scripts / 'qmp_command.py'), str(vm / 'qmp.sock'), + 'system_powerdown'], check=False, timeout=20) + for _ in range(30): + if subprocess.run(['systemctl', 'is-active', '--quiet', args.unit]).returncode: + break + time.sleep(2) + subprocess.run(['systemctl', 'stop', args.unit], check=False, timeout=90) diff --git a/probes/gnome_vm_input.py b/probes/gnome_vm_input.py new file mode 100644 index 0000000..87ad95b --- /dev/null +++ b/probes/gnome_vm_input.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Native QMP keyboard/pointer input and a screenshot for a lab GNOME VM.""" +import argparse +import json +from pathlib import Path +import socket +import time + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('run', type=Path) + parser.add_argument('--click', nargs=2, type=int, metavar=('X', 'Y')) + parser.add_argument('--keys', nargs='+') + parser.add_argument('--text') + parser.add_argument('--text-file', type=Path, help='Private credential file; contents are never logged') + parser.add_argument('--screen', default='interaction.png') + args = parser.parse_args() + with socket.socket(socket.AF_UNIX) as connection: + connection.settimeout(15) + connection.connect(str(args.run / 'qmp.sock')) + with connection.makefile('rwb') as stream: + json.loads(stream.readline()) + + def call(command, arguments=None): + stream.write((json.dumps({'execute': command, 'arguments': arguments or {}}) + '\n').encode()) + stream.flush() + while True: + response = json.loads(stream.readline()) + if 'error' in response: + raise RuntimeError(response['error']) + if 'return' in response: + return response['return'] + + def key(code): + call('send-key', {'keys': [{'type': 'qcode', 'data': code}], 'hold-time': 50}) + time.sleep(0.08) + + call('qmp_capabilities') + if args.click: + # Target VM uses a 1280x800 display and an absolute USB tablet. + x, y = args.click + if not 0 <= x < 1280 or not 0 <= y < 800: + raise ValueError('Click outside 1280x800 display') + call('input-send-event', {'events': [ + {'type': 'abs', 'data': {'axis': 'x', 'value': round(x * 32767 / 1279)}}, + {'type': 'abs', 'data': {'axis': 'y', 'value': round(y * 32767 / 799)}}, + {'type': 'btn', 'data': {'down': True, 'button': 'left'}}]}) + call('input-send-event', {'events': [ + {'type': 'btn', 'data': {'down': False, 'button': 'left'}}]}) + text = args.text_file.read_text().strip() if args.text_file else args.text + if text: + if any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789 -.' for c in text): + raise ValueError('Text input supports lowercase US ASCII only') + for char in text: + key({' ': 'spc', '-': 'minus', '.': 'dot'}.get(char, char)) + for code in args.keys or []: + key(code) + time.sleep(2) + call('screendump', {'filename': str(args.run / args.screen), 'format': 'png'}) + + +if __name__ == '__main__': + main() diff --git a/probes/gnome_vm_prepare.py b/probes/gnome_vm_prepare.py new file mode 100644 index 0000000..dc6445e --- /dev/null +++ b/probes/gnome_vm_prepare.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Install a private GNOME probe into a fresh VM; leave native onboarding running. + +This prepares a graphical test target, not a Desktop acceptance result. QMP and +serial diagnostics stay local to the run directory. No guest account is injected. +""" +import argparse +import hashlib +import json +from pathlib import Path +import shlex +import shutil +import subprocess +import tempfile + +import pexpect + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--iso', required=True, type=Path) + parser.add_argument('--workdir', required=True, type=Path) + parser.add_argument('--vm-unit', help='Run the installed VM in a separate host systemd service') + parser.add_argument('--ovmf-code', default='/usr/share/OVMF/OVMF_CODE_4M.fd') + parser.add_argument('--ovmf-vars', default='/usr/share/OVMF/OVMF_VARS_4M.fd') + parser.add_argument('--rtc-base', help='Explicit QEMU RTC base for clock-regression probes') + args = parser.parse_args() + args.workdir.mkdir(parents=True, exist_ok=True) + run = Path(tempfile.mkdtemp(prefix='gnome-', dir=args.workdir)).resolve() + iso = args.iso.resolve(strict=True) + state = {'run': str(run), 'iso': str(iso), 'state': 'preparing', + 'acceptance_passed': False} + + def save(): + (run / 'preparation.json').write_text(json.dumps(state, indent=2) + '\n') + + print(run, flush=True) + save() + child = None + try: + with iso.open('rb') as stream: + state['iso_sha256'] = hashlib.file_digest(stream, 'sha256').hexdigest() + shutil.copyfile(args.ovmf_vars, run / 'OVMF_VARS.fd') + subprocess.run(['qemu-img', 'create', '-f', 'qcow2', str(run / 'disk.qcow2'), '48G'], check=True) + common = ['-machine', 'q35,accel=kvm', '-cpu', 'host', '-smp', '4', + '-m', '6144', '-display', 'none', '-vga', 'virtio', + '-device', 'qemu-xhci', '-device', 'usb-tablet', + '-monitor', 'none', '-nic', 'user,model=virtio-net-pci', + '-drive', f'if=pflash,format=raw,readonly=on,file={args.ovmf_code}', + '-drive', f'if=pflash,format=raw,file={run}/OVMF_VARS.fd', + '-drive', f'if=virtio,format=qcow2,file={run}/disk.qcow2'] + if args.rtc_base: + common += ['-rtc', 'base=' + args.rtc_base + ',clock=host'] + state['rtc_base'] = args.rtc_base + with (run / 'live.serial').open('w') as log: + child = pexpect.spawn('qemu-system-x86_64', common + [ + '-serial', 'stdio', '-cdrom', str(iso), '-boot', 'order=d'], + encoding='utf-8', codec_errors='replace', timeout=600) + child.logfile_read = log + child.expect(r'root@.*[#] ') + command = ('archipelago self-check && test -e /run/archipelago-live && ' + 'archipelago install /dev/vda --erase') + child.sendline('bash -ec ' + shlex.quote(command) + + "; printf '\\n__GNOME_INSTALL=%s__\\n' \"$?\"") + child.expect(r'__GNOME_INSTALL=(\d+)__', timeout=1800) + if int(child.match.group(1)): + raise RuntimeError('Live installation failed; inspect live.serial') + child.expect(r'root@.*[#] ') + child.sendline('systemctl poweroff') + child.expect(pexpect.EOF, timeout=120) + child.close() + child = None + state['state'] = 'installed' + save() + command = ['qemu-system-x86_64', *common, '-daemonize', + '-pidfile', str(run / 'qemu.pid'), + '-serial', f'file:{run}/installed.serial', + '-qmp', f'unix:{run}/qmp.sock,server=on,wait=off'] + (run / 'installed-command.json').write_text(json.dumps(command, indent=2) + '\n') + launch = command + if args.vm_unit: + launch = ['systemd-run', '--unit=' + args.vm_unit, + '--property=Type=forking', '--property=PIDFile=' + str(run / 'qemu.pid'), + *command] + state['vm_unit'] = args.vm_unit + subprocess.run(launch, check=True, capture_output=True, text=True) + state['state'] = 'installed-vm-started-awaiting-graphical-tests' + save() + except BaseException as error: + state.update(state='failed', error=str(error)) + save() + raise + finally: + if child is not None: + child.close(force=True) + + +if __name__ == '__main__': + main() diff --git a/probes/kvm_smoke.py b/probes/kvm_smoke.py new file mode 100644 index 0000000..c0ac54e --- /dev/null +++ b/probes/kvm_smoke.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Bounded, diskless KVM/QMP smoke probe; run on the designated lab host.""" + +import argparse +import hashlib +import json +from pathlib import Path +import platform +import shutil +import subprocess +import tempfile + + +def sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def probe(args, report): + workdir = Path(args.workdir).resolve(strict=True) + code = Path(args.ovmf_code).resolve(strict=True) + vars_source = Path(args.ovmf_vars).resolve(strict=True) + qemu = Path(args.qemu).resolve(strict=True) + report["inputs"] = { + "probe_sha256": sha256(__file__), + "qemu": str(qemu), + "qemu_sha256": sha256(qemu), + "ovmf_code": {"path": str(code), "sha256": sha256(code)}, + "ovmf_vars": {"path": str(vars_source), "sha256": sha256(vars_source)}, + } + with tempfile.TemporaryDirectory(prefix="kvm-smoke-", dir=workdir) as tmp: + variables = Path(tmp) / "OVMF_VARS.fd" + shutil.copyfile(vars_source, variables) + command = [ + str(qemu), "-machine", "q35,accel=kvm", "-cpu", "host", + "-smp", "1", "-m", "256", "-nodefaults", "-display", "none", + "-serial", "none", "-monitor", "none", "-nic", "none", "-S", + "-qmp", "stdio", + "-drive", f"if=pflash,format=raw,readonly=on,file={code}", + "-drive", f"if=pflash,format=raw,file={variables}", + ] + report["command"] = command + requests = [ + ("qmp_capabilities", "capabilities"), ("query-kvm", "kvm"), + ("cont", "start"), ("query-status", "running"), + ("stop", "stop"), ("query-status", "paused"), ("quit", "quit"), + ] + payload = "".join( + json.dumps({"execute": method, "id": identifier}) + "\n" + for method, identifier in requests + ) + process = subprocess.Popen( + command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, + ) + try: + stdout, stderr = process.communicate(payload, timeout=15) + except subprocess.TimeoutExpired: + process.kill() + stdout, stderr = process.communicate() + report.update(stdout=stdout, stderr=stderr, exit_code=process.returncode) + raise RuntimeError("QEMU exceeded the 15-second timeout") + finally: + if process.poll() is None: + process.kill() + process.wait() + report.update(stdout=stdout, stderr=stderr, exit_code=process.returncode) + if process.returncode != 0: + raise RuntimeError("QEMU exited unsuccessfully") + responses = [json.loads(line) for line in stdout.splitlines() if line.strip()] + report["responses"] = responses + if any("error" in response for response in responses): + raise RuntimeError("QMP returned an error") + results = { + response["id"]: response["return"] + for response in responses if "id" in response and "return" in response + } + if any(identifier not in results for _, identifier in requests): + raise RuntimeError("Missing QMP response") + if not (results["kvm"].get("enabled") and results["kvm"].get("present")): + raise RuntimeError("Hardware KVM acceleration is not enabled") + if results["running"].get("running") is not True: + raise RuntimeError("VM did not enter running state") + if results["paused"].get("status") != "paused": + raise RuntimeError("VM did not enter paused state") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--workdir", required=True) + parser.add_argument("--qemu", default="/usr/libexec/qemu-kvm") + parser.add_argument("--ovmf-code", default="/usr/share/edk2/ovmf/OVMF_CODE.fd") + parser.add_argument("--ovmf-vars", default="/usr/share/edk2/ovmf/OVMF_VARS.fd") + args = parser.parse_args() + report = {"probe": "kvm-qmp-uefi-smoke", "host": platform.node(), + "kernel": platform.release(), "success": False} + try: + probe(args, report) + report["success"] = True + except (OSError, ValueError, RuntimeError) as error: + report["error"] = str(error) + print(json.dumps(report, indent=2)) + return 0 if report["success"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/probes/qmp_command.py b/probes/qmp_command.py new file mode 100644 index 0000000..e396fb9 --- /dev/null +++ b/probes/qmp_command.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Execute one QMP command on an explicit local lab VM socket.""" +import argparse +import json +import socket + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('socket') + parser.add_argument('command') + parser.add_argument('arguments', nargs='?', default='{}') + args = parser.parse_args() + arguments = json.loads(args.arguments) + with socket.socket(socket.AF_UNIX) as connection: + connection.settimeout(15) + connection.connect(args.socket) + with connection.makefile('rwb') as stream: + json.loads(stream.readline()) + for command, values in [('qmp_capabilities', {}), (args.command, arguments)]: + stream.write((json.dumps({'execute': command, 'arguments': values}) + '\n').encode()) + stream.flush() + while True: + response = json.loads(stream.readline()) + if 'error' in response: + raise RuntimeError(response['error']) + if 'return' in response: + break + print(json.dumps(response['return'])) + + +if __name__ == '__main__': + main() diff --git a/probes/toolbox-install-hook-probe.sh b/probes/toolbox-install-hook-probe.sh new file mode 100644 index 0000000..21fe401 --- /dev/null +++ b/probes/toolbox-install-hook-probe.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Install overrides only in the disposable test container, preserving evidence. +set -euo pipefail +[[ $EUID == 0 && -f /run/.toolboxenv && -f /run/.containerenv ]] +source_adapter=$(realpath "$1") +adapter=/usr/local/libexec/archipelago-toolbox-systemd-hook +[[ ! -e $adapter ]] +mkdir -p /usr/local/libexec /etc/pacman.d/hooks +hooks=() +for hook in /usr/share/libalpm/hooks/*.hook; do + if grep -q '^Exec = /usr/share/libalpm/scripts/systemd-hook ' "$hook"; then + target=/etc/pacman.d/hooks/$(basename "$hook") + [[ ! -e $target && ! -L $target ]] + hooks+=("$hook") + fi +done +[[ ${#hooks[@]} -gt 0 ]] +install -m0755 "$source_adapter" "$adapter" +for hook in "${hooks[@]}"; do + sed "s|^Exec = /usr/share/libalpm/scripts/systemd-hook |Exec = $adapter |" \ + "$hook" > "/etc/pacman.d/hooks/$(basename "$hook")" + printf 'Adapted %s\n' "$(basename "$hook")" +done diff --git a/probes/toolbox-systemd-hook.sh b/probes/toolbox-systemd-hook.sh new file mode 100644 index 0000000..f67b578 --- /dev/null +++ b/probes/toolbox-systemd-hook.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Private adapter probe for Arch Toolbx 0.3; not a host hook or stable API. +set -eu +test -f /run/.toolboxenv && test -f /run/.containerenv || { + echo 'This adapter requires a Toolbx container' >&2 + exit 1 +} +op=${1:?Missing action} +shift +case "$op" in + daemon-reload-system|daemon-reload-user|enqueue-marked|reload|restart|binfmt|sysctl|udev-reload) + # Toolbx shares host runtime mounts but has no system manager of its own. + printf 'Toolbx: %s belongs to the host runtime; skipped in container\n' "$op" + ;; + tmpfiles) + # Keep container-local state creation. Exclude the reviewed upstream + # shared mounts and their /home and /mnt aliases; no blanket error ignore. + exec /usr/bin/systemd-tmpfiles --create -E \ + --exclude-prefix=/tmp --exclude-prefix=/home --exclude-prefix=/var/home \ + --exclude-prefix=/mnt --exclude-prefix=/var/mnt --exclude-prefix=/media \ + --exclude-prefix=/var/lib/flatpak \ + --exclude-prefix=/var/lib/systemd/coredump --exclude-prefix=/var/log/journal + ;; + catalog|hwdb|sysusers|update) + exec /usr/share/libalpm/scripts/systemd-hook "$op" "$@" + ;; + *) + printf 'Unreviewed Toolbx systemd hook action: %s\n' "$op" >&2 + exit 1 + ;; +esac diff --git a/probes/update_rollout_guest.py b/probes/update_rollout_guest.py new file mode 100644 index 0000000..6ac62e8 --- /dev/null +++ b/probes/update_rollout_guest.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Validate a terra-signed candidate on the retained GNOME VM, then rollback. + +Candidate checksum is an explicit validation input, not an advanced public channel. +The normal updater verifies the commit signature before staging. No /usr injection. +""" +import argparse +import json +from pathlib import Path +import pexpect +import shlex +import subprocess +import time + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--vm', type=Path, required=True) +parser.add_argument('--binary', type=Path, required=True) +parser.add_argument('--candidate', required=True) +parser.add_argument('--evidence', type=Path, required=True) +parser.add_argument('--resume', action='store_true', help='Resume validation of the recorded booted candidate') +parser.add_argument('--ssh-port', type=int, default=22296) +parser.add_argument('--bootstrap-update-profile', type=Path) +parser.add_argument('--bootstrap-update-key', type=Path) +args = parser.parse_args() +assert len(args.candidate) == 64 and all(c in '0123456789abcdef' for c in args.candidate) +args.evidence.mkdir(parents=True, exist_ok=True) +password = (args.vm / 'credential').read_text() +log = (args.evidence / 'guest.log').open('a' if args.resume else 'w') + + +def run(script, timeout=180, check=True): + c = pexpect.spawn('ssh', ['-tt', '-o', 'ConnectTimeout=5', '-o', + 'UserKnownHostsFile=' + str(args.vm / 'known_hosts'), '-p', str(args.ssh_port), + 'coretest@127.0.0.1', 'sudo -p SUDO_AUTH: bash -ec ' + shlex.quote(script)], + encoding='utf-8', timeout=timeout) + try: + c.expect('[Pp]assword:', timeout=15); c.sendline(password) + auth = c.expect(['SUDO_AUTH:', 'Permission denied', '[Pp]assword:'], timeout=15) + if auth != 0: raise RuntimeError('Guest authentication rejected') + c.sendline(password) + c.logfile_read = log + c.expect(pexpect.EOF) + text = c.before + c.close() + if check and c.exitstatus != 0: + raise RuntimeError('Guest command failed: ' + str(c.exitstatus)) + return text + finally: + if c.isalive(): c.close(force=True) + log.flush() + + +def state(): + text = run('ostree admin status --json') + return json.JSONDecoder().raw_decode(text[text.index('{'):])[0]['deployments'] + + +def booted(): + return next(d['checksum'] for d in state() if d['booted']) + + +def wait_boot(expected=None): + for _ in range(120): + try: + value = booted() + if expected is None or value == expected: return value + except (pexpect.ExceptionPexpect, RuntimeError, ValueError, StopIteration): + pass + time.sleep(3) + raise RuntimeError('Guest failed to boot expected deployment') + + +result = {'candidate': args.candidate, 'passed': False} +try: + if args.resume: + previous = json.loads((args.evidence / 'summary.json').read_text()) + assert previous['candidate'] == args.candidate + original = previous['original'] + pending = previous['updated'] + wait_boot(pending) + result.update(original=original, updated=pending) + else: + original = wait_boot() + result['original'] = original + if not args.resume: + c = pexpect.spawn('scp', ['-o', 'UserKnownHostsFile=' + str(args.vm / 'known_hosts'), + '-P', str(args.ssh_port), str(args.binary), 'coretest@127.0.0.1:/var/tmp/archipelago-updater'], + encoding='utf-8', timeout=120) + c.expect('[Pp]assword:'); c.sendline(password); c.expect(pexpect.EOF); c.close() + if c.exitstatus: raise RuntimeError('Updater upload failed') + if args.bootstrap_update_profile: + if not args.bootstrap_update_key: + raise RuntimeError('Bootstrap profile requires a public key') + for source, target in ((args.bootstrap_update_profile, 'rollout-update.json'), + (args.bootstrap_update_key, 'rollout-update.asc')): + c = pexpect.spawn('scp', ['-o', 'UserKnownHostsFile=' + str(args.vm / 'known_hosts'), + '-P', str(args.ssh_port), str(source), 'coretest@127.0.0.1:/var/tmp/' + target], + encoding='utf-8', timeout=120) + c.expect('[Pp]assword:'); c.sendline(password); c.expect(pexpect.EOF); c.close() + if c.exitstatus: raise RuntimeError('Bootstrap upload failed') + run('''test ! -e /etc/archipelago/update.json +install -m644 /var/tmp/rollout-update.json /etc/archipelago/update.json +''') + run('''set -e +archipelago self-check +getent passwd coretest > /var/tmp/rollout-account +test "$(cat /var/home/coretest/.archipelago-clean-persistence)" = "clean dropin candidate" +/var/tmp/archipelago-updater update plan > /var/tmp/rollout-channel-plan +''') + # Explicit candidate plan for pre-publication validation. All other captured + # preconditions stay unchanged. The production updater still verifies GPG. + text = run('cat /var/lib/archipelago/updates/plan-$(sed -n "s/^Plan: //p" /var/tmp/rollout-channel-plan).json') + plan = json.JSONDecoder().raw_decode(text[text.index('{'):])[0] + plan['target'] = args.candidate + run('printf %s ' + shlex.quote(json.dumps(plan, sort_keys=True)) + ' > /var/tmp/rollout-candidate-plan.json\n' + 'hash=$(sha256sum /var/tmp/rollout-candidate-plan.json | cut -d" " -f1)\n' + 'cp /var/tmp/rollout-candidate-plan.json /var/lib/archipelago/updates/plan-$hash.json\n' + 'printf %s "$hash" > /var/tmp/rollout-plan-id\n' + '/var/tmp/archipelago-updater update apply --plan "$hash"', timeout=3600) + pending = next(d['checksum'] for d in state() if d['staged']) + result['updated'] = pending + run('systemctl reboot', check=False) + wait_boot(pending) + run('''set -e +archipelago self-check +nano --version +systemctl is-active gdm NetworkManager ostree-finalize-staged.service +getent passwd coretest | cmp - /var/tmp/rollout-account +test "$(cat /var/home/coretest/.archipelago-clean-persistence)" = "clean dropin candidate" +diff -r /sysroot/boot/loader/entries /efi/loader/entries +pacman -Q epiphany gnome-calculator gnome-calendar gnome-contacts gnome-text-editor loupe papers gnome-clocks gnome-weather gnome-characters gnome-font-viewer gnome-connections file-roller simple-scan +ostree admin status --json > /var/tmp/rollout-before-stale +if archipelago update apply --plan "$(cat /var/tmp/rollout-plan-id)"; then exit 1; fi +ostree admin status --json > /var/tmp/rollout-after-stale +cmp /var/tmp/rollout-before-stale /var/tmp/rollout-after-stale +''') + metadata = run('cat /usr/lib/archipelago/extensions.json') + metadata = json.JSONDecoder().raw_decode(metadata[metadata.index('{'):])[0] + assert metadata['base'] == args.candidate and metadata['requested'] == ['nano'] + # Authenticate through native GDM; do not inject autologin configuration. + ui = ['python3', str(Path(__file__).resolve().parent / 'gnome_vm_input.py'), str(args.vm)] + active = run('''loginctl list-sessions --no-legend | awk '$3=="coretest" {print $1}' | xargs -r -n1 loginctl show-session -p Type --value | grep -qx wayland && echo WAYLAND_ALREADY_ACTIVE || true''') + if 'WAYLAND_ALREADY_ACTIVE' not in active: + subprocess.run(ui + ['--keys', 'spc', '--screen', 'update-gdm.png'], check=True) + time.sleep(5) + subprocess.run(ui + ['--text-file', str(args.vm / 'credential'), '--keys', 'ret', + '--screen', 'update-login.png'], check=True) + wait_script = '''until loginctl list-sessions --no-legend | awk '$3=="coretest" {print $1}' | xargs -r -n1 loginctl show-session -p Type --value | grep -qx wayland; do sleep 3; done''' + run('timeout 120 bash -c ' + shlex.quote(wait_script), timeout=150) + result['wayland_login'] = True + index = next(d['index'] for d in state() if d['checksum'] == original) + run('ostree admin set-default ' + str(index) + '; systemctl reboot', check=False) + wait_boot(original) + run('''set -e +archipelago self-check +nano --version +getent passwd coretest | cmp - /var/tmp/rollout-account +diff -r /sysroot/boot/loader/entries /efi/loader/entries +test "$(cat /var/home/coretest/.archipelago-clean-persistence)" = "clean dropin candidate" +''') + result['passed'] = True + run('systemctl poweroff', check=False) +except BaseException as error: + result['error'] = str(error) + raise +finally: + (args.evidence / 'summary.json').write_text(json.dumps(result, indent=2) + '\n') + log.close()