Commit Graph
278 Commits
Author SHA1 Message Date
oqyude 5a4711a738 fix(server): warn-on-sphinx-unsupported for python3.11 in engipy
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-19 18:23:19 +03:00
oqyude 13904c2b0a fix(server): восстановить users/environment/systemd блоки в engipy.nix
При предыдущем правке (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-19 18:23:19 +03:00
oqyude 4354d07ff2 fix(server): merge storage.systemd и services.engipy через lib.mkMerge
NixOS ругался «attribute 'systemd' already defined», потому что Nix
видит systemd = storage.systemd и systemd.services.engipy = ... как
два разных присвоения корневому systemd, а не как deep-merge.
lib.mkMerge делает явный merge двух attrsets внутри systemd.
2026-10-19 18:23:19 +03:00
oqyude 5a6b767d01 feat(server): add engipy webapp (FastAPI + SBERT) за Authelia
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-19 18:23:19 +03:00
oqyude f92b035d7b chore(pxe-infra): gitignore — ignore H_fix.* regression debris
Adds two patterns:

  h-fix-*-helpers/   \u2014 catch regression test script dirs (e.g. h-fix-2-helpers/)
  *.bak-t*           \u2014 in-place edit backup suffixes from T9/T10 (.bak-t9, .bak-t10)

Both directories/files are session-scoped: produced by ad-hoc test scripts
during a regression cycle, then left behind as untracked noise after the
cycle completes. Easiest fix at the source is the gitignore; future
H_fix.{3,4,...} sessions should not need to manually exclude them.

Followup to 52d6b0b feat(pxe-infra): split boot.ipxe ...
2026-10-19 18:23:19 +03:00
oqyude 1d91e328ed feat(pxe-infra): split boot.ipxe (sanboot) from boot-bypass.ipxe (regression baseline)
The former single boot.ipxe writeText block in modules/pxe-infra/ipxe.nix has been split into two static scripts under artifacts.root/http/:

  - boot.ipxe        \u2014 production sanboot path. Chains to the
                        alpine-worker raw image; OVMF walks the ESP,
                        systemd-boot reads loader/entries/alpine.conf.
  - boot-bypass.ipxe \u2014 H_fix.1b regression baseline. kernel+initrd
                        path; preserved byte-identical to the pre-split
                        boot.ipxe content (matches the
                        T10-h-fix-1b log shape on rydiwo 2026-10-14).

autoexec.ipxe now selects the chain target via a new option:

  pxe-infra.bootloader.bypassFallback.enable (lib.types.bool, default false)

When true, autoexec.ipxe chains to boot-bypass.ipxe; when false (default),
to boot.ipxe. Both scripts are always staged (no mkIf gate) so the chain
target flips with a config change + rebuild, no redeploy.

In modules/pxe-infra/default.nix a new systemd-tmpfiles L+ rule mirrors
the existing boot.ipxe rule for boot-bypass.ipxe.

This unblocks H_fix.2 (real sanboot + POST end-to-end verification on
rydiwo). The bypass path is the regression baseline \u2014 S4 in
.agent/notes/H_fix.2-scenarios.md validates it still reaches the Alpine
Init shell when the option is flipped.
2026-10-19 18:23:19 +03:00
oqyude 46b89afe83 chore(agents): metastate cleanup — sync checkpoints↔manifest, fix handoff T18/T32, dedup AGENTS.md invariant 12, fix backlog_count 28→30
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, дубль-данные гарантированно протухнут)
2026-10-19 18:23:19 +03:00
oqyude ab172c6f21 chore(agents): meta-state refresh — herdr attach attempt reverted, dev force-reset to 3d4f1f5
Сессия 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.
2026-10-19 18:23:19 +03:00
oqyude f0ea1fd535 fix(nginx): don't forward request body to Authelia auth subrequest
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-19 18:23:19 +03:00
oqyude 816ae1985f docs(agents): saga close-out — T18/T32 closed, T33 added, ADR-0005 maintenance procedure зафиксирована
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 закрыта.
2026-10-19 18:23:19 +03:00
oqyude 27138b2660 fix(home): add nodejs_22 to herdr-runtime.nix (herdr-web-ui preflight)
После 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 мерджит и дедуплицирует,
так что лишней копии не будет.
2026-10-19 18:23:19 +03:00
oqyude 90c83d89e2 feat(essentials): enable programs.nix-ld for generic-linux bun runtime
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; в этом же файле было закомментировано —
видимо, не дошли руки; теперь разкомментировано с явным почему.
2026-10-19 18:23:19 +03:00
oqyude c309e187e8 refactor(home): extract pkgs.bun into herdr-runtime.nix, drop duplication
Раньше 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 + новый модуль).
2026-10-19 18:23:19 +03:00
oqyude c9a6c29f04 fix(home): add pkgs.bun to rydiwo home packages (herdr-web-ui runtime)
На сапфире 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 и не пытается скачивать свой.
2026-10-19 18:23:18 +03:00
oqyude 478e4e486e docs(agents): document deploy .#rydiwo as next physical action (T22 fix landed)
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.
2026-10-19 18:23:18 +03:00
oqyude 6170a0e774 docs(agents): sync R1.15, ADR-0005, T21-T32 from metaagent-director-2026-10-15
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 после «проверяться.»
2026-10-19 18:23:18 +03:00
oqyude 989f93bf9b feat(home): add herdr import to rydiwo config (multi-host bridge)
rydiwo's home/secondary.nix now imports home/modules/herdr.nix so the
herdr systemd user service (server --session herdr-prod) is installed
declaratively via Nix instead of relying on scp'd files on rydiwo's
working tree (intent-to-add state from the metaagent-director-2026-10-15
session). Once this lands on gitea/dev, deploy-rs pulls it and applies
home.packages = [ pkgs.herdr ] + the systemd user unit through
home-manager activation, so 'herdr --machine rydiwo' on sapphira no
longer depends on a manually-provisioned binary on rydiwo.

