Commit Graph
242 Commits
Author SHA1 Message Date
oqyude 0ab45578d1 refactor: реестр адресов флота lib/xlib/net.nix
Один адрес — одно имя. Раньше 192.168.1.20 был написан 41 раз, 100.64.0.0
— семь, а зона CoreDNS и vhost'ы nginx жили в разных файлах и разъезжались
(например, kuma.zeroq.su остался в DNS после отключения uptime-kuma).

Реестр: хосты (LAN/tailscale/public), публичные DNS, сети, общие порты.
Все хардкоды адресов флота переведены на xlib.net.*.

Намеренно не тронуто: 127.0.0.1 и 0.0.0.0 (константы языка, не топология),
сеть 10.66.0.0/24 (у PXE-инфраструктуры своя опционная поверхность) и
home/modules/opencode.nix (рабочая конфигурация агента владельца, её
рефакторинг запрещён ADR-0009).

Поведение не изменилось: config-fingerprint до/после совпадает по всем
шести хостам.
2026-11-15 06:34:12 +03:00
oqyude d6d64d21c3 treefmt + samba dir changed
nixos flake checks / invariant-checks (push) Failing after 7s
test-runner / smoke (push) Successful in 1s
2026-11-07 18:37:42 +03:00
oqyude d1b1b07903 nginx: vhost vetymae.webmux.zeroq.su — webmux через sapphira, вход через Authelia
nixos flake checks / invariant-checks (push) Successful in 1m53s
test-runner / smoke (push) Successful in 1s
webmux (github.com/samoylenkodmitry/webmux) — веб-терминал к tmux-сессиям на
vetymae; на хосте уже поднят scheduled task'ом WebmuxServe
(HOST=0.0.0.0 PORT=8083). Не хватало входа снаружи.

Vhost (sapphira): proxyPass на LAN-адрес 192.168.1.100:8083 (tailscaled на
vetymae в NoState — пакетов не принимает), proxyWebsockets +
proxy_read/send_timeout 3600s (терминал стримится по WS /ws/session/<name>).

Вход — Authelia forward-auth, как на tty.zeroq.su: у webmux НЕТ своей
аутентификации («кто достучался до порта — получил шелл твоим пользователем»),
а его README прямо запрещает 0.0.0.0 и публичный интернет. Wildcard
*.zeroq.su в access_control покрывает домен, правки политики не нужно.

Плюс ADR-0010, T61 и строка в AGENTS.md.
2026-11-06 15:56:36 +03:00
oqyude bbc15699a5 fix(sops): каталоги-родители секретов opencode принадлежат пользователю
nixos flake checks / invariant-checks (push) Successful in 1m13s
test-runner / smoke (push) Successful in 1s
home-manager на rydiwo падал при активации:
  ln: failed to create symbolic link
    '/home/oqyude/.config/opencode/opencode.json': Permission denied
→ home-manager-oqyude.service: status=1/FAILURE, домашняя активация не
применялась.

Причина: sops-nix создаёт отсутствующие каталоги-родители секретов от root
(0755 root:root) и не меняет владельца уже существующих. На rydiwo секреты
opencode появились раньше home-manager (13.10 против 06.11), поэтому
~/.config/opencode и ~/.local/share/opencode остались root:root. На sapphira
те же каталоги создал home-manager (как пользователь) — там не сломано.

sops-nix не умеет менять владельца каталога-родителя, поэтому делаем это в
активации системы (root), снипет после 'users' — до старта
home-manager-<user>.service. chown/install через '|| echo': у activate
скрипта ERR-trap, и падение сделало бы активацию проваленной при уже
переключённой системе.

Заодно в home/modules/opencode-desktop.nix: timeout 600/900 на прогрев
плагина и npx-кеша — зависшая загрузка не должна держать активацию
(и пересборку) намертво.
2026-11-06 15:22:43 +03:00
oqyude 51a3723abb opencode: rydiwo — opencode v2 + browser-control под rydiwo.opencodes.zeroq.su
Desktop-адаптация opencode на rydiwo (device: secondary, Plasma 6/Wayland).

- новый модуль home/modules/opencode-desktop.nix (импорт в home/secondary.nix):
  opencode 2.0.32 из nixpkgs-master, плагин oh-my-opencode-slim@3.0.5,
  конфиг slim/permissions/дефолт модели — как на vetymae (эталон), webpage-MCP
  выключен, плюс MCP browser-control (@opencode-ai/browser-control@0.8.4);
  opencode serve как systemd user service на 0.0.0.0:4096 с
  --cors https://rydiwo.opencodes.zeroq.su и паролем из sops-окружения;
  обёртки oc и browser-control; Chromium в home.packages.
- nginx (sapphira): vhost rydiwo.opencodes.zeroq.su -> 100.92.238.19:4096
  (tailscale; LAN 192.168.1.102 — DHCP-lease, уже уезжал на LAMET).
- computer-use и genoffice MCP не перенесены (Windows-only) — ADR-0009.
- ADR-0009, задача T60, AGENTS.md (инвариант 17 + две ловушки).
2026-11-06 14:44:35 +03:00
oqyudeandClaude Opus 4.5 569f130b78 nginx: reverse proxy opencode для etherea и dejavu
nixos flake checks / invariant-checks (push) Successful in 1m33s
test-runner / smoke (push) Successful in 1s
По образцу lamet.opencodes.zeroq.su — два новых vhost в
modules/server/nginx.nix:

- etherea.opencodes.zeroq.su → http://100.125.228.63:4096
  (tailscale). Апстрим: opencode v2.1.1 в service-режиме
  (`opencode serve --service`), читает ~/.config/opencode/service.json
  (hostname 0.0.0.0, port 4096, basic-auth opencode/<пароль>).
  Проверено с sapphira: HTTP 200, отдаёт web-UI OpenCode.

- dejavu.opencodes.zeroq.su → http://100.86.134.111:4096
  (tailscale). На момент правки хост офлайн (last seen 8h) — апстрим
  не проверен, vhost отдаст 502, пока хост не вернётся в tailnet.

