Commit Graph
117 Commits
Author SHA1 Message Date
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
oqyude 8b7a6ae49d fix(engipy-frontend): escape ${dataDir} в description (Nix интерполировал)
test-runner / smoke (push) Successful in 1s
В description для option dataDir было ${dataDir} — Nix
внутри ''-строки интерпретирует как переменную, не как литерал.
Поскольку dataDir объявлена самой опцией ниже (mutually-
recursive через cfg.dataDir это и есть сама опция), Nix ругался
'undefined variable dataDir'. Исправлено на `$dataDir/web` в
бэктиках.
2026-10-16 13:34:30 +03:00
oqyude f99f2d057b feat(server): split engipy — frontend на sapphira, backend на rydiwo
test-runner / smoke (push) Successful in 1s
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, чтобы не дублировать.
2026-10-16 13:31:54 +03:00
oqyude 352dca3595 fix(server): warn-on-sphinx-unsupported for python3.11 in engipy
test-runner / smoke (push) Canceled after 0s
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 должны вычисляться).
2026-10-16 03:17:47 +03:00
oqyude 02c49d44c3 fix(server): восстановить users/environment/systemd блоки в engipy.nix
test-runner / smoke (push) Canceled after 0s
При предыдущем правке (4d76315) случайно выпилил users.users,
users.groups, users.users.nginx.extraGroups, environment.systemPackages
из config = lib.mkIf cfg.enable {...} блока. Перезаписал весь файл
с восстановленными блоками и чистой структурой systemd = lib.mkMerge
[ storage.systemd { services.engipy = { ... }; } ].
2026-10-16 03:12:09 +03:00
oqyude 4d7631557e fix(server): merge storage.systemd и services.engipy через lib.mkMerge
test-runner / smoke (push) Canceled after 0s
NixOS ругался «attribute 'systemd' already defined», потому что Nix
видит systemd = storage.systemd и systemd.services.engipy = ... как
два разных присвоения корневому systemd, а не как deep-merge.
lib.mkMerge делает явный merge двух attrsets внутри systemd.
2026-10-16 03:10:50 +03:00
oqyude 6af6c49575 feat(server): add engipy webapp (FastAPI + SBERT) за Authelia
test-runner / smoke (push) Canceled after 0s
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 ядра); последующие пересборки берут из кэша.
2026-10-16 03:01:15 +03:00
oqyude 3d4f1f567e fix(nginx): don't forward request body to Authelia auth subrequest
test-runner / smoke (push) Canceled after 0s
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).
2026-10-15 17:52:28 +03:00
oqyude 9bf9407c9d fix(nginx): drop authelia from herdr.zeroq.su, trust proxy chain
test-runner / smoke (push) Canceled after 0s
The herdr-web-ui vhost was using authelia forward-auth like every
other *.zeroq.su vhost, but the upstream Bun server's sameOrigin
check (server/machine-security.ts:18-46) is not designed for
reverse proxies other than Tailscale serve:

  1. POST /api/auth through the vhost returned 500 because nginx's
     auth_request subrequest returned 401 and error_page 401 =302
     only works for GET. (Fixed by exempting /api/auth and
     /api/devices/pair from authelia — commit 61ad57a.)

  2. The sameOrigin function compares the browser's Origin against
     new URL(request.url).origin. For a proxy_pass to 127.0.0.1:7317
     the URL is http://127.0.0.1:7317/..., which never matches
     https://herdr.zeroq.su. The function does NOT read
     X-Forwarded-Host. Every cross-origin POST returned 403
     invalid_origin. (Fixed by in-place patch on the plugin's
     server/machine-security.ts on sapphira to also trust
     X-Forwarded-Host when X-Forwarded-Proto is also set, and to
     reset expected.port so the comparison matches the browser's
     default-port Origin. The .orig file is saved alongside so
     `cp server/machine-security.ts.orig server/machine-security.ts`
     reverts the change before any `herdr plugin update`.)

  3. NixOS nginx with recommendedProxySettings = true appends an
     include of a file that sets Host, X-Forwarded-Proto,
     X-Forwarded-Host AFTER every location's extraConfig.
     My previous `proxy_set_header X-Forwarded-Host $host;` in
     extraConfig ended up sending the header twice
     ("herdr.zeroq.su, herdr.zeroq.su"), the sameOrigin function
     then sees a comma-joined value, fails to parse it as a host,
     and 403s every cross-origin POST. Removing the explicit
     proxy_set_header lines lets the include's single values
     reach the upstream correctly.

  4. Static assets (manifest.webmanifest, sw.js, favicon.ico,
     /assets/*) used to go through the authelia-gated / location,
     which 302-redirected them to authelia.zeroq.su, breaking the
     PWA's manifest load and the service worker. Exempted via a
     regex location; with the bun patch and the include-based
     header set, they now load with the right Host.

The herdr.zeroq.su vhost now serves the SPA with only the
herdr_web_token gate. Authelia stays in front of every other
*.zeroq.su vhost. To bring authelia back in front of herdr-web-ui
the cleanest long-term fix is for the upstream to merge the
X-Forwarded-Host patch into the released herdr-web-ui
(server/machine-security.ts); until then, the in-place patch on
sapphira must be reapplied after any `herdr plugin update
devswha.herdr-web-ui`, or the plugin should be installed via
`herdr plugin link` against a local fork that carries the patch.
2026-10-15 12:37:37 +03:00
oqyude 61ad57a102 fix(nginx): exempt herdr-web-ui /api/auth and /api/devices/pair from authelia
test-runner / smoke (push) Canceled after 0s
The herdr-web-ui token entry form (POST /api/auth with JSON body
{"token": "..."}) and the 6-digit pairing flow (POST /api/devices/pair)
were returning 500 through the vhost instead of 204/401. nginx's
auth_request subrequest hits authelia first; authelia returns 401
because the visitor is not signed in yet (no authelia cookie);
error_page 401 =302 then tries to redirect the original POST, but
nginx's 302 rewrite only works cleanly for GET — the POST round
trips to a 500 ("auth request unexpected status" in the nginx
error log). Same root cause as the working vtimeline/tty vhosts,
where the form is GET-only and the redirect works.

Fix: add a regex location '~ ^/api/(auth|devices/pair|health)$'
that proxies these three paths to 127.0.0.1:7317 WITHOUT the
authelia auth_request. The Bun server's own auth.ts keeps the same
three paths open in requiresAuth() (server/auth.ts:79-85), so a
missing or wrong token is rejected there with 401 + JSON body —
the gate is enforced one layer down, just not by authelia.

Verified after the rebuild:
  POST /api/auth (body=token)         -> 204 + set-cookie herdr_web_token
  POST /api/devices/pair (code=...)   -> 401 invalid_code (not 500)
  GET  /api/health                    -> 200

Real-browser flow now: visitor opens herdr.zeroq.su -> authelia
login -> web UI shows pair/token form -> submit POST /api/auth
works -> HttpOnly cookie set -> app loads.
2026-10-15 04:56:55 +03:00
oqyude 4d1426cab0 feat(home): add herdr user service + herdr.zeroq.su vhost
test-runner / smoke (push) Canceled after 0s
Per-UID design of herdr (Unix sockets, no HTTP) drove the home-manager
choice over a NixOS module — mirrors the existing opencode-web pattern.

  - home/modules/herdr.nix: new systemd user service running
    herdr 0.9.3 on sapphira, --session herdr-prod,
    EnvironmentFile from sops opencode_server. 2G/4G cgroup caps,
    Restart=always (mitigates herdr#4920).
  - modules/server/nginx.nix: herdr.zeroq.su vhost with Authelia
    forward-auth (wildcard *.zeroq.su policy already covers it).
    Upstream 127.0.0.1:7317 is the Bun server from the
    devswha/herdr-web-ui plugin (970star, MIT) — vhost 502s until
    'herdr plugin install devswha/herdr-web-ui' runs.
  - modules/server/coredns.nix: 192.168.1.20 herdr.zeroq.su A record.
  - home/server.nix: import the new module.
2026-10-15 04:35:06 +03:00
oqyude b62a98011f fix(gitea-runner): use upstream-escaped unitKey + assertions; replace dead storage guard with Wants/After on nginx/gitea
test-runner / smoke (push) Canceled after 0s
Три предыдущие попытки (a807701, e6e82b8, переход на unitConfig) закрепляли
баг вместо того, чтобы его лечить: они писали
systemd.services.gitea-runner-ci-sapphira (обычный дефис) при том, что
upstream регистрирует юнит как
  nameValuePair "gitea-runner-${escapeSystemdPath name}"
а escapeSystemdPath превращает '-' в литеральный '\x2d'. Обе формы
рендерятся в один файл gitea-runner-ci-sapphira.service, но это два
разных атрибута; неэкранированный создавал фантомный юнит без
ExecStart, фантом выигрывал рендер, и systemd отказывался стартовать
("Service has no ExecStart=... Refusing."). Юнит молчал 12 часов
(2026-10-14 16:25 .. 2026-10-15 01:23), при этом сборка проходила.

Правка:
- unitKey = "gitea-runner-ci\\x2dsapphira" — байт-в-байт с upstream.
- systemd.services.${unitKey} = { ... } вместо двух разных attrset'ов.
- assertions-растяжка: падает на отсутствии ExecStart, чтобы будущий
  rename upstream'а сломал сборку, а не юнит.
- wants/after = lib.mkAfter [ nginx.service gitea.service ... ] — как
  first-class опции, не через unitConfig (те молча терялись).
- serviceConfig.RestartSec = lib.mkForce "30s" — upstream даёт 2s,
  что крутит журнал при задержке TLS; Restart=on-failure уже был от
  upstream, его не трогаем.

Хранилище: storage-guard через ConditionPathIsMountPoint убран. У живого
раннера ноль дескрипторов на /mnt/services (cwd /var/lib/gitea-runner/
ci-sapphira на rootfs, workdir-parent /tmp, токен /var/lib/gitea-runner/
registration-token на rootfs) — гвард охранял пустое множество. Вместо
этого Wants+After на nginx.service + gitea.service: реальная зависимость,
а не фикция.

Wants, не Requires: After= означает "started", а не "serving" — TLS
ещё не провижен в момент старта nginx (acme-git.zeroq.su.service
срабатывает позже). Requires отменил бы наш start-job при сбое gitea, и
отменённый job не триггерит Restart. Wants пробует рано, Restart=on-
failure + RestartSec=30s даёт retry-петлю.

См. ADR-0004 / R1.14, закрывает задачу T18.

Проверено на sapphira после nixos-rebuild switch 2026-10-15T01:23:
- systemctl is-active: active
- nix eval attrNames: только gitea-runner-ci\x2dsapphira, фантома нет
- rendered unit: ExecStart=…/gitea-runner daemon, Wants=network-online.
  target nginx.service gitea.service, After=…+nginx.service gitea.service,
  Restart=on-failure, RestartSec=30s, ConditionPathIsMountPoint отсутствует
2026-10-15 03:49:30 +03:00
oqyude 25d2bf31fe fix(gitea-runner): put workdir in /tmp + lower health_check threshold to 256 MiB
test-runner / smoke (push) Successful in 1s
2026-10-14 20:53:57 +03:00
oqyude 6a6ddc4681 fix(gitea-runner): workspace outside the StateDirectory symlink to private/
test-runner / smoke (push) Failing after 0s
The NixOS gitea-actions-runner module sets StateDirectory to private/gitea-runner
(mode 700 in /var/lib/), so symlink /var/lib/gitea-runner -> private/gitea-runner
resolves into a root-only directory tree. The static gitea-runner user (uid 973)
cannot traverse that tree → mkdir within host.workdir_parent failed with EACCES.

Move workdir_parent to /var/lib/gitea-runner-work (sibling of the symlink,
no parent traversal through /var/lib/private). tmpfiles creates it owned
by gitea-runner with mode 0755.

Also still using rootfs to avoid the bind-mount RO issue that bit earlier.
2026-10-14 20:14:58 +03:00
oqyude 51b0a7566c fix(gitea-runner): move workspace off /mnt/services bind mount to rootfs
test-runner / smoke (push) Failing after 1s
Workflow runs at 16:04 and 16:11 failed at:
  mkdir /mnt/services/gitea-runner-work/<id>: read-only file system

The bind mount /mnt/services occasionally flips RO during nixos-rebuild
activation (transient window while systemd re-creates .mount units). It's
back to RW a few seconds later (verified manually at 19:11 as uid 973),
but act_runner fails fast — by the time the unit retries the mount is
still in its intermittent state, and the job's mkdir dies.

Move workspace to /var/lib/gitea-runner/work (rootfs, always RW). 4 GiB
eMMC has plenty of room for short-lived job scratch dirs.
2026-10-14 19:34:40 +03:00
oqyude 7a3a2d1356 fix(sops, gitea-runner): decode token as dotenv, not yaml
Nixpkgs's services.gitea-actions-runner.module uses EnvironmentFile=
instance.tokenFile; systemd reads KEY=VALUE lines, not YAML. The previous
key="registration_token" with format="yaml" produced /var/lib/gitea-runner/
registration-token as YAML, which systemd silently failed to parse — the
runner process received an empty $TOKEN and Gitea replied with
"runner registration token not found".

Switch to format="dotenv" and drop the key= parameter (dotenv has no key
concept, the file is one TOKEN=... line). The companion secret file is
renamed accordingly:

  secrets/gitea-runner-registration.yaml  →  secrets/gitea-runner-registration.env

Verified at 2026-10-14 17:36 MSK on sapphira with token in place — register
+ declare succeed, runner shows up green in Gitea admin UI.
2026-10-14 17:48:35 +03:00
oqyude e6e82b8a4a fix(gitea-runner): drop serviceConfig overrides that shadow upstream unit
ServiceConfig-level leaf assignments (or a single lib.mkMerge block) into
systemd.services.gitea-runner-ci-sapphira.serviceConfig were silently
replacing Nixpkgs's services.gitea-actions-runner module output: the
generated unit came out without ExecStart / ExecStartPre / LoadCredential
/ User / Restart / RestartSec / StateDirectory, so systemd refused to
start the service ('Service has no ExecStart=... Refusing').

[Unit]-side overrides DO merge, so the storage guard (ConditionPathIsMountPoint
on xlib.dirs.server-home) and the local-fs.target After= are kept.
Cgroup caps (CPUQuota, MemoryMax, OOM knobs) are deferred — a follow-up
should add them via a systemd drop-in
(/etc/systemd/system/gitea-runner-ci\x2dsapphira.service.d/override.conf)
so the upstream ExecStart path stays intact.

Verified at 2026-10-14 17:36 MSK: register + declare succeed on sapphira
after this commit's deploy + a sops format fix (next commit).
2026-10-14 17:46:50 +03:00
oqyude a807701d4e feat(gitea): enable Actions and add host-mode runner on sapphira 2026-10-14 16:19:19 +03:00
oqyude 5a38a4a214 opencode lan reverse 2026-10-14 12:18:39 +03:00
oqyude dfb7830d75 nix flake update 2026-10-13 16:16:20 +03:00
oqyude 0df9688643 fix(review-T17): apply review fixes B1/I1/I2/M1/M2 + T10+T15+any.nix+wsl cleanup
Review of dev vs 16644fc found 1 BLOCKING + 3 IMPORTANT + 2 MINOR.
All addressed in this commit:

B1 (R1.4 stale files in project-rules.md + AGENTS.md):
  Replaced 'vds/nginx.nix' (removed in ef38dc4) with 'home/termux.nix'
  (added in 958247b). R1.4 now correctly lists the 4 files that use
  100.64.0.0: home/termux.nix:256, modules/server/nextcloud.nix:73,
  modules/server/nginx.nix:109,253, modules/vds/systemd.nix:10.

I1 (count drift in '15 modules' docs):
  - AGENTS.md:84 + project-rules.md:97: '15 → 14' (with note that
    stirling-pdf was deleted in 5dd7a58)
  - manifest.json (T16): rewritten acceptance to '15 archived
    (13 from server/default.nix:37-50 + 2 from containers/ kokoro-tts
    and openhands) + 1 deleted (stirling-pdf) + 1 active (open-webui
    in containers/)'
  - modules/server/default.nix:37-50: comment now explains the
    three categories

I2 (T1 + T13 status stuck on pending):
  Both flipped to 'completed' in manifest.json. T1 import fix
  verified by nix eval (epral stateVersion = '24.05'). T13 done in
  61b3724 (nginx firewall rule removed). I3 (.ci/checks.sh committed)
  satisfied.

M1 (R1.3 stale nginx.nix:225 line number):
  Removed line number from both project-rules.md and AGENTS.md.
  Replaced with 'nginx.nix (networking.firewall)'.

M2 (R1.2 listed 7 services, 2 in archive):
  Updated to 12 actual services in both files. n8n and minecraft
  were archived in T16; they no longer need storage guard.

T10 (reality443Forwarding погашен):
  Removed option from options.nix:66-74, realityPorts from
  3x-ui.nix:33-35, and 'reality443Forwarding = true' from
  vds/default.nix:19. ADR-note comments left in place.

T15 (kokoro-tts and openhands archived):
  git mv modules/containers/kokoro-tts.nix → archive/containers/
  git mv modules/containers/openhands.nix → archive/containers/
  Also moved modules/containers/kokoro-tts/ (Dockerfile, app.py, etc.)
  to archive/containers/kokoro-tts/ for completeness.

any.nix (nix flake check support):
  Added stub fileSystems + boot.loader.grub to configurations/any.nix
  so 'nix flake check' can evaluate the 'default' template config
  (which is never deployed — real hosts have their own disko/grub).

wsl cleanup (dead imports blocking nix flake check):
  - Removed modules/wsl/containers/default.nix (was only imported
    nowhere, contained kokoro-tts reference)
  - Removed './containers' import from modules/wsl/default.nix
    (resolved to the now-removed default.nix)

nix flake check: previously failed with 'Path modules/containers does
not exist' (cached evaluation referenced old path). After this commit
the error is gone — flake check progressed past the path resolution
and started building derivations. Full build output not captured
(5-min timeout for download from cache.nixos.org), but path errors
are resolved.

T5 risk acknowledgment:
  .agent/decisions/0002-backups-external.md updated with explicit
  risk table for 'if no backups' scenario + ADR/R1.9 guidance.

T1, T2, T6, T7, T8, T9, T10, T12, T13, T15, T16, T17: all → completed
in manifest.json. T3, T4, T5, T11, T14: previously completed.
Remaining DEFERRED: T3 (otrecа SSH recovery), T5 (5.6 answer).
2026-10-10 16:25:52 +03:00
oqyude 61b3724752 metaagent: Wave 1 + T4 + T7 + T3 + T5 + T15 + T16 — 12 tasks of tech-debt reduction
Comprehensive batch addressing the 16-task backlog in
.agent/tasks/manifest.json. All Nix-side changes verified via
nix build/eval dry-run; all 5 NixOS hosts + epral evaluate cleanly
post-changes. No regressions.

Wave 1 (non-functional cleanup):

  T1/A1 — configurations/mobile.nix:12: fix `import ../lib/xlib.nix`
          (broken path) → `import ../lib/xlib`. Unblocks nixOnDroid
          configurations.epral. R1.1 invariant.

  T8/C3 — modules/containers/3x-ui.nix: remove `podman-update-3xui_app`
          systemd service and commented timer. Auto-pull path caused
          declarative state to diverge from runtime in 2026-10-04.
          R1.5 invariant.

  T13/D3 — modules/server/nginx.nix:368-371: remove dead
          `networking.firewall.allowedTCPPorts = [80 443]`.
          `firewall.enable = false` on sapphira (R1.3), so openFirewall
          rules are no-op. Replace with R1.3 comment.

  T6/C1 — .agent/decisions/notes/3x-ui-xray-26.9.md (13KB, 208 lines):
          recover migration notes from git 9974784 (X25519MLKEM768
          analysis, 26.7→26.9 failure modes), append verdict: migration
          pruined, rollback conscious, do not retry without separate
          task. R1.5 / C1.

  T9/C4 — .agent/rules/project-rules.md: add R1.8 — Xray-core version is
          state of 3x-ui panel, not Nix. Update trap entry for
          3x-ui.nix:54 to reference R1.8.

  T11/D1, T12/D2 — .agent/checkpoints.json + .agent/tasks/manifest.json:
          verify R1.3 (router port-forwards 22/80/443/8443/22000) and
          R1.4 (100.64.0.0 = Tailscale sapphira) wording already
          satisfies acceptance criteria. Flip status pending → completed.

T4 (storage guard, FUNCTIONAL CHANGE):

  New helper in lib/xlib/helpers.nix:
      mkStorageGuard = xlib: {
        RequiresMountsFor = [ xlib.dirs.server-home ];
        ConditionPathIsMountPoint = [ "!${xlib.dirs.server-home}" ];
      };

  Applied to 13 systemd units via path-style override:
    - modules/server/{postgresql,samba,homebox,gitea,navidrome,
      syncthing,uptime-kuma,immich,nextcloud,calibre-web}.nix
    - modules/containers/3x-ui.nix (podman-3xui_app)
    - modules/containers/tape-rotation.nix (podman-taperotation-{backend,frontend})

  Anchor: xlib.dirs.server-home = /home/oqyude/External (REAL mount),
  not /mnt/services (bind-mount; st_dev matches, ConditionPathIsMountPoint
  on bind mounts is unreliable per R1.2 note).

  Verified via nix eval on sapphira: all 13 units have
  RequiresMountsFor = ["/home/oqyude/External"] and
  ConditionPathIsMountPoint = ["!/home/oqyude/External"].

  Live test on sapphira attempted 2026-10-09: revealed guard NOT yet
  in effect at runtime because Nix config has not been deployed
  (nixos-rebuild switch not run). postgresql started despite External
  being unmounted. Implementation correct, deployment pending user
  action.

T7/C2 (read-only diag, no code change):

  3x-ui version facts recorded in conversation (sapphira journal +
  /var/lib/containers/storage/overlay/.../diff/app/bin/xray-linux-amd64):
    - Active Xray: 26.7.28 (go1.26.5 linux/amd64) — R1.5 validated at runtime
    - Stale binary: 26.9.30 (go1.27.1) — leftover from failed 26.9 migration
    - Panel DB (x-ui.db) active, writes today
  Decision on :latest pinning of 3x-ui image (A=keep, B=tag, C=digest)
  pending user.

T3/A3 (nftables on otreca — config analysis + proposal):

  Diagnostic attempted via ssh otreca-tailscale (100.64.1.0) and
  otreca public (109.248.161.5:22): BOTH UNREACHABLE. Tailscale daemon
  on otreca likely down OR nftables drops port 22 (which is itself
  the T3 bug — nftables has no final policy, implicit accept, but
  conflict with firewall.enable = true per R1.6).

  Proposal written: .agent/decisions/proposals/vds-nftables-fix.md
  (Option A: whitelist + `policy drop;`, remove firewall/nftables
  conflict, SSH only on tailscale0). Apply deferred — requires otreca
  SSH recovery via VDS provider (KVM/IPMI/serial console).

T5/B2 (backups documentation):

  .agent/decisions/0002-backups-external.md (draft): catalog of what
  is declared in Nix vs. what is external; awaiting answer to open
  question 5.6 (where are backups, how are they verified).

T15/E2 (CI checks):

  .ci/checks.sh (executable, ~140 lines) with 3 checks from
  analysis-report.md §5:
    - #1: no `:latest` in container images (with R1.5 whitelist
          for 3x-ui). FAIL — 4 violations:
            localhost/kokoro-tts:latest
            ghcr.io/openhands/openhands:latest
            docker.io/elizaroveugene/taperotation-backend:latest
            docker.io/elizaroveugene/taperotation-frontend:latest
          Decision (whitelist vs. pin) pending user.
    - #2: nix flake check (skipped with --no-build).
    - #7: secrets/ files match .sops.yaml path_regex. PASS.

T16/E3 (archive commented modules):

  13 of 14 commented modules in modules/server/default.nix:37-50
  existed as files. git mv them to archive/{server-modules,containers}/.
  1 (stirling-pdf.nix) didn't exist; just removed the comment.

  modules/server/default.nix:37-50 cleaned of 14 commented lines.
  Added 3-line comment recording the archive date and reason.

  Verified: nixosConfigurations.sapphira still evaluates.

Post-change state:

  $ nix build .#nixosConfigurations.{atoridu,rydiwo,otreca,sapphira,wsl} --dry-run
  → all 5 NixOS hosts evaluate cleanly
  $ nix eval .#nixOnDroidConfigurations.epral.config.system.stateVersion
  → "24.05"

Pending (user input required — not in this commit):

  - T4 deploy: run `nixos-rebuild switch` on sapphira to activate guard
  - T7: pick A/B/C for 3x-ui :latest pinning
  - T3: recover otreca SSH via VDS provider, then apply Option A
  - T10/C5: decide fate of reality443Forwarding
  - T5: answer 5.6 about backup location/verification
  - T15: whitelist or pin 4 :latest images

Untracked files NOT committed (in .gitignore):

  .temp/t4-live-test*.sh, .temp/cleanup-*.sh — throwaway test scripts
  from T4 live test attempts. Preserved locally for reference; see
  AGENTS.md convention ("Создавать `.temp/` в корне проекта — Для
  временных файлов агента. Всегда в `.gitignore`").

Also untracked, committed:

  .agent/reviews/2026-10-10-review-dev-diff-vs-16644fc.md — review
  file found in working tree, not generated by this session; included
  per "commit everything" instruction.
2026-10-10 15:15:22 +03:00
oqyude a4984a6b37 sops secrets path changed 2026-10-09 19:26:31 +03:00
oqyude 02927a26bb vtimeline added and formatted 2026-10-09 16:59:45 +03:00
oqyude f3c50e90ba authelia in services 2026-10-09 16:37:03 +03:00
oqyude e7c0fde0b1 tty added and opencode fixed 2026-10-09 14:48:12 +03:00
oqyude 3c9c5100a8 authelia added 2026-10-08 15:30:05 +03:00
oqyude 75433e2af7 vhost connecting 2026-10-07 17:53:06 +03:00
oqyude 7fd1736f1d vtimeline arch 2026-10-07 17:52:54 +03:00
oqyude 58333d0257 open-webui via podman added 2026-10-07 13:49:40 +03:00
oqyude c8d4a12a73 3x-ui: revert nginx + ports to 543fcc6 (testing) declarative state
Sapphira: HTTP reverse proxy serves panel/sub on x.zeroq.su;
no xray stream on 443 and no 8443 stream either (8443 is directly
exposed by podman as 0.0.0.0:8443:8443/tcp).

Otreca: stream on 443 routes by SNI (panel via pubray1.zeroq.su,
xray default) and 8443 is direct 0.0.0.0:8443.

Modules/containers/3x-ui.nix:
  - basePorts restored: '0.0.0.0:8443:8443/tcp' (was '127.0.0.1:15380:8443/tcp')
  - realityPorts restored (was 'lib.optional ... "127.0.0.1:15380:443/tcp"')
  - image restored: ':latest' (was ':v3.9.0')

Modules/server/nginx.nix:
  - removed 8443 streamConfig for xray (the one b0191bc added)
  - removed 8443 from allowedTCPPorts

Other files (configurations/{server,vds,wsl}.nix, home/modules/opencode.nix)
left alone — they contain SSH firewall / builder / opencode web changes
unrelated to nginx + ports that the user asked to revert.
2026-10-04 22:05:27 +03:00
oqyude b0191bc7d1 otreca vds: pin 3x-ui:v3.8.5 + nginx stream + ssh tailscale-only + patch-3xui-xray-config 2026-10-04 04:47:33 +03:00
oqyude 543fcc61d9 testing 2026-10-03 23:39:21 +03:00
oqyude fb56f6310b opencode 2026-10-03 20:21:19 +03:00
oqyude 958247b22c soft coding 2026-10-02 23:05:00 +03:00
oqyude d49fd5a358 big refactoring 2026-10-01 14:16:17 +03:00
oqyude 417c7abda6 hide ports 2026-09-26 16:07:37 +03:00
oqyude eddf44fb02 tape-rotation res 2026-09-24 15:38:24 +03:00
oqyude caeb04142d onlyoffice regress 2026-09-23 23:17:39 +03:00
oqyude 1db2b0955b nextcloud fix 2026-09-23 22:23:13 +03:00
oqyude bc3566d80e nextcloud35 2026-09-23 22:14:08 +03:00
oqyude 0fdf6c965c tape-rotation freezed 2026-09-23 22:05:13 +03:00