T22 acceptance: home/secondary.nix committed + gitea/dev updated; the
existing scp'd copy on rydiwo becomes redundant and will be subsumed
by the next 'deploy .#rydiwo' run.
2026-10-19 18:23:18 +03:00
oqyude ea8b3d200b fix(nginx): drop authelia from herdr.zeroq.su, trust proxy chain
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-19 18:23:18 +03:00
oqyude d9c56746a1 fix(nginx): exempt herdr-web-ui /api/auth and /api/devices/pair from authelia
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-19 18:23:18 +03:00
oqyude 5c6c28f380 feat(home): add herdr user service + herdr.zeroq.su vhost
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-19 18:23:18 +03:00
oqyude 13a86dfc9d fix(gitea-runner): use upstream-escaped unitKey + assertions; replace dead storage guard with Wants/After on nginx/gitea
Три предыдущие попытки (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-19 18:23:18 +03:00
oqyude 25587c2972 agents(narrative): refresh project-state, handoff, roadmap
project-state.md: контейнеры 6 → 4 (3xui_app, taperotation-backend,
taperotation-frontend, open-webui); mkServiceStorage → mkStorageGuard;
T4 переписан под 13/12 + RequiresMountsFor отсутствует намеренно;
добавлен ADR-0002 в Decisions in Effect; дрейф manifest.md помечен
как устранённый; nftables атрибутирован configurations/vds.nix:71-91;
добавлена заметка про завис nix flake check в этой сессии (T2
не отзывается — коммит 61b3724 фиксирует более ранний прогон).

handoff-summary.md: полностью переписан по структуре 06_METASTATE 6.7.
Сняты три ложные утверждения: «checkpoints уже синхронизирован»,
«R1.14 ещё не внесён», «manifest.md устарел». Сохранены T18
(незакоммиченный gitea-runner.nix), T4/T3/T10 как pending. Постмортем
из трёх ошибок сохранён, ошибка №3 переформулирована: serviceConfig
мержится штатно, дефект гварда — секция [Service] вместо [Unit].

roadmap/sources.md: §10.4 переписан (3 файла CI, 3 из 7 проверок);
§10.3, 0.1, 0.3, 0.4, 5.6, 9.3, 11.2 — закрытые с указанием куда
ушёл ответ; сводка инвариантов расширена до R1.1–R1.14; backlog 23 → 22
(закрыт 5.6).
2026-10-19 18:23:18 +03:00
oqyude a48858ecaa agents(state): metastate refresh 2026-10-15 (T19, T20, ADR-0002, manifest.md)
Фаза 06_METASTATE: рефреш бухгалтерского слоя.

Фазы manifest.json и checkpoints.json синхронизированы (analyse,
roadmap, decomposition, metastate теперь completed).

T4 (мёртвый storage-guard): notes переписан под 13/12, убрана ложная
рекомендация RequiresMountsFor, направление починки через unitConfig/
unit., ссылка на ADR-0004.

T15 (CI/pre-commit): ложное «.ci/checks.sh (executable)» заменено
на факт режима 100644 (см. T20).

T16 (E3, закомментированные модули): notes отражает современное
состояние (0 закомментированных, 12 в archive/server-modules/ + 3 в
archive/containers/ + stirling-pdf.nix удалён в 5dd7a58).

T19 (R1.14, из этого коммита): completed.

T20 (новый, pending, severity: high): .ci/checks.sh лежит в git с
режимом 100644, оба call-site (.github/workflows/nix-checks.yml:20
run: .ci/checks.sh; .pre-commit-config.yaml:10 entry: ... language:
script) зовут его как исполняемый — оба падают с permission denied.
Все три проверки T15 (:latest, nix flake check, sops path_regex)
ни разу не запускались, инварианты не защищены. Фикс тривиален
(chmod +x или bash .ci/checks.sh в обоих вызовах), но требует
осознанного решения — отсюда severity high.

ADR-0002 (backups external): status draft → accepted. Владелец так и
не ответил на 5.6, риск формализован как R1.9.

Удалён .agent/tasks/manifest.md — единственный источник истины
manifest.json.

checkpoints.json: known_doc_drift → resolved_doc_drift, добавлен
protocol_deviations (6.3 архивация пропущена осознанно; .agent/
requests/ никогда не существовало; 6.4/6.5/6.7/6.8 выполнены).
2026-10-19 18:23:18 +03:00
oqyude b43b782982 agents(rules): sync R1.2/R1.14/R2, trap rows, nextcloud:80
R1.2 (мёртвый storage-guard): mkStorageGuard возвращает только
ConditionPathIsMountPoint; RequiresMountsFor отсутствует намеренно
(создаёт dependency, по которой systemd сам монтирует ФС при старте
юнита и обессмысливает гвард — проверено 2026-10-10). Все потребители
передают ConditionPathIsMountPoint через serviceConfig → рендерится
в [Service], где systemd его не читает. Масштаб: 13 systemd-юнитов /
12 сервисов (postgresql, samba, homebox, gitea, navidrome, syncthing,
uptime-kuma, immich, nextcloud, calibre-web, 3x-ui, tape-rotation x2).

R1.14 (новый, из ADR-0004): имя systemd.services.<…> при переопределении
upstream-юнита должно побайтово совпадать с nameValuePair-ключом
модуля. Диагностировать юнит только чтением файла, не systemctl show.

R2: ссылка обновлена с opencode.nix:339 на :407; баг serviceConfig
отмечен как исправленный в c73a698, R2 удерживает от регрессии.

Ловушки (trap table):
- server/default.nix:37-50 — заменена: закомментированных импортов 0,
  T16 завершена, архив 12+3+1.
- opencode.nix:339 — заменена: правильный паттерн на строке 407.

nextcloud.nix:73 → :80 (100.64.0.0 живёт там, не на :73).

Все правки зеркально продублированы в AGENTS.md (always-loaded
mirror).
2026-10-19 18:23:18 +03:00
oqyude 68e761c69f agents(decisions): add ADR-0004 — phantom systemd unit при переопределении upstream
Переопределяя systemd-юнит, который порождает upstream-модуль через
nameValuePair (например services.gitea-actions-runner), имя атрибута в
systemd.services.<…> должно побайтово совпадать с тем, что передаётся в
nameValuePair. escapeSystemdPath превращает '-' в литеральный '\x2d', что
для gitea-runner-ci-sapphira даёт ключ gitea-runner-ci\x2dsapphira (с
обратным слэшем). Обе формы рендерятся в один и тот же файл, но это
два разных атрибута; неэкранированный вариант создаёт фантомный юнит
без ExecStart, который выигрывает рендер — и systemd отказывается
стартовать. Юнит gitea-runner-ci-sapphira молчал 12 часов
(2026-10-14 16:25 → 2026-10-15 01:23).

Фикс — unitKey = "gitea-runner-ci\\x2dsapphira" плюс assertions-
растяжка в modules/server/gitea-runner.nix, которая валит сборку при
отсутствии ExecStart.

Этот же ADR формализует инвариант R1.14 (см. .agent/rules/project-rules.md).
Смежная находка: ConditionPathIsMountPoint в mkStorageGuard
(lib/xlib/helpers.nix:180-189) попадает в [Service] и игнорируется
systemd — задача T4 остаётся pending.
2026-10-19 18:23:18 +03:00
oqyude 49b9248de9 secrets(gitea-runner): replace placeholder with real registration token
Fills in TOKEN with the value from Gitea's "Create new runner" admin
panel, completing the placeholder introduced when host-mode Actions was
enabled. Edited via `sops secrets/gitea-runner-registration.env`, so the
commit carries ciphertext only — the age recipient key stays outside
the repo.

The runner re-registers on its own: ExecStartPre compares the .runner
hash against TOKEN and re-runs registration when they diverge.
2026-10-19 18:23:18 +03:00
oqyude 762275fdd3 opencode: remove opencode-loop plugin
Reverts the plugin registration added in 4ff7188 ("opencode:
opencode-loop added"). The entry had to be dropped from both places
inside programs.opencode, otherwise the plugin keeps loading in the
TUI:

  settings.plugin -> ~/.config/opencode/opencode.json
  tui.plugin      -> ~/.config/opencode/tui.json

oh-my-openagent is untouched; its agent and category overrides in
~/.omo/omo.jsonc still apply.
2026-10-19 18:23:18 +03:00
oqyude 6c1bf6917e fix(gitea-runner): put workdir in /tmp + lower health_check threshold to 256 MiB 2026-10-19 18:23:18 +03:00
oqyude b663ffb887 ci(gitea): re-trigger /tmp workspace 2026-10-19 18:23:18 +03:00
oqyude 7372549b4b ci(gitea): workspace -> /tmp 2026-10-19 18:23:18 +03:00
oqyude 8729537c5f ci(gitea): strace trigger 2026-10-19 18:23:18 +03:00
oqyude 6c42551911 ci(gitea): trigger after restart 2026-10-19 18:23:18 +03:00
oqyude cdff5b2672 fix(gitea-runner): workspace outside the StateDirectory symlink to private/
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-19 18:23:18 +03:00
oqyude 899e6faa84 ci(gitea): re-trigger test-runner after workspace fix + token re-entry 2026-10-19 18:23:18 +03:00
oqyude 7cc19900d8 fix(gitea-runner): move workspace off /mnt/services bind mount to rootfs
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-19 18:23:18 +03:00
oqyude 77e0436b25 ci(gitea): re-trigger after fixing mount 2026-10-19 18:23:18 +03:00
oqyude 03fca3410b ci(gitea): trigger test-runner workflow on push to dev 2026-10-19 18:23:18 +03:00
oqyude 23cbb2e0d5 ci(gitea): add note so the next push triggers test-runner 2026-10-19 18:23:18 +03:00
oqyude fb46ffeadb ci(gitea): add smoke-test workflow for the ci-sapphira runner
A two-trigger workflow — manual (workflow_dispatch) and on every push to
dev — that runs a single shell step on 'runs-on: native' to verify the
sapphira runner is healthy: hostname/whoami/pwd plus probes for the
common ZeroQ-workflow tools (nix, git, python3) and the act_runner
environment variables (RUNNER_NAME, RUNNER_TEMP).

Useful as a quick health check after any change to modules/server/
gitea-runner.nix, secrets/gitea-runner-registration.env, or after a
NixOS upgrade.
2026-10-19 18:23:18 +03:00
oqyude 71826d3b99 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-19 18:23:18 +03:00
oqyude 7a0e7d560e 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-19 18:23:18 +03:00
oqyude d4abd8f0cc feat(gitea): enable Actions and add host-mode runner on sapphira 2026-10-19 18:23:18 +03:00
oqyude 9693ded39a secrets(gitea-runner): add sops placeholder for registration token 2026-10-19 18:23:18 +03:00
oqyude 501086dde7 gitignore upd 2026-10-19 18:23:18 +03:00
oqyude 952451d15e feat(pxe-infra): use qemu-bridge-helper with setuid wrapper (T13)
Replace the manual `ip tuntap add` + `ip link set master` pattern in the
VM service with the standard `-netdev bridge,helper=...` approach. This
removes the bespoke tap lifecycle from the systemd script and uses
qemu's own bridge helper for TAP creation/teardown.

What changed in vm.nix:
  - Added security.wrappers.qemu-bridge-helper: a setuid root wrapper
    at /run/wrappers/bin/qemu-bridge-helper that execs the nixpkgs
    binary (${pkgs.qemu}/libexec/qemu-bridge-helper).
  - Added /etc/qemu/bridge.conf restricting the helper to the pxe0
    bridge (single `allow pxe0` line).
  - Added /run/wrappers/bin to the service PATH and `helper=` option
    on -netdev bridge, so qemu finds the wrapper.
  - Removed the tap creation in the script and the teardown in
    postStop — qemu-bridge-helper handles both.
  - Inlined `chmod 4755` on the wrapper at the top of the service
    script. The security.wrappers activation script in this NixOS
    version (qemu 11.1.1, edk2 202608) doesn't always apply the
    setuid bit, leaving the wrapper at mode 0511 which makes the
    helper fail to create the TAP. The inlined chmod is idempotent
    and runs as root (system service). Remove this once upstream
    NixOS is fixed.

Verified 2026-10-14 on rydiwo:
  - direct mode: VM boots, tap0 (created by helper) attaches to
    pxe0, all network up.
  - pxe mode: iPXE chain works end-to-end through the bridge —
    snp.efi -> autoexec.ipxe -> boot.ipxe (vmlinuz-virt Not found is
    expected; /latest/ copies were cleaned up after the H_fix.1b
    test).

T10 fix (autoexec.ipxe on TFTP root) is independent and already
committed (7c9a8d8 + syntax fix ae14fec). Closes T13.
2026-10-19 18:23:18 +03:00
oqyude a08c5ddd54 fix(pxe-infra): correct triple-quote to double-quote in autoexec.ipxe block
Nix indented strings use \x27\x27 (two single quotes) as delimiters, not \x27\x27\x27
(three). The autoexec.ipxe block added in 7c9a8d8 used \x27\x27\x27 which
the parser rejects with "unexpected end of file, expecting indented
string or \x27${ or end of an indented string". Replacing with the
correct \x27\x27 makes both copies (this one and the home-manager
symlink target) parse cleanly and unblocks nixos-rebuild.
2026-10-19 18:23:18 +03:00
oqyude 64036c4951 fix(pxe-infra): add autoexec.ipxe to TFTP root (resolves iPXE #GP / T10)
iPXE in UEFI mode looks for autoexec.ipxe on the same TFTP server it
was loaded from, and runs it as the boot script. Without it, the iPXE
instance that replaced the firmware PXE ROM has nothing to chain to
and ends up in No more network devices -> #GP.

This was the root cause of T10 (the iPXE 2.0.0 #GP with RIP 0x7EE8A5FC
or 0x7EC9456F depending on which point in the chain it crashed at).
Adding a 1-line autoexec.ipxe that chains to the HTTP-served boot.ipxe
makes the full chain work end-to-end: snp.efi -> autoexec.ipxe ->
boot.ipxe -> vmlinuz-virt+initramfs-virt -> kernel boot -> Alpine Init.

ipxe.nix: new environment.etc entry autoexec.ipxe via pkgs.writeText.
default.nix: tmpfiles rule symlinks it into the served TFTP root.

Verified 2026-10-14 on rydiwo with manual QEMU test (H_fix.1b):
snp.efi (iPXE 2.0.0) loaded, autoexec.ipxe found, HTTP boot.ipxe
fetched, kernel+initrd downloaded, handoff to firmware, Alpine Init
ran. No #GP. Detailed diagnostic in pxe-infra-automation
.agent/notes/T10-diagnostic-2026-10-14.md.
2026-10-19 18:23:18 +03:00
oqyude f0bb11de28 pxe-infra: add vm.bootMode option (direct | pxe)
The default "direct" preserves the proven E2E behavior
(2026-10-13). "pxe" enables the full L3 boot chain
(-boot n, no virtio drive) for reproducing T10 (iPXE 2.0.0
#GP at ExitBootServices, RIP 0x7EE8A5FC) and verifying any
fix. Switch modes by editing pxe-infra.vm.bootMode in
configurations/rydiwo and running nixos-rebuild switch —
no other changes needed.
2026-10-19 18:23:17 +03:00
oqyude afbfcaec69 opencode lan reverse 2026-10-19 18:23:17 +03:00
oqyude 09412b8bdb nix flake update 2026-10-19 18:23:17 +03:00