DNS: *.opencodes.zeroq.su — wildcard CNAME на home.zeroq.su,
правки зоны не требуются. LE-сертификаты для обоих доменов выпущены
(acme-etherea/dejavu.opencodes.zeroq.su.service — status=0).

Проверки: nix build sapphira (ok), nixos-rebuild switch (ok),
.ci/checks.sh --no-build (4/4 PASS), nginx -t (ok), systemctl --failed
пуст.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-11-05 22:37:34 +03:00
oqyude 730800d660 sddm: починить тему WhiteSur после plasma-workspace 6.8 (экран входа rydiwo)
nixos flake checks / invariant-checks (push) Successful in 1m17s
test-runner / smoke (push) Successful in 1s
plasma-workspace 6.8.1 убрал VirtualKeyboardLoader из
org.kde.breeze.components, а SDDM-тема WhiteSur (whitesur-kde 2024-11-18)
всё ещё его инстанцирует. Гритер не мог загрузить Main.qml:

  Main.qml:316:9: VirtualKeyboardLoader is not a type
  Fallback to embedded theme

и экран входа молча деградировал до встроенной плоской заглушки.

- overlays/patch-whitesur-sddm.pl: заменить VirtualKeyboardLoader на
  Keyboards.KWinVirtualKeyboard (API актуальной breeze-темы), сохранив
  интерфейс inputPanel (keyboardActive/showHide), который используется
  в других местах Main.qml
