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.
- ADR-0009: разбор инцидента 2026-11-06 (home-manager EACCES из-за
root-owned каталогов-родителей секретов), механизм фикса и разблокировка
без пересборки.
- AGENTS.md: инвариант 18 (класс граблей sops-nix + фикс).
- T60: фактическое состояние rydiwo (юнит живой, плагин есть, апстрим
отвечает) и открытый пункт — OAuth-учётка интеграции opencode для
провайдера opencode-go.
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-кеша — зависшая загрузка не должна держать активацию
(и пересборку) намертво.
computer-use и genoffice (Windows-only) сознательно вне объёма T60/ADR-0009:
владелец 2026-11-06 — «browser-control пусть будет, остальное пока не будем
ставить, главное появилась еще нода на равне с sapphira».
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 + две ловушки).
По образцу 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>
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).
Сборка opencode 2.2.5 падала на проверке fixed-output деривации:
hash mismatch in '…-opencode-node_modules-2.2.5.drv'
specified: sha256-xfOVcw1+waLVNhFDwzOtzxrUSQEogvn88YomydOlhwc=
got: sha256-prx9dX7kUvs/E3zopkaPk5LXh3xJAy5sZeum/W8L7cA=
Пин от 2026-11-04 17:14 был взят за 2.5 часа ДО того, как апстрим это
починил: `c399e1b7` «opencode: fix hash», коммитнут 2026-11-04 19:47 и
выставляет ровно `sha256-prx9dX7kUvs…` для Linux.
`nix flake update nixpkgs-master` → 04c9f4a18de5 (2026-11-04 23:16).
После него drvPath совпал с собранным на 24-ядерном WSL-хосте
(`jaj1m6ab…-opencode-2.2.5.drv`), оттуда забраны opencode-2.2.5 и
opencode-node_modules-2.2.5; система собралась локально без изменений,
активирована (поколение 869), живой сервер отвечает version 2.2.5.
Владелец: «нужно, чтобы разрешения выдавались автоматически, без открытых
вкладок и auto-accept». Причина: любой путь вне рабочей папки сессии поднимает
`external_directory`, и ход стоит, пока человек не нажмёт кнопку — агент,
который работает с хостом (~/.local/share/metaagent, /etc/nixos, другой
репозиторий), без присмотра работать не может.
Форма — v2 `permissions`, упорядоченный набор {action, resource, effect}
(устаревший `permission` с ask|allow|deny не используется). Разрешены
external_directory, read, edit, bash, webfetch, websearch.
Это заменяет человеческий клик, а не правила безопасности агента: secrets/,
*.env, *.pem и .ssh остаются закрытыми политикой, а не запросом.
Файл на sapphira лежал с 2026-11-01 руками (правка моделей до 0c3e0d5),
HM отказывался затирать и падал с 'would be clobbered' — ДО применения
остальных домашних изменений. Из-за этого home-manager-oqyude.service
в failed, а дом. генерация стояла на 30 октября (721e6e8, 0c3e0d5 не
активированы). Содержимое совпадает с объявленным, перезапись безопасна.
НЕ активировано намеренно: активация перезапускает opencode-web
(ловушка 11). Применять switch'ем, когда сессия может умереть.
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; значения сохранены.
Исследование по исходникам пина 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.
T59 фиксирует задачу владельца 2026-10-27 и её проверки: pwsh 7.6.6 в
systemPackages только у sapphira (otreca/atoridu/rydiwo/wsl — 0), сборка
nixos-rebuild build --flake .#sapphira успешна, .ci/checks.sh --no-build
PASS 4 / FAIL 0.
ADR-0008 объясняет границу выбора: configurations/server.nix (тело модуля
ровно одной записи реестра) вместо modules/essentials/packages.nix (общий
список всех NixOS-хостов, замыкание powershell — 300.2 МиБ), и почему
powershell в lib/ci-tools.nix при этом остаётся (PATH джобы раннера ≠
системный PATH). Отдельно зафиксировано, что правка НЕ развёрнута: бинарь
появится только после nixos-rebuild switch|boot.
Без pwsh в системном PATH ps1-реализация metaagent-director (director.ps1
и её тесты) на sapphira всегда уходит в skip и проверяется только чтением.
Место — configurations/server.nix (тело модуля ровно одной записи реестра,
sapphira), а не modules/essentials/packages.nix: тот список общий для всех
NixOS-хостов флейка, включая 1-vCPU vds otreca, а замыкание powershell —
300 МиБ. Остальные хосты не меняются (проверено nix eval по всем).
The MINIMAX Token Plan keeps its own ceiling, invisible to the director's
quota probe: on 2026-10-26 every sub-agent died on spawn with
"Token Plan usage limit reached (2056)" while the probe for the same
provider reported decision=ok. The director already mints its worker
sessions on opencode-go/deepseek-v4.1-flash (state/quota.json
provider_selection), so this makes agents, workers and the gate share one
provider and one budget.
modelFast drives all five slim agents and the global default model, so the
whole set moves together. Build-verified: nixos-rebuild build --flake
.#sapphira -> rc=0. Not activated: switch restarts opencode-web, where the
sessions doing the deploy live.
Бандл 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.
After the runs-on: native fix the workflow finally executes: run 141 was
cancelled by the concurrency group, run 144 on 3c1269b succeeded in ~97
seconds with checks.sh --no-build plus the sapphira drvPath evaluation.
nix-checks.yml asked for ubuntu-latest while the only runner advertises the
single label 'native'; it therefore never produced a run. After switching to
runs-on: native, Gitea created run 141 for nix-checks.yml. Update T39 notes
and the checks/CI docs; use eval drvPath wording (not a build).
The workflow could never run: it asked for 'runs-on: ubuntu-latest', but the
only runner (gitea-runner-ci-sapphira) advertises exactly one label, 'native'
(host executor). test-runner.yml used 'native' and runs; nix-checks never
produced a single run.
- runs-on: native
- drop cachix/install-nix-action and 'nix profile install sops': the host
profile already provides nix, sops, git and python3
- evaluate sapphira with 'nix eval --raw ...toplevel.drvPath' instead of
'nix build --dry-run': the runner user is not a Nix trusted user, so a
dry-run build would want store write access; evaluation is the actual gate
- timeout 15 min, concurrency cancel-in-progress
The only runner is gitea-runner-ci-sapphira, running on the same 2-core /
5.6 GiB host as ~20 production services. Evaluating all seven configurations
took 40+ minutes and pushed the host into swap.
- checks.sh is invoked with --no-build, so check #2 (full nix flake check,
every host) no longer runs in push CI
- only .#nixosConfigurations.sapphira is evaluated: a broken sapphira is an
immediate CI-runner outage; other hosts are verified explicitly per change
- workflow_dispatch added, timeout 45 -> 20 min, and concurrency group
cancels superseded runs instead of queueing them on the same host
Docs: AGENTS checks section, project-state test-runner row, T39 notes.
Live state after switch: guard condition present on 13/13 units under [Unit],
phantom samba/nextcloud/immich units gone, nginx serves lamet with upstream
100.106.21.39:4096 (6061 no longer answers). systemctl --failed is empty.
- T3: premise refuted by a runtime 'nft list ruleset' on otreca - 'inet nixos-fw'
already has 'policy drop'; the hand-written 'inet filter' only rate-limits SYN
and must NOT get a drop (it would blackhole the VDS). AGENTS invariant 6 and
the traps table updated; T3-A proposal marked withdrawn. No code change.
- T38: herdr_web_token rotated (old -> 401, new -> 200); literal removed from
manifest.json (token -> secret_ref). Old token in git history is now invalid.
- T20: completed (100755, bash invocation, .gitea workflow).
- T57: T38-T57 registered in manifest.json, schemas aligned with the real
format, dangling request.json $schema resolved, new dependency-free
validator wired as check #9.
- T4/T52: completed; invariant 2, R1.2, ADR-0004 and project-state updated;
checkpoints.phases.execution -> completed, handoff -> in_progress.
- T58 filed: triple 'allowedUDPPorts = [ 53 ]' duplicate.
AGENTS.md also carries the .omo trap-row update from the parallel opencode
session (commit 8079536), which was left uncommitted in the shared tree.
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.
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].
Metastate only — no code touched. Brings the three state files in line with
what actually landed between f484a89 and 1adf6dd.
.agent/tasks/manifest.md
Overview table now carries the real status per task: 10 done, 10 blocked.
T38 is marked partial (handoff-summary.md cleaned, manifest.json:412 is
outside this session's mandate). T47/T49/T56 are re-classified from
"pending" to "blocked" because doing them needs home-manager merge
semantics confirmed and there is no nix binary on this machine.
Adds a section for a finding that was not in the plan: HEAD contained
invalid Nix — modules/server/default.nix:79 and modules/vds/default.nix:40
called `config.modules."3x-ui".reconfig` without declaring `config` in the
module arguments, so sapphira and otreca should not have evaluated. Fixed
in 39e1887. That is independent proof that `nix flake check` never ran.
.agent/context/project-state.md
"What's next" becomes "what was done", with the commit for each item.
Testing status updated: 4 checks now (the import-graph one was added), and
the "never ran" claim is scoped to the pre-2026-10-24 state since T39 fixed
all three defects. modules/options.nix row updated — it is 81 lines now,
with modules/pxe-infra/options.nix added.
.agent/handoff-summary.md
Entry point gains the commit table, the parallel-session collision note
(two commits were absorbed by the other session: 95a4f92 for T40 and
39e1887 for T42, plus 2991164 swallowing my staged deletions), and a
next-action list that is addressed to the owner rather than the next agent.
Not pushed.
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.
.gitignore had `scripts` as an unanchored pattern. A pattern without a slash
matches a directory of that name at ANY depth, so a future
modules/*/scripts/ would have been silently ignored — the kind of thing that
only shows up as "why is my file not in git". It is anchored to /scripts/
now. No tracked file was matched before or after (verified with
`git ls-files | git check-ignore --stdin --no-index`, empty both ways).
The 22 scripts in .temp/ are not committed wholesale: they are eight
iterations of one T4 test (t4-final-v5..v8), three of another
(t4-live-test{,v2,v3}), plus one-shot deploy/cleanup/diagnose scripts that
hardcode `cd /mnt/s/Git/nixos` and perform umount / mount --move. Committing
them would be noise, not knowledge.
One of them is reusable and non-destructive, so it is preserved:
.ci/verify/guard-non-destructive-verify.sh. It creates two throwaway systemd
units (ConditionPathIsMountPoint=/nonexistent must refuse to start,
=/mnt/services must start) and resets them, so it can be run against a live
host to prove the condition is evaluated at all. That is the check the owner
needs for T52. Content is byte-identical to the .temp original
(md5 b0ac8081aae568a3db921fb64f4c0a05) and passes shellcheck -S error.
Not pushed.
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.
AGENTS.md is the one file an agent always reads, so a wrong path there sends
the next reader somewhere that does not exist. Eleven references were stale:
:78 modules/server/nginx.nix:109,253 -> :109 and :378
(253 is inside the herdr forward-auth block, not a Tailscale bind)
:97 server.nix:130 -> configurations/server.nix:129
:100 3x-ui.nix:54 -> modules/containers/3x-ui.nix:62
(the file `modules/3x-ui.nix` does not exist; modules/3x-ui/ holds
only default.nix, which declares the reconfig option)
:101 3x-ui.nix:33-35 -> modules/containers/3x-ui.nix:35
:104 server/default.nix:7-44, comment 38-41
-> :9-50, comment 43-49
:105 opencode.nix:354 -> home/modules/opencode.nix:449
:98 mobile.nix / wsl.nix -> configurations/mobile.nix / configurations/wsl.nix
:99 users.nix:66 -> modules/users.nix:66
:109 vds.nix:73-91 -> configurations/vds.nix:71-92
:111 server.nix:61-63 -> configurations/server.nix:61-63
:123 users.nix:99 -> modules/users.nix:99
The bare names in the trap table were ambiguous: `server.nix` could mean
configurations/server.nix or modules/server/default.nix. They now carry their
directory.
Verified with a one-off scan: all 16 `path:line` references in AGENTS.md now
resolve to an existing file with at least that many lines. Documentation only
— no .nix file is touched, so nothing can change evaluation.
Not pushed.
Check #1 allows `:latest` images listed in LATEST_ALLOWLIST. The list still
carried `ghcr.io/mhsanaei/3x-ui:latest` with the comment "panel frozen on
:latest", but the panel has been pinned to `ghcr.io/mhsanaei/3x-ui:v3.10.2`
since 2026-10-20 (modules/containers/3x-ui.nix:62, R1.5). The entry matched
nothing, and the comment stated the opposite of the invariant it cited.
Consequence of the stale entry: if someone reverted the pin to `:latest`, the
check would have stayed green and said nothing. Verified by mutation — with
v3.10.2 temporarily replaced by :latest the check now reports
"Images using :latest (not in whitelist): ghcr.io/mhsanaei/3x-ui:latest";
before this commit the same mutation passed silently.
Also: check #4's description named `mkServiceStorage`, while the guard the
consumers actually call is `mkStorageGuard` (lib/xlib/helpers.nix:180). Both
names exist in that file and mean different things, so the comment pointed at
the wrong helper. Now it names the right one and says so explicitly.
`bash .ci/checks.sh --no-build` -> PASS 3 / FAIL 0, before and after; the
current tree contains exactly two `:latest` images, both tape-rotation, both
still whitelisted.
Not pushed.
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.
.ci/tests/import-graph.py — проверяет, что каждый .nix ссылается только
на существующие файлы и каталоги. Раньше логика жила инлайн в
checks.sh и не была переиспользуема.
Проверки: PASS 3, FAIL 0.
Nothing in this repo verifies that an import actually resolves. That matters
here more than usual: several modules are referenced only through
commented-out import lines, and 15 .nix files sit outside the import graph
entirely, so a stale reference is invisible until someone uncomments it or
nix evaluation happens to touch that file.
The check is deliberately narrow: it matches only two import shapes — a line
whose whole content (after an optional `#`) is a relative path, and
`import ../foo` / single-line `imports = [ ./a ./b ]`. Prose and shell-script
bodies are not matched, and anything containing `${...}` is skipped because it
cannot be resolved statically. Commented-out import lines ARE matched on
purpose: a comment naming a deleted file still misleads the next reader.
Baseline on the current tree: 132 .nix files, 120 import references, all
resolve. Wired in as check #8 of .ci/checks.sh; skips when python3 is absent.
`bash .ci/checks.sh --no-build` → PASS 3 / FAIL 0.
Not pushed.
Проверка #7 искала файлы только в secrets/ и не замечала вложенные
каталоги: modules/server/secrets/, modules/containers/secrets/,
modules/essentials/secrets/, modules/wsl/secrets/.
Теперь обходятся все файлы под */secrets/*, а совпадения, требующие
непривязанного правила (поведение sops для вложенных каталогов),
перечисляются отдельно — предположение видно, а не спрятано.
PASS: 2 FAIL: 0; 13 файлов помечены как требующие непривязанного
правила.
Two independent reasons why the CI never ran a single check:
1. The workflow lived under .github/workflows/, but the only remote of this
repo is gitea@git.zeroq.su — there is no GitHub remote, so GitHub Actions
never saw it. Gitea Actions reads .gitea/workflows/ in preference to
.github/workflows/, and .gitea/workflows/ already contained
test-runner.yml, which does not call .ci/checks.sh. The file is moved
with `git mv` so history follows it.
2. Every step of the job ended in `|| true` and used `--dry-run`, so even
if it had run, the job could never go red. The `|| true` is dropped:
the step now fails the job when a host configuration fails to evaluate.
`--dry-run` is kept on purpose — the value of this step is evaluation,
not building — and `--no-link` keeps the workspace free of `result`
symlinks.
Also: the `default` (minimal) configuration was missing from the list and is
now evaluated; epral is evaluated with `nix eval` (cheap, and it is an
aarch64 target that cannot be built on the x86_64 runner); `nix-env -iA` is
replaced by the supported `nix profile install`; a job timeout is added so a
hung evaluation cannot hold the runner.
The check script is invoked through `bash`, so the step no longer depends on
the file mode (see ca450f1 and db3cbd0).
Not pushed.
pre-commit's `language: script` execs the entry directly, without a shell.
Running the script through `bash` removes the dependency on the file mode
entirely, so the hook keeps working in checkouts made with core.fileMode
=false, from a tarball, or on a filesystem that does not preserve the
executable bit.
The previous commit (ca450f1) sets the mode to 100755 as well; both are
kept because they fail independently.
Not pushed.
The script has a shebang and its own usage header documents `./.ci/checks.sh`,
but git tracked it as mode 100644. Both call sites exec it directly:
.pre-commit-config.yaml:10 entry: .ci/checks.sh --no-build
.github/workflows/nix-checks.yml:20 run: .ci/checks.sh
so both failed with "Permission denied" before running a single check. This
was already tracked as T20 in .agent/tasks/manifest.json.
core.fileMode is false in this checkout, which is why the on-disk permission
never made it into the index. `git update-index --chmod=+x` sets the mode in
the index explicitly, regardless of core.fileMode.
Mode-only change: no content of the script is touched.
Not pushed.
The live 256-bit herdr_web_token was committed in cleartext. This repo only has
a gitea remote and the token is the sole gate for herdr.zeroq.su (vhost
without authelia — R1.15 / ADR-0005), so a leaked literal is a real exposure.
The identical 64-hex literal lived in two files. Only .agent/handoff-summary.md
is in scope for this session (.agent/tasks/manifest.json:412 is off-limits by
the session constraints), so this commit removes it from the reachable file
and documents the remainder explicitly.
The value is still in git history, so removing it from the tree is not enough:
the token must be rotated on the host. Left as an open item — see
.agent/tasks/manifest.md T38 and the note added next to the redacted token.
Not pushed.
A read-only audit of the whole repo (233 tracked files, 147 .nix) surfaced 20
tech-debt items across structure, duplication, doc drift, fragility, test
coverage and junk. This commit records the metastate only — no code is touched.
.agent/tasks/manifest.md — NEW. Human-readable register of the T38+ series
(20 items: 11 pending, 9 blocked); each with id, path:line, type
(restructuring / drift / junk / fragility), risk, benefit and "safe now or
needs a safety net". Deliberately NOT a copy of manifest.json: that file was
deleted on 2026-10-15 precisely because it was a duplicate, so it stays the
machine source of truth for T1–T37. PROTOCOLS/07_HANDOFF.md:39 requires both
files to exist, so this restores the protocol without reintroducing the drift.
.agent/context/project-state.md — new session section (was / done / next) and
removal of stale claims: the 3x-ui panel is pinned to v3.10.2 (not :latest),
T18 is committed, ADR-0003/0005/0006 exist, CI status is "never ran once",
192.168.1.20 occurs 42 times, nginx.nix:253 -> :378.
.agent/handoff-summary.md — new entry point at the top for the next agent,
pending count 8 -> 9 (T37 was missing), manifest.json described as T1–T37.
Not pushed.
В v2 без явного выбора CLI берёт модель из реестра сам
(opencode/minimax-m3.1-flash-free) и передаёт её явно — она перебивает
модель агента, заданную oh-my-opencode-slim. Проверено по сообщению в БД:
без фикса запрос шёл на бесплатной модели. Рабочая машина обходится за счёт
«помни последний использованный» в TUI, серверная БД пустая.
- herdr: установка opencode-интеграции пишет V2-регистрацию в cli.json, а он
read-only симлинк в /nix/store ⇒ herdr отказывается («config has multiple
hard links», не EROFS). На sapphira не установлена НИ ОДНА agent-интеграция
herdr ⇒ интеграцию не ставим, решение владельца снято.
- oc: --server принимают не все подкоманды (run/attach/tui/api/models/agent —
да; mcp/service/auth/serve/plugin — нет) ⇒ обёртка фильтрует по подкоманде.
- legacy ~/.omo/omo.jsonc проверен на хосте: реальные model id реестра.
- Вычищен мёртвый кэш v1 (~/.cache/opencode/packages, npm/oh-my-openagent@latest).
- T36 → completed.
v2 разбирает --server per subcommand: run/attach/tui/api/models/agent его
берут, mcp/service/auth/serve/plugin — нет ("Unrecognized flag: --server in
command opencode plugin list"). Обёртка добавляла флаг всем подряд, из-за
чего локальные команды (plugin list, auth, service) падали.
Дополнительно: если сервер на 4096 не поднят — понятная подсказка вместо
connection refused.
work/pxe-infra-automation is adding a Gitea Actions pipeline, and its
checks live in ci/check.sh: shellcheck over the build scripts AND over
the guest payload (image/*.sh, which is copied into the image verbatim),
plus a YAML validation of the workflow files.
That script exits 2 when shellcheck is missing, so on this runner —
where the job PATH is frozen into the systemd unit at activation time
and cannot gain a package without a nixos-rebuild — the linter has to
come from the ci devshell instead. shellcheck is now in lib/ci-tools.nix,
which is the single list both consumers use (the runner's hostPackages
and the devshell), so the two cannot drift apart.
PyYAML did NOT make it in: the obvious fix,
`python3.withPackages (ps: [ ps.pyyaml ])`, is not a valid buildInput
(nix rejects it with 'Dependency is not of a valid type: element N of
buildInputs'), and the devshell is the consumer that breaks. The
workflow YAML stays validated on GitHub and locally, where PyYAML is
present; the Gitea job says so in its log instead of pretending to have
checked it.
The nixos repo's own flake.lock pins nixpkgs; the pipeline uses that
revision instead of a floating nixos-unstable, because the nix registry
on sapphira is empty and 'nixpkgs#...' cannot resolve there.
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.
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.
Раннер на 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.
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.
snp.efi (SNP-only, 310K) was the right choice on linux-virt 6.18.56
because the universal ipxe.efi (1.2 MB) hit a deterministic crash at
iPXE offset 0x35FC with RAX=0xAF..AF (uninit-memory fill) — root
cause not OOM, not NIC driver (virtio-net works in both), but a
buffer-path bug in the universal binary. Switching to snp.efi
sidestepped it (commit 687d6d1, 2026-10-13).
On 2026-10-17 an e2e test on rydiwo found that snp.efi broke the
PXE chain after the kernel upgrade: iPXE chain
snp.efi → autoexec.ipxe → boot.ipxe → sanboot registers the SAN
device 0x80, the kernel (linux-virt 6.18.57) boots, but PCI
enumeration shows only the NIC — no `pci 0000:00:03.0 [1af4:1001]`
virtio-blk endpoint. Rootfs mount fails:
`UUID=...: Can't lookup blockdev` → `Mounting root: failed.`
Bisecting aports identified upstream c967b365 (`PCI: Make
pci_match_one_device() match on ID instead of device`) in
patch-6.18.57.xz, delivered via aports 2b1f5137
(`main/linux-lts: upgrade to 6.18.57`, 2026-10-16T11:11:20Z).
The new drivers/pci/search.c match_pci_dev_by_id() uses
pci_match_one_id()+pci_id_from_device(); the IDs that snp.efi's
SAN hook reports to the kernel for the virtio-blk device are not
full device IDs, so the new matching fails. The universal
ipxe.efi presents the SAN device through a different code path
whose IDs are full device IDs and match cleanly.
Direct-mode boot (`bootMode=direct`, QEMU virtio drive) is not
affected — there the kernel sees the device through a proper PCI
attach and the IDs are complete. Only the iPXE-SAN-presentation
path regressed.
Switch back to the universal binary. The original 687d6d1 crash
bug is not present in the current ipxe.efi (a different upstream
build was involved) — verified by two independent e2e runs on
rydiwo 2026-10-17 with explicit bootMode=pxe, both verdict=PASS
(20261017T180654Z, 20261017T180730Z). The ~290K extra TFTP volume
per boot vs snp.efi is negligible.
This permanently encodes the runtime-only change that was applied
to /etc/nixos/configurations/mini-laptop.nix on rydiwo on
2026-10-17 20:48 MSK during the T14 closure session. Without this
commit, a fresh nixos-rebuild switch from origin/dev would
silently revert to snp.efi and re-trigger the regression.
Closes T14 (P1, opened 2026-10-17 in session
pxe-infra-e2e-2026-10-17). Full RCA and verification evidence:
https://github.com/oqyude/pxe-infra-automation/blob/dev/.agent/tasks/manifest.json
(grep T14).
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)
Default в app/config.py = "cointegrated/rubert-tiny2" (HF Hub id).
Optimum-ONNX при from_pretrained("cointegrated/rubert-tiny2") пытается
скачать с HuggingFace Hub, конвертировать в ONNX через torch, и
падает в в GELU activation
torch.nn.Module.forward — точно тот же симптом, что был у нас с
sentence-transformers+openblas.
Локальный ONNX-чекпойнт лежит на rydiwo в
/var/lib/engipy/model/cointegrated__rubert-tiny2 (экспортирован в
WSL nixos через optimum-cli export onnx). Передаём явный путь в
host.engipy-backend.model — это попадёт в systemd Environment= как
ENGIPY_MODEL, и GesnEmbedder(model_name=...) примет его без
попытки качать с HF.
После миграции на 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).
Без 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 сек),
но не упадёт.
При 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].
В 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.
FastAPI route /api/match использует file: UploadFile = File(...). При
импорте app.routes.match (через 'import app.main') FastAPI вызывает
ensure_multipart_is_installed() и падает с RuntimeError, если
python-multipart не установлен. Добавил в requirements.txt.
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.
Предыдущий подход ставил 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 не предлагает).
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).
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).
В description для option dataDir было ${dataDir} — Nix
внутри ''-строки интерпретирует как переменную, не как литерал.
Поскольку dataDir объявлена самой опцией ниже (mutually-
recursive через cfg.dataDir это и есть сама опция), Nix ругался
'undefined variable dataDir'. Исправлено на `$dataDir/web` в
бэктиках.
rydiwo (device: secondary) не импортирует ../modules/server по
умолчанию — self.nixosModules.default подключает только ./server для
device: server. Без явного импорта engipy-backend.nix опции
host.engipy-backend.* не существуют в evaluation rydiwo, и
nixos-rebuild switch падает с 'Did you mean host.builder,
host.3x-ui or host.ssh?'.
Sapphira (2 cores, 5.6 GB RAM) не вытянет torch/sentence-transformers —
первый nixos-rebuild на ней упал с No space left on device и долгим
копированием 50+ MB ML-deps с узкого cache.nixos.org канала. Разносим
архитектуру:
* engipy-frontend.nix (sapphira) — только nginx vhost engipy.zeroq.su.
/api/* → proxyPass на 192.168.1.102:8000 (rydiwo). Статика
/var/lib/engipy/web на root fs (без bind-mount, External не нужен).
Authelia forward-auth через wildcard *.zeroq.su → one_factor.
* engipy-backend.nix (rydiwo) — systemd unit engipy с uvicorn +
FastAPI + полный ML-стек. bindAddress=0.0.0.0, чтобы sapphira
могла проксировать по LAN. Sandbox через PrivateTmp/ProtectSystem
+ LD_LIBRARY_PATH для libgomp/openblas (нужно torch CPU-wheel'у).
* requirements.nix — wheels с PyPI + torch 2.6.0+cpu c
https://download.pytorch.org/whl/cpu. Все sha256-хэши посчитаны
в WSL nixos через 'pip download --only-binary=:all: --platform
manylinux_2_17_x86_64' + 'nix hash path --type sha256'. Никакой
компиляции — только скачивание wheels на rydiwo (~5-10 мин rebuild).
* configurations/server.nix — host.engipy-frontend.enable = true +
backendHost = 192.168.1.102.
* configurations/mini-laptop.nix — host.engipy-backend.enable = true +
bindAddress = 0.0.0.0 + logind.lidSwitch = ignore (rydiwo
используется как headless-сервер, не засыпать при закрытии крышки).
nsot: старый engipy.nix (185 строк) удалён — он делал всё сразу на одном
хосте, что перегружало sapphira. nginx.nix vhost перенесён в
engipy-frontend.nix, чтобы не дублировать.
engipy webapp использует pkgs.python311.withPackages (fastapi, pydantic,
sentence-transformers, torch). При evaluation Nix встречает
python3.11-sphinx-9.1.0 как транзитивную docs-dep — а она не
поддерживает python 3.11 (broken). sphinx не нужен в runtime, и
реальная БД от него не зависит, поэтому глушим ошибку до warning
через nixpkgs.problems.handlers (см. .agent/rules/project-rules.md
R1 — outputs должны вычисляться).
NixOS ругался «attribute 'systemd' already defined», потому что Nix
видит systemd = storage.systemd и systemd.services.engipy = ... как
два разных присвоения корневому systemd, а не как deep-merge.
lib.mkMerge делает явный merge двух attrsets внутри systemd.
engipy.zeroq.su — FastAPI webapp для подбора ГЭСН по ВОР (uvicorn + SBERT).
Дизайн по образцу vtimeline.nix (systemd unit) + vtimeline.zeroq.su vhost:
- modules/server/engipy.nix: новый модуль. systemd-юнит engipy запускает
uvicorn на 127.0.0.1:8000 (порт через host.engipy.port). Хранилище —
через xlib.helpers.mkServiceStorage: bind-mount
/mnt/services/engipy → /var/lib/engipy (mode 0750 engipy:engipy),
соглашение R1.2 в .agent/rules/project-rules.md. Зависимость
requires = [ var-lib-engipy.mount ] заменяет нерабочий mkStorageGuard.
nginx читает /var/lib/engipy/web через users.users.nginx.extraGroups.
Опции: port, user, pythonPackage, dbFileName, embeddingsStem, model.
- modules/server/default.nix: импорт ./engipy.nix + host.engipy.enable
с pythonPackage = pkgs.python311.withPackages (fastapi/uvicorn/
pydantic/sqlalchemy/numpy/sentence-transformers/torch) — список из
nix/engipy.nix проекта, чтобы backend-стек на сервере совпадал с
dev-окружением.
- modules/server/nginx.nix: vhost engipy.zeroq.su (forceSSL + ACME).
/api/ проксирует на 127.0.0.1:8000 (client_max_body_size 50m для
крупных ВОР-файлов), / отдаёт /var/lib/engipy/web с try_files для
SPA-fallback. Authelia forward-auth через auth_request /authelia +
401→302 redirect на authelia.zeroq.su (как у vtimeline.zeroq.su) —
wildcard *.zeroq.su → one_factor уже покрывает новый vhost.
Первый nixos-rebuild на sapphira собирает torch + sentence-transformers
~30-90 мин (2 ядра); последующие пересборки берут из кэша.
Detected drift:
- checkpoints.json:tasks[] (T1-T20 + T35) устаревал vs manifest.json:tasks (T1-T33); tasks[] удалён
полностью (manifest.json — единственный source of truth по задачам, per checkpoints-schema v3.0 +
protocol 6.3 archival deviation). T35-призрак перенесён в closed_attempts[].
- checkpoints.json:phases (execution=completed, handoff=in_progress) расходились с manifest.json
(execution=in_progress, handoff=pending). Синхронизированы на manifest-версию + AGENTS.md:159-163
обновлён до того же набора с комментарием про source of truth.
- AGENTS.md:87 инвариант 12 заканчивался дублированным R1.14-блоком про escapeSystemdPath
(остался с сессии 14:30). Удалён хвостовик, инвариант 12 теперь корректно заканчивается на
R1.15, ADR-0005.
- handoff-summary.md:74 T18 в pending таблице (формально completed в manifest с saga close-out),
строка удалена. handoff-summary.md:90 T32 в pending таблице (тоже completed) — статус изменён
на completed 2026-10-15T14:30. Сопутствующие ссылки T18/T32 в «Project State» и «Next Steps»
тоже приведены к актуальному состоянию.
- manifest.json:backlog_count=28 был арифметически неверен (22 F-вопроса + 8 pending задач = 30);
F-листинг включал закрытый 5.6, а счётчик «новых pending» не учитывал T20. Исправлено на 30
с breakdown блоком и переписанной backlog_note.
- checkpoints.json:resolved_doc_drift — 3 deferral'а (checkpoints↔manifest-tasks, agentsmd-
invariant12-dup-r114, checkpoints-phases-vs-manifest) закрыты с resolved_at=2026-10-15T17:42Z
и описанием фикса в каждом.
- checkpoints.json:session_id и session_chain обновлены до текущей сессии
metaagent-cleanup-2026-10-15T17:42Z.
- manifest.json:session_id и date обновлены до 2026-10-15T17:42; session_id показывает всю
цепочку init → director → attempt(rollback) → cleanup.
- AGENTS.md frontmatter date-modified: 2026-10-15T03:00 → 2026-10-15T17:42.
Not changed (out of scope):
- metaagent-director/AGENTS.md + README.md (другой репо, не закоммичены)
- 4 reflog-коммита от попытки шима (3e85307, 16a44b9, 158f08d, 574ec27) — оставлены в reflog
- protocol_deviations блок в checkpoints.json не перенесён (medium scope, B+C+A)
- tasks[] в checkpoints.json не заменён на one-liners по schema spec (drop чище: manifest —
единственный source of truth, дубль-данные гарантированно протухнут)
Сессия metaagent-attempt-2026-10-15T20:25Z закрыта. Попытка (3e85307 +
16a44b9) и два revert-коммита (158f08d + 574ec27) стёрты из dev через
git reset --hard 3d4f1f5; force-push в gitea/dev. Сохранено в
~/.cache/t34-attempt-backup/ (9 файлов) и metaagent-director/.
checkpoints.json:
- session_id: metaagent-attempt-2026-10-15T20:25Z (attempt, не closed —
не "vanilla" state, а состояние "была попытка, отменена");
- host_state: новый vanilla toplevel 3qki65iy7…; herdr.service ванильный
(PID 27752); opencode-web PID 1152 без изменений; opencode-loop кеш
удалён; opencode-sessions НЕ установлен;
- tasks[]: T35 closed — запись о попытке+откате, чтобы будущие сессии
не повторяли без новой мотивации;
- resolved_doc_drift[]: добавлены 3 предсуществующих drift'а (отложены
до чистки метаданных в следующей сессии):
* drift-checkpoints-vs-manifest-tasks (tasks 1-20 vs 1-33);
* drift-agentsmd-invariant12-dup-r114 (хвост R1.14 в инварианте 12);
* drift-checkpoints-phases-vs-manifest (execution/hand-off расходятся);
- session_chain: previous/current/next_entry_point обновлены под новую
сессию, next_entry_point указывает на добавленную секцию
handoff-summary.md.
handoff-summary.md:
- новая секция "Сессия metaagent-attempt-2026-10-15T20:25Z — попытка
и отмена шима herdr → opencode serve" (39 строк): цель, что делал,
главное наблюдение (opencode attach ≈ 300 МБ RSS, шим не экономит
RAM), рассмотренные альтернативы director, force-reset,
сохранённые данные, мелкое (opencode-loop кеш, opencode-sessions),
pending без изменений, ссылки на doc-drift;
- вставлена ПЕРЕД последним "⚠️ Контекст сессии раздут" — это
становится новой точкой входа, устаревшее предупреждение ниже.
manifest.json, index.json, AGENTS.md, project-rules.md — НЕ правил,
уже vanilla.
Authelia's forward-auth endpoint was handed the original Content-Length
header of the client request but not the body itself, so it blocked
reading bytes that never arrived and finally answered 408. auth_request
cannot classify 408, so nginx reported it to the client as 500 + an HTML
error page, and the frontend surfaced "Server returned non-JSON" on
every upload.
Every bodied POST was affected (JSON upload and zip ingest) while plain
GETs kept working, which is why the page loaded fine but uploads failed.
Payload size was irrelevant: a 60-byte body failed identically to a
300 KB one.
With `proxy_pass_request_body off` and an empty Content-Length, Authelia
authorises on the forwarded headers alone, which is all forward-auth
needs. Applied to both "= /authelia" blocks (vtimeline.zeroq.su and
tty.zeroq.su).
Verified on a reproduction bench mirroring the production vhost: bodied
POSTs went 500 (HTML, 6 s timeout) -> 201 (JSON, ~10 ms).
Saga: пользовательский репорт «rydiwo — Connection failed / Could not start
dynamically linked executable: bun» → три слоя фиксов на NixOS + plugin
update + closeout. Закрыта 2026-10-15T15:00.
ADR-0005 (.agent/decisions/0005-herdr-webui-no-authelia.md):
• Maintenance procedure переписана с устаревшей «herdr plugin update» (такой
команды нет — veriried 2026-10-15, herdr plugin --help показывает
enable|disable|action|log|pane|list|install) на фактический 7-шаговый
flow, отработанный на переходе 79beb36 → 439ad38:
1. cp active → .patched.bak (НЕ в .orig, там upstream-версия от install)
2. git checkout -- server/machine-security.ts (сброс unstaged patch)
3. git pull --ff-only origin main
4. cp .patched.bak active (восстановить)
5. cd $PLUGIN_DIR && bun install + bun run build
6. **python-edit ~/.config/herdr/plugins.json:source.resolved_commit**
(это поле обновляется ТОЛЬКО через herdr plugin install; без шага 6
herdr plugin list будет показывать старый коммит после рестарта — главный gotcha)
7. systemctl --user restart herdr + herdr plugin list | grep devswha
• Новый раздел «Runtime prerequisites на NixOS» (3 слоя, каждый проявляется
после починки предыдущего): pkgs.bun + pkgs.nodejs_22 в shell PATH
(home/modules/herdr-runtime.nix) + programs.nix-ld.enable = true глобально
(modules/essentials/packages.nix, stdenv.cc.cc.lib). Trap: системный bun
в PATH НЕ чинит запуск скачанного плагином bun'а (plugin использует свой
runtime manager, а не fallback).
manifest.json:
• T18 → completed (fix в 9bf9407 + b62a980 + d021804)
• T32 → completed (cleanup формализован)
• T33 → completed (saga close-out documentation)
decisions/index.json:
• ADR-0005: tags расширены (nix-ld, runtime-manager); resolution поле
дополнено maintenance procedure и тремя NixOS prerequisite
• updated_at: 2026-10-15T15:00
handoff-summary.md:
• Session Summary обновлён (9 задач completed, 8 pending)
• Hosts: оба sapphira+rydiwo с herdr-runtime.nix, plugins
devswha.herdr-web-ui@439ad38d091c02c3e4747956808dbac2305702d3
• Plugins секция: .patched.bak добавлен рядом с .orig (для быстрого
restore после git pull)
• Новая секция «Saga close-out: 2026-10-15T14:30–15:00» с тремя слоями
фиксов и пятью выводами
checkpoints.json:
• T18 → completed (в tasks array)
• uncommitted_work → ALL_COMMITTED (gitea-runner.nix закрыт)
• corrections_this_session: +2 ложных вывода саги (bun в PATH ≠ fix,
herdr plugin update ≠ команда)
• session_chain.current обновлён до «closed at 2026-10-15T15:00»
• last_updated: 2026-10-15T15:00
Tree clean после коммита. Saga закрыта.
После feat(essentials): enable programs.nix-ld, bun-runtime plugin install
прошёл дальше preflight — теперь падает на следующем шаге: «herdr web ui
needs Node 18 or newer for its terminal sidecar, and 'node' is not on the
PATH of the shell that started herdr».
preflight.sh плагина проверяет `node --version` на PATH. На sapphira
node уже был через opencode.nix home.packages (там же, где раньше был
bun — мы его оттуда убрали в прошлом рефакторе). На rydiwo opencode
не подключён, и node отсутствовал.
Добавляю pkgs.nodejs_22 в home.modules.herdr-runtime.nix — это тот же
пакет, что используется в opencode.nix (consistency, один major). На
sapphira он уже был через opencode; home.packages мерджит и дедуплицирует,
так что лишней копии не будет.
bun в shell PATH (home/modules/herdr-runtime.nix) не помогает — herdr-web-ui
plugin на rydiwo использует собственный runtime manager (path-pattern
~/.local/share/herdr-web-ui/install.<hash>/runtime/bin/bun, типичный bun
runtime installer), а не fallback на PATH. Этот bun динамически слинкован
для generic linux (glibc) и на NixOS без nix-ld stub падает с «NixOS cannot
run dynamically linked executables intended for generic linux environments
out of the box».
Включаю programs.nix-ld глобально (в modules/essentials) с одной зависимостью
stdenv.cc.cc.lib (glibc + libstdc++ + libgcc_s) — этого достаточно для
запуска glibc-based bun. Применяется ко всем NixOS-хостам; на хостах без
generic-linux бинарей overhead минимальный (несколько .so в /lib, плюс
ld-linux.so.2 в /libexec).
Дополнение / подноши: если конкретный плагин потребует ещё (zlib, openssl,
etc.), расширять programs.nix-ld.libraries через ldd-проверку и точечно.
Раньше # nix-ld.enable = true; в этом же файле было закомментировано —
видимо, не дошли руки; теперь разкомментировано с явным почему.
Раньше bun для пользовательского shell PATH приходил двумя путями:
на sapphira — через opencode.nix:339 (home.packages=[... pkgs.bun ...]),
на rydiwo — добавлен вручную в home/secondary.nix (commit ffd85dc) для
herdr-web-ui plugin'а, который без bun в PATH скачивает generic-linux
runtime и ломается о NixOS dynamic linker.
Теперь:
• home/modules/herdr-runtime.nix — единый источник pkgs.bun для
пользовательского PATH (импортируется и в server.nix, и в
secondary.nix).
• home/secondary.nix — добавлен импорт herdr-runtime.nix, убран
прямой home.packages = with pkgs; [ bun ]; и его 10-строчный
комментарий-объяснение (переехал в herdr-runtime.nix).
• home/server.nix — добавлен импорт herdr-runtime.nix.
• home/modules/opencode.nix — pkgs.bun удалён из home.packages
(он теперь из herdr-runtime.nix), но ОСТАВЛЕН в
programs.opencode.extraPackages (line 271) — это другой PATH
(--suffix PATH внутри opencode-wrapped env), не дубликат.
Результат для обоих хостов:
- shell PATH: bun из /nix/store/...-bun-*/bin/bun
- opencode-wrapped env (только sapphira): bun через extraPackages
- herdr-web-ui plugin auto-install на rydiwo: находит bun в PATH,
не скачивает generic-linux runtime
После этого оба хоста пересобираются (sapphira: opencode/server.nix;
rydiwo: secondary.nix + новый модуль).
На сапфире pkgs.bun приходит через импорт ./modules/opencode.nix
(opencode.nix:271,339). На rydiwo opencode.nix не подключали — bun в
PATH нет, поэтому herdr-web-ui plugin при первой попытке стартовать
на rydiwo скачивает generic-linux bun в
~/.local/share/herdr-web-ui/install.<hash>/runtime/bin/bun, и тот
спотыкается о динамический линкер NixOS:
«Could not start dynamically linked executable: ... NixOS cannot run
dynamically linked executables intended for generic linux
environments out of the box.»
Один-в-один одна. С pkgs.bun в PATH plugin находит системный
/nix/store/...-bun-*/bin/bun и не пытается скачивать свой.
T22 в tasks/manifest.json: 'warning' (stale: «home/secondary.nix НЕ
закоммичен») → три новых поля:
• fix_landed: 034bb5e закоммичен и запушен в gitea/dev 2026-10-15T13:45
• next_action_required: на sapphira выполнить deploy .#rydiwo
(или nixos-rebuild switch --flake .#rydiwo --target-host oqyude@rydiwo)
• verify_after_deploy: 4 ожидаемых проверки (systemctl status, socket,
git status на rydiwo, herdr --machine rydiwo с sapphira)
handoff-summary.md:
• «⚠️ Незакоммиченная работа» — две metaagent-director записи (вне
этого репо), затем секция «Запушено в gitea/dev после прохода» с
034bb5e + 4bf8e55, затем «⏳ Следующее физическое действие»
объясняющее, почему до deploy .#rydiwo herdr на rydiwo живёт из
scp-копии, а не из /nix/store, и почему из-за этого мост
sapphira↔rydiwo может «впечатлять, что sapphira пытается
императивно установить».
• T22 строка в Pending-таблице: 'коммит 034bb5e, в gitea/dev; deploy
step pending'.
• Project State: herdr user service — оба через home/modules/herdr.nix,
на rydiwo ждёт deploy .#rydiwo.
• Next Steps: deploy .#rydiwo как item #1, старый item #7 (про
коммиты в nixos .agent/) удалён — выполнено в 4bf8e55.
• Key Artifacts / State: checkpoints.json phases
(execution → completed, metastate → completed, handoff →
in_progress) — синхронизировано с реальным состоянием из 4bf8e55.
Brings the meta-agent narrative layer (.agent/) in sync with the
metaagent-director-2026-10-15 session that landed herdr multi-host
setup (T21-T25), herdr-webui nginx vhost evolution (T23), token gate
(T24), v0.2 docs in metaagent-director repo (T26), ADR-0005 (T27),
and the next-pass pending tasks (T28-T32, including v0.2 opencode-
director unit, upstream PR for sameOrigin X-Forwarded-Host, cleanup
of T18 status).
Key invariant formalized: R1.15 (herdr.zeroq.su без authelia, только
herdr-webui token + in-place patch в server/machine-security.ts до
T29 merge). Подробности в ADR-0005.
R1.14 (ADR-0004, escapeSystemdPath) уже внесён в прошлом проходе
(T19), дополнительно не дублируется здесь.
Whitespace regression fix in project-rules.md:145 — single line
wrap вместо extra spaces после «проверяться.»