- overlays/pkgs.nix: overlay на whitesur-kde, гоняет патч по sddm/*/Main.qml
- theming.nix: включить whitesur-cursors (kwin писал
  `Failed to load cursor theme "WhiteSur-cursors"`)
- kde.nix: sddm.extraPackages = plasma-desktop + qtsvg (требование пакета)

Проверено на rydiwo (поколение 91, display-manager перезапущен):
Fallback to embedded theme — 0 раз, VirtualKeyboardLoader is not a type — 0,
гритер создал вью на реальном выходе (DSI-1, 1324x828).
2026-11-05 21:17:03 +03:00
oqyude ecb69c2a1a fix(nixos): убрать boot.initrd.verbose и переименовать lidSwitch* — флейк не оценивается
nixpkgs 31ecbaca удалил опцию boot.initrd.verbose, поэтому nixos-rebuild switch падал в фазе оценки (evaluation) на rydiwo. Управление verbosity initrd теперь через rd.systemd.show_status в kernelParams.

Опции services.logind.lidSwitch / lidSwitchDocked переименованы в nixpkgs в services.logind.settings.Login.HandleLidSwitch / HandleLidSwitchDocked; значения сохранены.
2026-11-01 17:35:23 +03:00
director b1ad41942a Merge branch 'agent/samba-ad': модуль host.samba-ad (выключен по умолчанию)
nixos flake checks / invariant-checks (push) Canceled after 1m8s
test-runner / smoke (push) Successful in 1s
Владелец разрешил слить вручную (у oqyude/nixos merge_allowed=false —
живая конфигурация хоста, director.sh merge такой репозиторий не берёт).

Модуль не активируется: host.samba-ad.enable = false. Включение упирается
в assertion'ы — порт 53 занят coredns, 445 занят файловым samba; оба
конфликта названы, а не обойдены.
2026-10-31 03:08:00 +03:00
oqyude 94b28f9bfc Samba AD DS: модуль-опция (выключен по умолчанию) + доказательства
Исследование по исходникам пина 31ecbaca (26.11), samba 4.23.10:

* В nixpkgs `services.samba` НЕТ ни одной опции AD DC — ни
  enableActiveDirectoryDomainController, ни domainName/realm/serverRole.
  Единственное похожее — settings.global.security = "ads" (вход в
  существующий домен как member server, а не DC).
* pkgs.samba собран --without-ad-dc --without-ldap --without-ads: бинаря
  samba-tool в нём нет вообще (проверено на работающем на sapphira
  файловом сервере). Для DC нужен отдельный пакет; берём минимальный
  override samba4.override { enableLDAP = true; enableDomainController = true; },
  а не pkgs.samba4Full (cups + avahi + cephfs лишним весом).
* samba-tool domain provision берёт realm из smb.conf (флага --realm нет),
  пишет <targetdir>/etc/smb.conf, private/, state/sysvol/, bind-dns/.
  Шейры [sysvol] и [netlogon] обязательны: lp.get("path", "<имя шейры>")
  возвращает path именно этой секции, иначе MissingShareError.
  Непустой smb.conf не перезаписывается — поэтому шаблон задаёт
  dns forwarder / dns port / server services.
* Провижининг НЕ идемпотентен → идемпотентность сделана в юните
  (наличие private/sam.ldb → skip, exit 0).

Конфликты на sapphira (ссороться за порты нельзя, оба — assertion):
  53/tcp+udp  coredns (зоны zeroq.su + home.arpa) против AD DNS
  445/tcp     samba-smbd (файловый сервер) против DC (нужен для sysvol/GPO)
Оба порта — с внятным текстом и тремя вариантами решения; по умолчанию
предложен отдельный хост. Время не блокер: chronyd, расхождение ≈0.5 мс
при требовании ≤5 минут.

Что добавлено:
* modules/server/samba-ad.nix — опция host.samba-ad (enable = false),
  юниты samba-ad-provision.service (oneshot, идемпотентный) и
  samba-ad.service (Type=notify), smb.conf-шаблон в state dir,
  пароль администратора только из sops-секрета (в рантайме).
* modules/server/default.nix — импорт (выключено).
* modules/server/samba.nix — samba-smbd теперь создаётся только при
  services.samba.enable. Без этого выключение файлового сервера (нужное,
  чтобы отдать 445 DC'у) оставляло фантомный юнит без ExecStart —
  ровно ловушка ADR-0004 / R1.14. Для работающих хостов поведение
  не меняется ни на байт.

Доказательства (ничего не активировано):
* enable=false: конфигурация оценивается, юнитов samba-ad* нет, AD-вариант
  samba в замыкании отсутствует (0 совпадений).
* enable=true: конфигурация падает с тремя assertion'ами (realm не задан,
  53 занят, 445 занят) — правильный результат.
* enable=true + конфликты сняты: drvPath
  /nix/store/hm0i8qmni34b2j5bcjak1yvmg2s3y20p-nixos-system-sapphira-default.drv,
  в плане сборки AD-сборка samba, шаблон smb.conf и оба юнита.

Открытые решения владельца (имя домена/realm, где живёт DC, делегирование
DNS, пароль, нужен ли DC на sapphira) — в .agent/notes/samba-ad-2026-10-30.md.
2026-10-30 19:25:59 +03:00
director 877caa381d beets: монтировать ~/Music после активации home-manager
nixos flake checks / invariant-checks (push) Successful in 3m13s
test-runner / smoke (push) Successful in 1s
После перезагрузки 2026-10-30 17:33 юнит
home-oqyude-.config-beets.mount был в failed:

  mount: special device /home/oqyude/Music does not exist

Источник монтирования — симлинк, который создаёт home-manager при своей
активации (~/Music -> /nix/store/…-home-manager-files/Music -> ~/External/Music).
Монтирование стартовало параллельно с активацией и проиграло гонку.

Порядок (After=), а не Requires=: на хостах, где home-manager для этого
пользователя не запускается, зависимость от несуществующего юнита уронила
бы монтирование целиком, а порядок без такого юнита просто игнорируется.

Сейчас юнит руками перезапущен и активен; правка нужна, чтобы это не
повторилось при следующей загрузке.
2026-10-30 18:19:55 +03:00
director ce7292284d nginx: убрать мёртвый vhost health.zeroq.su (netdata не существует)
nixos flake checks / invariant-checks (push) Successful in 1m58s
test-runner / smoke (push) Successful in 1s
Проверка живая, не по конфигу: из 19 локальных портов, на которые
ссылается nginx, не отвечает ровно один — 127.0.0.1:19999. Netdata в
этой системе не установлен вообще: ни юнита, ни процесса, только
1.5 ГБ мусора в /var/cache/netdata.

Без upstream vhost отдаёт 502, то есть домен выглядел как «сломанный
сервис», хотя сервиса нет. Вернуть — вместе с модулем netdata.
2026-10-30 18:00:18 +03:00
director 861b19e1e1 server: immich вернуть, glances выключить
test-runner / smoke (push) Successful in 1s
nixos flake checks / invariant-checks (push) Successful in 3m11s
Владелец: immich нужен, glances нет.

  immich    — возвращён импорт и vhost immich.zeroq.su. Юниты были
              enabled, но остановлены в 15:07; кэш ML-моделей (2.9 ГБ),
              который директор удалил, скачается заново при первом
              ML-задании. Пик памяти ~1.3 ГБ.
  glances   — выключен (порт 61208, openFirewall открывал его наружу).
              Записи coredns (glances.zeroq.su) оставлены: указывают
              в закрытый порт.

Остаются выключенными только uptime-kuma и open-webui — оба были failed.
Устаревший комментарий про «open-webui никогда не комментировался» снят:
теперь это неправда.
2026-10-30 15:40:36 +03:00
director 06f2237b16 server: выключить три мёртвых сервиса (uptime-kuma, open-webui, immich)
nixos flake checks / invariant-checks (push) Canceled after 6m32s
test-runner / smoke (push) Successful in 4s
Все три не работали — выключение не отнимает функцию, а убирает падающие
юниты и фоновую работу:

  uptime-kuma  uptime-kuma.service failed (timeout) с 15:09 сегодня
  open-webui   podman-open-webui.service failed; образ 4.69 ГБ тянулся
               с ghcr.io и обновлялся автоматически
  immich       immich-server / immich-machine-learning / redis-immich —
               все inactive dead, но кэш ML-моделей занимал 2.9 ГБ

Убраны и nginx-вхосты (immich.zeroq.su, kuma.zeroq.su, open.zeroq.su):
vhost без upstream отдаёт 502.

Измерено перед правкой: все сервисы вместе ~640 МиБ RSS, то есть
разгрузка тут не про память, а про мусор (падающие юниты, 4.69 ГБ
образа, 2.9 ГБ кэша моделей).

Вернуть: раскомментировать строки — в комментариях рядом указано, что
вернуть вместе с чем.
2026-10-30 15:34:19 +03:00
director 9cf846b82c nextcloud: drop adminuser/adminpassFile — removed upstream in nixpkgs 31ecbaca
nixos flake checks / invariant-checks (push) Failing after 15m4s
test-runner / smoke (push) Successful in 2s
nixpkgs 31ecbaca (flake update 7a5c9c6) replaced both options with
mkRemovedOptionModule: leaving them makes evaluation of EVERY host fail
with 'Failed assertions', so the flake update alone could not be deployed.

  - services.nextcloud.config.adminuser    -> removed
  - services.nextcloud.config.adminpassFile -> removed
  upstream: 'use nextcloud-occ user:add <username>'

On this installation the admin user already exists, so the two settings
were already inert. Verified with
  nix build --dry-run .#nixosConfigurations.sapphira...toplevel
=> evaluates; 744 derivations will be built, 1640 paths fetched.
2026-10-30 14:20:11 +03:00
director 904352a077 3x-ui: publish the local proxy port 10808 on the host loopback
nixos flake checks / invariant-checks (push) Successful in 2m9s
test-runner / smoke (push) Successful in 1s
The telegram control channel reaches Telegram through the node outbound
telegram-edge-of-truth: the panel's inbound host-egress listens on 10808
inside the container. Publishing it on 127.0.0.1 only lets host
processes use it (curl -x socks5h://127.0.0.1:10808) without exposing
it to the LAN.

The change was live in the running container but uncommitted; committed
by the director on the owner's instruction (E.2, 2026-10-27) so the next
rebuild does not silently drop it.
2026-10-27 16:11:42 +03:00
oqyude a4ee09dca0 3x-ui: pin image v3.11.0 (xray 26.10.21), ADR-0007
Бандл v3.10.2 тянул ядро Xray 26.10.10, которое апстрим отозвал:
release notes v3.11.0 говорят «the pulled v26.10.10 binary pins are
replaced». Пин остаётся явным тегом (R1.5) — :latest не возвращается.

- modules/containers/3x-ui.nix: v3.10.2 -> v3.11.0, история инцидента в
  комментарии сохранена и дополнена.
- .agent/decisions/0007-3x-ui-3.11.0.md: контекст, решение, последствия
  (REALITY: fp in {chrome,firefox,safari}, minClientVer 1.0.0, R1.16),
  риски, откат через бэкап тома db/ (миграции БД необратимы), чеклист
  после rebuild. index.json: запись 0007.
- AGENTS.md, project-rules.md (R1.5/R1.8), project-state.md,
  manifest.md (T43/T44), .ci/checks.sh: фактические упоминания версии и
  номера строки (:62 -> :71). Хроника notes/3x-ui-xray-26.9.md не
  переписана, добавлена ссылка на 0007.
2026-10-25 23:42:09 +03:00
oqyude 066b3acec1 refactor(nix): consolidate fragmented attribute-path writes
Same owner written as '.a = ...; .b = ...;' repeated dotted paths is now one
attrset block. Behaviour-preserving (values, list order and comments kept):

- 3xui-reconfig description/serviceConfig in server/ and vds/ (separate units,
  different PANEL_URL - deliberately not extracted into a shared module)
- authelia after/wants inside the existing config = mkIf wrapper
- gitea-actions-runner settings: runner/metrics/health_check/container
- boot.loader.grub, services.logind, pxe-infra.bridge, pipewire.alsa
- nix.{distributedBuilds,buildMachines}; nix.settings on WSL (mkForce kept)
- build.activation on termux (nix-on-droid freeform)

Also in this commit: lamet.opencodes.zeroq.su upstream 6061 -> 4096
(verified by nix eval of the vhost proxyPass).

nix-instantiate --parse: 12/12 files OK.
2026-10-25 02:10:05 +03:00
oqyude 69691f96d1 fix(systemd): move the storage guard into [Unit] (T4/T52)
mkStorageGuard returned a serviceConfig fragment, so ConditionPathIsMountPoint
landed in [Service] where systemd ignores it - the guard was dead on 13 units.

- helper now returns a unitConfig fragment ([Unit]); RequiresMountsFor still
  intentionally absent
- consumers re-pointed at the real unit names: samba-smbd, phpfpm-nextcloud,
  immich-server, podman-3xui_app, podman-taperotation-{backend,frontend};
  the old serviceConfig keys silently rendered three empty phantom units
- vds excluded: otreca has no /home/oqyude/External and a live condition would
  skip podman-3xui_app and kill the 3x-ui panel at pubray1.zeroq.su

Verified: sapphira and otreca toplevel builds exit 0; all 13 units carry the
condition under [Unit] (line 3), zero occurrences under [Service].
2026-10-25 02:09:40 +03:00
oqyude 1adf6dd90c refactor(pxe-infra): move the pxe-infra option surface next to the feature (T46)
modules/options.nix was 433 lines, of which 351 (80%) were the
`options.pxe-infra` block. That file is documented as the home of
cross-module options, but the pxe-infra surface belongs to one feature that
already owns a directory of eight modules.

modules/pxe-infra/default.nix had already made this call for the sibling
option and said so at :26-33: "Declared here (not in modules/options.nix)
because this task's scope is modules/pxe-infra/ only". This commit applies the
same rule to the rest of the surface, which also removes the split where
`pxe-infra.bootloader` lived in one file and
`pxe-infra.bootloader.bypassFallback` in another.

The moved block is byte-identical — md5 e672a94dd9676cff1e3dd5096499232c for
both the old range (modules/options.nix:82-432) and the new
(modules/pxe-infra/options.nix:15-365), 351 lines. modules/options.nix is now
81 lines and holds only `host.builder` and `host."3x-ui"`, plus a pointer to
where feature-local options live.

Behaviour is preserved:
  - the declared option set is unchanged: still exactly
    `options.pxe-infra` and `options.pxe-infra.bootloader.bypassFallback`;
  - `modules/pxe-infra/default.nix` imports ./options.nix, so the option
    exists on every host that imports the umbrella;
  - the only place outside modules/pxe-infra/ that touches it is
    configurations/mini-laptop.nix:88, and that host imports
    ../modules/pxe-infra at :17. No other host reads config.pxe-infra.

Verified: import-graph green (120 files, 120 references), checks PASS 3 /
FAIL 0.

Not verified here: `nix flake check`. There is no nix binary on this machine,
so evaluation must be confirmed by the owner before this is deployed.

Not pushed.
2026-10-24 02:33:22 +03:00
oqyude 0d52f2058d refactor(modules): drop the duplicated WSL nix-serve module (T45)
modules/wsl/nix-serve.nix was a byte-identical copy of
modules/server/nix-serve.nix — md5 0aca1128f12f975d2376db21fbd92e40 for both.
Two live hosts, two copies of the same 25 lines: any fix to one silently
missed the other.

The WSL module now imports ../server/nix-serve.nix.

Equivalence is established by content, not by a run: the module body is
identical, and its `sopsFile = ./secrets/nix-serve.yaml` resolves relative to
the importing file — so WSL now reads
modules/server/secrets/nix-serve.yaml, which is itself byte-identical to the
copy it used to read (md5 af6e04419e8b3dd467c8cb693f374782 for both). The
evaluated configuration is therefore unchanged; only the paths differ.

`services.nix-serve` is now declared by exactly one file in the repo.

Verified: import-graph check green (119 .nix files, 119 references), and
`bash .ci/checks.sh --no-build` -> PASS 3 / FAIL 0.

Note: modules/wsl/secrets/nix-serve.yaml is now unreferenced. It is NOT
deleted here — secrets need explicit owner sign-off, see
.agent/tasks/manifest.md T53.

Not pushed.
2026-10-24 02:25:38 +03:00
oqyude 39e1887d78 docs(modules): уточнить пути и счётчики в комментариях
test-runner / smoke (push) Successful in 1s
nixos flake checks / invariant-checks (push) Canceled after 0s
- xlib: mkXlib из lib/xlib/default.nix (было lib/xlib.nix);
- архив: ../../archive/ от modules/server, 12+3 модуля;
- убраны устаревшие номера строк в ссылке на T16.

Проверки: PASS 3, FAIL 0; граф импортов 120 файлов, 119 ссылок.
2026-10-24 02:17:25 +03:00
oqyude 13e90d06b5 chore(modules): delete 12 unreferenced modules (T41)
None of these are reachable from any import, so removing them cannot change
evaluation. Verified with the import-graph check added in 1b188fb, which is
green before and after (132 -> 120 .nix files, 119 references resolve), and
with an exact import-shaped grep for each path (zero hits outside archive/).

Deleted:
  modules/other/{daw,musnix,virtual,wine}.nix
  modules/other/gaming/{aagl,nix-gaming}.nix
  modules/other/self/fingerprint.nix
      modules/default.nix only imports ./<device-type>, and `other` is not a
      device type (lib/xlib/device.nix:12-41). Four of these also import flake
      inputs that are commented out in flake.nix (:8 fingerprint, :102
      nix-gaming, :103 aagl, :110 musnix), so they could not even evaluate.
  modules/server/requirements.nix
      Orphaned copy of a subset of the pins that modules/server/engipy-backend.nix
      embeds inline at :46-67. The two lists had already diverged: the orphan
      had 14 entries, the live one has 20+ (structlog, pandas, openpyxl,
      python-multipart, python-dotenv were missing from the orphan).
  modules/containers/remnanode.nix
      tmpfiles-only; its three rules duplicate modules that are imported.
  modules/containers/remnawave-examples/{docker-compose-local,docker-compose-prod}.nix
      compose2nix snapshots of the abandoned remnawave stack; the real module
      is preserved in archive/containers/remnawave.nix.
  modules/vds/glances.nix
      Byte-identical to modules/server/glances.nix (md5 f0133606...), whose
      import at modules/vds/default.nix:13 was commented out.

Also drops the now-dangling `# ./glances.nix` line from modules/vds/default.nix.

Deliberately NOT deleted, because "not imported" there means "disabled on
purpose" rather than "abandoned", and git history alone would not recover the
intent:
  modules/vds/netbird.nix            (40 lines, every option `enable = false`)
  modules/wsl/tools/default.nix      (16 lines, a commented-out dev toolchain)
  home/apps/v2rayn.nix               (23 lines, pairs with a package that is
                                      still installed in home/modules/packages.nix:19)

Note: the commented-out flake inputs in flake.nix that existed only for
modules/other/ are now vestigial. Left in place — removing them also rewrites
flake.lock behaviour and needs a nix run, see .agent/tasks/manifest.md T54.

Not pushed.
2026-10-24 01:46:23 +03:00
oqyude 299116495c test(ci): проверка целостности графа импортов вынесена в скрипт
test-runner / smoke (push) Successful in 1s
nixos flake checks / invariant-checks (push) Canceled after 0s
.ci/tests/import-graph.py — проверяет, что каждый .nix ссылается только
на существующие файлы и каталоги. Раньше логика жила инлайн в
checks.sh и не была переиспользуема.

Проверки: PASS 3, FAIL 0.
2026-10-24 01:45:59 +03:00
oqyude 262b966b1e regress need to be reversed
test-runner / smoke (push) Successful in 1s
nixos flake checks / invariant-checks (push) Canceled after 0s
2026-10-24 01:40:02 +03:00
oqyude af12e286c0 feat(3x-ui): вынести панель в отдельный модуль и подключить на сервере и VDS
test-runner / smoke (push) Successful in 1s
- modules/3x-ui/: новый модуль вместо правок внутри modules/containers/
- modules/server/default.nix и modules/vds/default.nix: подключение модуля
2026-10-23 00:30:01 +03:00
opencode 69fd72b602 chore(pxe-infra): drop the diagnostic autoexec.ipxe (T24 RCA done)
test-runner / smoke (push) Successful in 0s
The diagnostic (ifstat/route/ping) is what identified the closed
interface behind the 'Network unreachable' chain failure; the root cause
is fixed in vm.nix (e1000), so the rig goes back to a plain chain.
2026-10-21 21:08:22 +03:00
opencode 33bc04e6ef fix(pxe-infra): move the e1000 rationale out of the continued qemu command
test-runner / smoke (push) Successful in 1s
A '#' comment inside a backslash-continued shell command is not a
comment: the shell swallowed the rest of the script, so qemu started
without the -device line ('netdev net0 has no peer'). The rationale now
sits above the exec.
2026-10-21 21:03:03 +03:00
opencode 456236792f fix(pxe-infra): give the rig guest an e1000 NIC instead of virtio-net (T24)
test-runner / smoke (push) Successful in 1s
With virtio-net the guest's OVMF claims the device with its own
virtio-net driver and exposes no SNP handle, so iPXE falls back to its
own virtio-net driver and cannot open the device the firmware already
holds. The interface stays closed, the routes are marked inaccessible
and every HTTP fetch fails with 'Network unreachable' - the chain dies
before the payload is even fetched.

Measured on rydiwo 2026-10-21 with the diagnostic autoexec.ipxe:

  virtio-net-pci: net0: ... using virtio-net ... [closed]
                   route: net0: 10.66.0.10/255.255.255.0 gw 10.66.0.1 (inaccessible)
                   ping: timeout ; http://10.66.0.1/boot.ipxe... Network unreachable

  e1000:           net0: ... using 82540em ... [open]
                   route: net0: 10.66.0.10/255.255.255.0 gw 10.66.0.1
                   ping: replies ; boot.ipxe / vmlinuz-virt / initramfs-virt all ok

The guest kernel is unaffected: linux-virt ships e1000.ko and the
read-only payload loads it from the rootfs.
2026-10-21 20:59:16 +03:00
opencode a49916549f diag(pxe-infra): print iPXE network state in autoexec (T24 diagnosis)
test-runner / smoke (push) Successful in 1s
2026-10-21 20:55:06 +03:00
opencode 0c4139cd1f feat(pxe-infra): chain the read-only payload (kernel+initrd) instead of sanboot (T24)
test-runner / smoke (push) Successful in 0s
The worker payload is now a read-only squashfs rootfs carried INSIDE the
initramfs (build/alpine-worker/build-squashfs.sh), so the guest needs no
disk and no root UUID.

boot.ipxe therefore loads vmlinuz-virt + initramfs-virt over HTTP and
boots them; the initramfs attaches the embedded squashfs read-only and
switch_roots into the worker system.

This drops iPXE's SAN-boot extension from the production chain - the
dependency behind T14 (the 6.18.57 PCI-match regression) and risk R1
(SAN under ESXi EFI, never verified). The disk profile and its sanboot
chain stay reachable through boot-bypass.ipxe as the legacy path.

bootMode=pxe already attached no disk (vm.nix), so no change there.
2026-10-21 18:09:51 +03:00
oqyude 5a7db9fd36 fix(opencode): глобальный model в opencode.json, чтобы агенты slim-плагина не сбивались на free-тариф
test-runner / smoke (push) Successful in 0s
В v2 без явного выбора CLI берёт модель из реестра сам
(opencode/minimax-m3.1-flash-free) и передаёт её явно — она перебивает
модель агента, заданную oh-my-opencode-slim. Проверено по сообщению в БД:
без фикса запрос шёл на бесплатной модели. Рабочая машина обходится за счёт
«помни последний использованный» в TUI, серверная БД пустая.
2026-10-21 17:09:27 +03:00
oqyude 68294e8e0b 3x-ui update
test-runner / smoke (push) Successful in 0s
2026-10-21 13:53:10 +03:00
oqyude 4940a1e287 docs(pxe-infra): correct the stale description of the latest/ path
test-runner / smoke (push) Successful in 0s
The comment said 'A latest/ symlink points at the newest <rev>'. Since
T18 the worker deploy publishes into a real latest/ directory with a
rename(2); the symlink scheme was measured to be non-atomic (GNU
mv -T on a symlink-to-directory copies instead of renaming). The
iPXE scripts address the path, not the object type, so nothing in the
behaviour changes - only the description.
2026-10-20 16:03:04 +03:00
oqyude 0d9c892b4f feat(pxe-infra): make the kernel+initrd chain boot the real rootfs (T19)
test-runner / smoke (push) Successful in 1s
Mirrors the change in pxe-infra-automation (T19). The bypass chain
loaded the kernel and the initramfs over HTTP and then failed with
"mounting /dev/ram0 on /sysroot failed" - the root filesystem is the
worker's ext4 partition, addressed by UUID, and the script pointed at a
device that does not exist. The disk was visible the whole time
(virtio_blk virtio1: [vda] 2097152); only the command line was wrong.

Now the script fetches the root UUID from the HTTP root with isset and
puts it on the kernel command line, matching the options the
systemd-boot entry uses. The image must be attached to the guest as a
local block device (EXTRA_DRIVES in direct mode); the rootfs is not
inside the initramfs.

This path does not use iPXE's sanboot, so it works on firmware without
INT13 SAN extensions - which is what makes the ESXi rig usable
regardless of risk R1.

The production chain (boot.ipxe, sanboot) is unchanged; this script is
only reached when pxe-infra.bootloader.bypassFallback.enable is set.

The UUID is published next to the image by the pxe-infra-automation
deploy script, and is written without a trailing newline because iPXE
copies the file's contents into a variable verbatim.

Not verified on hardware: the artifact has not been republished since
the change.
2026-10-20 15:48:45 +03:00
oqyude 665f38a501 feat(ci): add the ci devshell with the Gitea runner tool set
test-runner / smoke (push) Successful in 1s
Раннер на sapphira отдаёт job'у PATH, равный своему hostPackages, и он
фиксируется в systemd-юните при активации -- чтобы добавить туда инструмент,
нужен nixos-rebuild switch на хосте. Для workflow'ов в oqyude/winos это тупик:
jq (scripts/update-manifest.sh) и pwsh (scripts/update-kvrt.ps1) в наборе
раннера отсутствуют, а nix-shell -p не запасной путь -- реестр nix на sapphira
пустой, каналов нет, -p не находит nixpkgs.

Что сделано:
- lib/ci-tools.nix -- один список инструментов CI.
- devshells/default.nix: devshell `ci` (nix develop .#ci) с этим списком.
  Workflow может взять PATH devshell'а и получить jq/pwsh без пересборки:
    nix develop /etc/nixos#ci --command bash -c 'echo $PATH'
- modules/server/gitea-runner.nix: hostPackages берёт тот же список, чтобы
  набор раннера и devshell не расходились; в списке теперь ещё и powershell.

Проверка: devshell собирается на sapphira (nix develop /etc/nixos#ci) и
отдаёт jq и pwsh.
2026-10-20 15:11:23 +03:00
oqyude 78c50dee87 feat(runner): add jq to hostPackages
test-runner / smoke (push) Successful in 1s
PATH of a host-mode job is exactly this list (nixos upstream module: path = coreutils ++ optionals wantsHost instance.hostPackages), so a tool that is not listed here simply does not exist for the job.

scripts/update-manifest.sh in oqyude/winos hard-requires jq -- 'for dep in curl jq' -- and calls it 14 times. It is a vendored script (logic preserved verbatim from Dicklesworthstone/scoop-bucket), so the tool belongs here rather than being rewritten out of the script.

Effect: the bucket auto-update workflow in oqyude/winos can actually apply the manifest updates it detects. Without jq it failed at 'required tool not found: jq' and every update was skipped.

Requires a rebuild on sapphira to take effect: the runner's systemd unit gets its PATH from hostPackages at activation time.
2026-10-20 00:05:27 +03:00
Sisyphus 585415905d feat(engipy-backend): deploy T-MULTI-MODEL-REGISTRY (3-model registry, ENGIPY_MODELS_DIR)
test-runner / smoke (push) Successful in 1s
T-MULTI-MODEL-REGISTRY (engipy cd64a8e, 2026-10-18) переводит прод с
single-model 'cointegrated/rubert-tiny2' на 3-модельный реестр:
rubert-tiny2 (default) + BAAI/bge-m3 + intfloat/multilingual-e5-large.
UI dropdown в фронте, GET /api/models endpoint.

* engipy-backend.nix: добавлена опция modelsDir (default
  /mnt/lamet/engipy-models) + ENV var ENGIPY_MODELS_DIR в systemd unit
* engipy-backend.nix: добавлена ENV var ENGIPY_EMBEDDINGS_DIR (=dataDir)
  чтобы bge-m3 / e5-large .npy искались рядом с дефолтным embeddings
* mini-laptop.nix: model override теперь указывает на
  /mnt/lamet/engipy-models/rubert-tiny2 (вместо legacy
  /var/lib/engipy/model/cointegrated__rubert-tiny2 — single-model style)
* .gitignore: .metaagent-director/ runtime-артефакты

Refs: engipy cd64a8e, T-MULTI-MODEL-REGISTRY
2026-10-18 13:42:01 +03:00
oqyude 1faef1d5e4 fix(engipy-frontend): T-FIX-BADZIP auth sub-request body off + Content-Length clear
test-runner / smoke (push) Successful in 1s
T-FIX-BADZIP (round 2): POST /api/match возвращал nginx-HTML 500 даже после фикса бэкенда, потому что:

- nginx auth_request по умолчанию шлёт sub-request с методом parent'а (POST для upload);
- В /authelia location не было `proxy_pass_request_body off` и `Content-Length ""`;
- nginx пересылал Content-Length в sub-request к Authelia, но не само тело;
- Authelia ждала обещанные байты и отвечала 408 (Request Timeout);
- nginx auth_request не классифицирует 408 как 2xx/4xx и возвращал клиенту 500.

vtimeline.zeroq.su уже починил этот же баг (vtimeline.nix + комментарий в nginx.conf) — engipy-frontend.nix просто забыл скопировать паттерн. Копирую.

Refs: T-FIX-BADZIP (production bug: HTTP 500 при загрузке xlsx через nginx/Authelia)
2026-10-17 00:58:08 +03:00
oqyude bb8dcd38d5 fix(engipy-backend): LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib
test-runner / smoke (push) Successful in 0s
После миграции на ONNX runtime старая path через nix-store
gcc-lib + openblas больше не нужна и вредит:
  1. nix-store libstdc++ + openblas конфликтовали с torch-internal
     OpenMP при SBERT forward (RuntimeError: could not create a
     primitive в GELU activation) — ранее приходилось ставить
     OMP_NUM_THREADS=1 чтобы torch не пытался multi-thread.
  2. После ONNX-миграции wheel-installed onnxruntime и numpy
     приносят свои bundled deps; тянуть ещё openblas поверх не нужно.

Системный nix-ld overrides directory (NixOS) лежит в фиксированном
пути /run/current-system/sw/share/nix-ld/lib и содержит симлинки
на 64-bit libstdc++.so.6, libz.so.1, libdl.so.2, libgcc_s.so.1,
libpthread.so.0, libc.so.6. Этого достаточно для wheels, и не
конфликтует с onnxruntime (тот поставляет свои OpenMP-библиотеки
внутри wheel).

Сабж: оставляю OMP_NUM_THREADS=1, OPENBLAS_NUM_THREADS=1,
TOKENIZERS_PARALLELISM=false. Убираю MKL_NUM_THREADS — onnxruntime
не использует MKL.

Проверено: через этот LD_LIBRARY_PATH numpy импортируется в
/var/lib/engipy/venv/bin/python на rydiwo, а ONNX inference
embed_gesn.py через ORTModelForFeatureExtraction
проходит (shape=(2,312) time=0.00s).
2026-10-16 17:28:15 +03:00
oqyude 12f6bfb0e1 fix(engipy-backend): LD_LIBRARY_PATH + OMP_NUM_THREADS=1
test-runner / smoke (push) Successful in 1s
Без LD_LIBRARY_PATH numpy падает 'Error importing numpy: you should
not try to import numpy from its source directory' (не находит
свой wheel-installed openblas без переменной). Возвращаю
LD_LIBRARY_PATH, но добавляю OMP_NUM_THREADS=1 MKL_NUM_THREADS=1
OPENBLAS_NUM_THREADS=1 и TOKENIZERS_PARALLELISM=false — это
отключает multi-thread BLAS, где SBERT forward падал в 'could
not create a primitive'. Inference пойдёт медленнее (~5 сек),
но не упадёт.
2026-10-16 14:26:40 +03:00
oqyude 61ebbf60ef fix(engipy-backend): убрать LD_LIBRARY_PATH openblas из env
test-runner / smoke (push) Successful in 1s
При POST /api/match SBERT forward pass через torch CPU падает с
RuntimeError: could not create a primitive на
transformers/activations.py:78 (GELU activation через BLAS).
Воспроизводимо на rydiwo с тем же Python/torch/openblas,
что работает локально.

Корневая причина — openblas lib из nix-store конфликтует с torch
internal threading. Переменная LD_LIBRARY_PATH=/nix/store/.../openblas/lib
+ libgcc.cc.cc.lib пробрасывалась мной как 'safety net' для других
wheel'ов (uvloop/scipy используют BLAS), но для torch это создаёт
конфликт (torch тащит свой mkl/openblas).

Без override torch берёт системный /lib/x86_64-linux-gnu/libgomp
и /lib/.../libopenblas (если установлен на системе). Если нет —
просто без OpenMP threading. SBERT inference должен идти медленнее
(без multi-thread MKL), но не падать.

Если после теста SBERT всё ещё падает — следующий вариант:
fastembed (ONNX-based, без torch) или optimum[onnx].
2026-10-16 14:25:03 +03:00
oqyude 4433e6e3ef fix(engipy-backend): uvicorn --factory app.main:create_app
test-runner / smoke (push) Successful in 1s
В app/main.py нет module-level 'app' — только create_app() функция-
фабрика (создаёт экземпляр FastAPI на каждый запуск). Без --factory
uvicorn ждёт 'app.main:app' (атрибут 'app' в модуле), не находит
его и завершается 'Attribute app not found in module app.main'.

smoke_api.sh в проекте использует именно '--factory app.main:create_app',
это рабочий паттерн для engipy — перенёс в systemd ExecStart.
2026-10-16 14:08:54 +03:00
oqyude 2d1ffa5aef fix(engipy-install): добавить python-multipart==0.0.20
test-runner / smoke (push) Successful in 1s
FastAPI route /api/match использует file: UploadFile = File(...). При
импорте app.routes.match (через 'import app.main') FastAPI вызывает
ensure_multipart_is_installed() и падает с RuntimeError, если
python-multipart не установлен. Добавил в requirements.txt.
2026-10-16 14:03:56 +03:00
oqyude ce4bfd3f0b fix(engipy-install): добавить structlog + pandas + openpyxl и PYTHONPATH
test-runner / smoke (push) Successful in 0s
1. structlog==24.4.0 — app/main.py импортирует его на boot, иначе
   ModuleNotFoundError стартует uvicorn. Аналогично pandas и
   openpyxl — app.matchers и app.routes.match их используют, и
   'import app.main' тянет всю иерархию.

2. PYTHONPATH=${cfg.dataDir} — WorkingDirectory не добавляет cwd в
   sys.path автоматически, uvicorn не находит 'app.main:app' при
   запуске из /var/lib/engipy. PYTHONPATH — это путь, который uvicorn
   ищет при import_from_string.
2026-10-16 13:54:45 +03:00
oqyude 424d918bb9 fix(engipy-install): включить torch в requirements.txt с --extra-index-url pytorch.org/whl/cpu
test-runner / smoke (push) Successful in 0s
Предыдущий подход ставил torch отдельным pip install -r torchReqs
ПОСЛЕ установки sentence-transformers. Но sentence-transformers
(через transformers/torch>=1.11.0) уже резолвил universal-torch
с PyPI при первой установке — это тянуло cuda-toolkit ~3GB.

Исправлено: torch==2.6.0+cpu + --extra-index-url pytorch.org/whl/cpu
включены прямо в requirements.txt. Sentence-transformers увидит
torch==2.6.0+cpu как явное ограничение и возьмёт именно CPU-wheel
(он единственный с +cpu тэгом, PyPI не предлагает).
2026-10-16 13:49:11 +03:00
oqyude c93a70c578 fix(engipy-backend): убрать environment.PATH из engipy.service — тоже конфликт с upstream NixOS systemd environment.
test-runner / smoke (push) Successful in 1s
2026-10-16 13:47:26 +03:00
oqyude b300b07456 fix(engipy-backend): убрать environment.PATH из engipy-install — конфликт с upstream NixOS systemd environment (PATH уже задан). Venv-скрипт работает по абсолютному пути.
test-runner / smoke (push) Successful in 1s
2026-10-16 13:46:29 +03:00
oqyude 716120eb82 fix(engipy-backend): переехать с fetchPypi на pip-venv через ExecStartPre
test-runner / smoke (push) Successful in 1s
pkgs.fetchPypi + python311.withPackages / buildEnv.override не
раскладывают wheels в site-packages — итоговый env содержит только
4 базовых файла python311 (__pycache__, README.txt, sitecustomize.py,
_sysconfigdata__). engipy.service стартует с 'No module named uvicorn'.

Перешёл на прямое pip install в systemd ExecStartPre:
  * engipy-install.service (oneshot) — создаёт /var/lib/engipy/venv,
    pip install -r requirements.txt, pip install torch (--index-url
    pytorch.org/whl/cpu). Маркер .engipy-venv-installed после успеха.
  * engipy.service (simple, requires engipy-install) — uvicorn из
    созданного venv.

Wheel'ы остаются те же (16 штук, ~1.7 GB на диске после распаковки),
но Nix больше не пытается интегрировать их в buildEnv — pip делает
это прямым образом за ~2-3 мин на rydiwo. Никаких часовых компиляций.

torch по-прежнему 2.6.0+cpu с https://download.pytorch.org/whl/cpu
(~250 MB). SBERT-модель 'cointegrated/rubert-tiny2' кэшируется при
первом запросе в cfg.dataDir/.cache/huggingface/ (~50 MB).
2026-10-16 13:45:34 +03:00
oqyude 276d3f4292 fix(engipy-backend): pkgs.fetchPypi + python311.withPackages
test-runner / smoke (push) Successful in 1s
python311.buildEnv уже derivation, не функция (правый attrset, не
lambda), поэтому python311.buildEnv { ... } падает с 'attempt to
call something which is not a function'. Аналогично pkgs.fetchPip
не существует — есть pkgs.fetchPypi (с 'y').

Исправлено:
  * requirements.nix: pkgs.fetchPip → pkgs.fetchPypi
  * engipy-backend.nix default: pkgs.python311.buildEnv →
    pkgs.python311.withPackages (ps: ...)

Сгенерировано в WSL nixos и подтверждено: 'nix-build' успешно
собирает /nix/store/...-python3-3.11.17-env (около 17 symlinks).
2026-10-16 13:38:30 +03:00