Commit Graph
272 Commits
Author SHA1 Message Date
oqyude 158f08d14a Revert "feat(home,agents): herdr workspaces now actually attach to shared opencode serve (ADR-0006 + symlink)"
This reverts commit 16a44b9fb2.
2026-10-15 20:15:39 +03:00
oqyude 16a44b9fb2 feat(home,agents): herdr workspaces now actually attach to shared opencode serve (ADR-0006 + symlink)
test-runner / smoke (push) Canceled after 0s
Предыдущая редакция (коммит 3e85307) положила шим первым в
Service.Environment herdr-юнита, но в боевом сценарии шим не
сработал: home-manager wrap (/etc/profiles/per-user/oqyude/bin/opencode)
всё равно выигрывал на интерактивных zsh-панелях с oh-my-zsh.

Причина (найдена эмпирически 2026-10-15): /etc/static/zshrc
подгружает oh-my-zsh.sh, который пересобирает $PATH из
$HOME/.nix-profile/bin и своего plugin list (ripgrep, nodejs-22, bun,
gh, ast-grep). Пересобранный PATH не содержит наш шим-каталог,
поэтому command -v opencode в панели возвращает wrap, и herdr
стартовал полный TUI с собственным LLM-аккаунтом.

Решение — второй слой: home-manager home.file кладёт симлинк
~/.local/bin/opencode → opencodeAttachShim/bin/opencode (под тем
же lib.mkIf config.programs.opencode.web.enable). ~/.local/bin
первый в PATH после ~/.local/bin/env, и этот симлинк
переживает пересборку PATH oh-my-zsh.

Проверено боевым тестом (sapphira, 2026-10-15T19:37):
herdr workspace create → herdr agent start opencode →
pane process-info: argv = [.../opencode-1.19.0/bin/opencode,
  attach, http://127.0.0.1:4096, --dir, /tmp/attach-smoke]
(5 аргументов вместо 1 у wrap'а); ss показывает 8 ESTAB
к 127.0.0.1:4096, 0 исходящих на LLM-провайдеры. RSS
упал с 570 МБ до 302 МБ, главный выигрыш — LLM-запросы
централизуются на opencode-web.service, открытие N воркспейсов
не множит N независимых LLM-аккаунтов.

Service.Environment остаётся как страховочный слой; для хостов
без oh-my-zsh он самодостаточен, для текущего sapphira (oh-my-zsh
включён) — нужен оба.

T34 в tasks/manifest.json: добавлены критерии про симлинк,
nixos-rebuild switch rc=0, боевой тест, отсутствие LLM-сокетов.
R1.16 в project-rules.md и инвариант 13 в AGENTS.md: расширены
под двухслойную схему. ADR-0006: новый раздел «Двухслойная
схема» с эмпирическим сценарием и командами теста.
2026-10-15 19:41:32 +03:00
oqyude 3e85307361 feat(home,agents): herdr workspaces connect to shared opencode serve (ADR-0006, T34)
test-runner / smoke (push) Canceled after 0s
herdr-демон v0.9.3 запускает агента как голый `opencode`
(src/detect/mod.rs: `Agent::OpenCode => "opencode"`) и вписывает токен в
шелл панели (src/app/agents.rs: `start_agent`). Конфиг-хука на замену
executable у herdr нет (`herdr --default-config` без `agent.*`).
На 2-4 вкладках это даёт 1.6-3.2 ГиБ opencode-инстансов поверх
5.6 ГиБ sapphira.

Решение: PATH-шим в herdr-юните. `opencodeAttachShim`
(`pkgs.writeShellScriptBin "opencode"`) кладётся первым в
`systemd.user.services.herdr.Service.Environment` под
`lib.mkIf config.programs.opencode.web.enable` и превращает голый
вызов в `opencode attach http://127.0.0.1:4096 --dir "$PWD"`. Реальные
подкоманды шим пропускает насквозь, resume после рестарта демона
(`opencode --session <id>`, src/agent_resume.rs) — в attach-with-session.
На rydiwo, где opencode.nix не импортирован, шим не ставится
(опция на default `false`).

Env (EnvironmentFile с OPENCODE_SERVER_USERNAME/PASSWORD и
GEMINI_API_KEY) тот же sops-файл, что у `opencode-web.service` —
`opencode attach` берёт basic-auth из env автоматически. systemd
НЕ разворачивает `$PATH` в `Environment=` (проверено на sapphira
2026-10-15: `PATH=/x:$PATH` хранится литералом), PATH выписан
целиком из реально существующих каталогов. R2 (Service ≠ serviceConfig)
соблюдён.

Доказательства (sapphira):
  • `nix build .#nixosConfigurations.sapphira.config.system.build.toplevel` — rc=0
  • отрендеренный herdr.service: `Environment=PATH=<shim>/bin:…`,
    `EnvironmentFile` и `ExecStart` не изменены
  • шим-перехват: `opencode --help` → attach help; `opencode serve --help` → passthrough
  • живой сервер: 3 сессии в opencode.db с `directory=/tmp/attach-smoke`
    созданы через `run/attach --attach`
  • `opencode attach` в pty держит связь

Документация (ADR-0006, T34): .agent/decisions/0006-herdr-shared-
opencode-serve.md. R1.16 в project-rules.md, инвариант 13 в AGENTS.md,
T34 в tasks/manifest.json. nixos-rebuild switch НЕ выполнен — на
ваше усмотрение после ревью.

Главный риск (открыто): opencode #55076 — общий сервер при resume
может не вернуть permissions/step-limits (та самая причина, по которой
предыдущая редакция herdr.nix обходила shared service). Митигация
лежит на сервере (OPENCODE_CONFIG_CONTENT cap или выделенный serve),
не в этом модуле. Мониторить; при рецидиве — менять на opencode-web
или поднимать выделенный.
2026-10-15 18:56:48 +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 999378a3a0 docs(agents): saga close-out — T18/T32 closed, T33 added, ADR-0005 maintenance procedure зафиксирована
test-runner / smoke (push) Canceled after 0s
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-15 15:55:55 +03:00
oqyude 2ab48515b9 fix(home): add nodejs_22 to herdr-runtime.nix (herdr-web-ui preflight)
test-runner / smoke (push) Canceled after 0s
После 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-15 15:33:33 +03:00
oqyude dfcd7f5728 feat(essentials): enable programs.nix-ld for generic-linux bun runtime
test-runner / smoke (push) Canceled after 0s
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-15 15:24:21 +03:00
oqyude 7f301765b5 refactor(home): extract pkgs.bun into herdr-runtime.nix, drop duplication
test-runner / smoke (push) Canceled after 0s
Раньше 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-15 15:07:54 +03:00
oqyude ffd85dc7f5 fix(home): add pkgs.bun to rydiwo home packages (herdr-web-ui runtime)
test-runner / smoke (push) Canceled after 0s
На сапфире 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-15 15:00:12 +03:00
oqyude fb36f78690 docs(agents): document deploy .#rydiwo as next physical action (T22 fix landed)
test-runner / smoke (push) Canceled after 0s
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-15 14:48:09 +03:00
oqyude 4bf8e552b4 docs(agents): sync R1.15, ADR-0005, T21-T32 from metaagent-director-2026-10-15
test-runner / smoke (push) Canceled after 0s
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-15 14:45:47 +03:00
oqyude 034bb5e632 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-15 14:45:35 +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 57182e2a4d agents(narrative): refresh project-state, handoff, roadmap
test-runner / smoke (push) Canceled after 0s
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-15 03:47:26 +03:00
oqyude 817e7c3d32 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-15 03:47:26 +03:00
oqyude ef8a355d00 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-15 03:47:26 +03:00
oqyude 5dd98b8525 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-15 03:47:25 +03:00
oqyude d021804cc7 secrets(gitea-runner): replace placeholder with real registration token
test-runner / smoke (push) Successful in 2s
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-15 00:28:57 +03:00
oqyude 3babee5392 opencode: remove opencode-loop plugin
test-runner / smoke (push) Successful in 1s
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-14 23:44:01 +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 f0b5a50e15 ci(gitea): re-trigger /tmp workspace
test-runner / smoke (push) Successful in 1s
2026-10-14 20:50:39 +03:00
oqyude 8726d1aae8 ci(gitea): workspace -> /tmp
test-runner / smoke (push) Successful in 5s
2026-10-14 20:43:48 +03:00
oqyude bf135b7817 ci(gitea): strace trigger
test-runner / smoke (push) Failing after 1s
2026-10-14 20:30:45 +03:00
oqyude cace6922ce ci(gitea): trigger after restart
test-runner / smoke (push) Failing after 1s
2026-10-14 20:19:59 +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 95166cee60 ci(gitea): re-trigger test-runner after workspace fix + token re-entry
test-runner / smoke (push) Failing after 0s
2026-10-14 20:06:09 +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 d554770dd8 ci(gitea): re-trigger after fixing mount
test-runner / smoke (push) Failing after 1s
2026-10-14 19:11:03 +03:00
oqyude 62d9ad23b9 ci(gitea): trigger test-runner workflow on push to dev
test-runner / smoke (push) Failing after 1s
2026-10-14 19:04:41 +03:00
oqyude 3186224d58 ci(gitea): add note so the next push triggers test-runner 2026-10-14 17:57:19 +03:00
oqyude b5cb99ff09 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-14 17:53:32 +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 d9a18fae3b secrets(gitea-runner): add sops placeholder for registration token 2026-10-14 16:19:19 +03:00
oqyude e8fc1f73e0 gitignore upd 2026-10-14 14:33:34 +03:00
oqyude 25baa2c503 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-14 14:32:08 +03:00
oqyude 7635df44e9 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-14 14:32:08 +03:00
oqyude 046a92700a 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-14 14:32:08 +03:00
oqyude ce1b0da32d 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-14 14:32:08 +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 13552039c7 opencode: opencode fix 2026-10-13 04:33:47 +03:00
oqyude a3c94906e9 feat(pxe-infra): boot VM from local image, not via iPXE sanboot
iPXE 2.0.0 reliably #GPs at RIP 0x7EE8A5FC (RAX=0xAF...AF) when handing off a 1-2 GB raw image back to the firmware under QEMU/OVMF, regardless of whether the boot primitive is sanboot, imgfetch+boot, or kernel+initrd+boot, regardless of iPXE binary (universal or snp-only), and regardless of VM memory (2G or 4G). The image itself is fine (kernel+initrd extract cleanly, BOOTX64.EFI is in the ESP, systemd-boot config is set up). The crash is in iPXE 2.0.0 `s exit-to-firmware path under this QEMU/OVMF combination.

Workaround: attach the Alpine worker image as a local virtio drive in the QEMU command line. The firmware (OVMF) finds BOOTX64.EFI in the image's ESP and boots the kernel from the image's ext4 partition. The network is still there (pxe0-tap, dnsmasq, nginx, report-sink), so the runner inside the guest can still POST to the report-sink and the VM can still talk to the L2/L3 services at runtime. The image attached is the same artifact nginx serves for the real PXE rig (the `latest` symlink at `artifacts.root/http/latest/`); deploy.sh keeps both paths in sync.

Refs: docs/ARCHITECTURE.md section L4.
2026-10-13 04:23:27 +03:00
oqyude e27eae9ae0 fix(pxe-infra): probe with kernel+initrd to isolate iPXE sanboot bug
All four attempts to sanboot the Alpine raw image through iPXE crash at the same RIP offset (0x35FC from the iPXE image base) regardless of memory (2G or 4G), iPXE binary (universal or snp-only), or image virtual size (2G or 1G). Common factor: all used sanboot to present the URL as a block device.

Replace boot.ipxe with iPXE's kernel/initrd/boot primitive. This bypasses sanboot and the SAN device creation path entirely. The kernel will fail to find a rootfs (no /dev/sda* is exposed) and panic — but kernel boot messages in the journal will tell us whether iPXE's kernel-initrd handoff works at all. If it does, the bug is isolated to the sanboot/SAN-device code path. If it also crashes, the bug is in shared iPXE code (HTTP download buffer management, probably).
2026-10-13 04:19:14 +03:00
oqyude 687d6d13f3 config(rydiwo): use snp.efi instead of universal ipxe.efi
The universal UEFI binary ipxe.efi (1.2 MB, all NIC drivers)
crashes at the same offset (0x35FC from the iPXE image
base) whether the VM has 2 GB or 4 GB of RAM, with
RAX = 0xAF...AF (iPXE uninit-memory fill). So this is not
OOM (the memory bump did not help) and not a NIC driver
issue (we use virtio-net, which the universal binary handles);
it is a deterministic bug somewhere in the sanboot/download
buffer path of the universal binary when the image is 2 GB.

snp.efi (310 KB, SNP-only — the driver virtio-net speaks)
is a separate iPXE build with a smaller code path: no UNDI,
no PXE prefix, no multi-NIC code. The same bug may not be
there, or the different code layout may avoid the bad
offset. Worth a try before reaching for GRUB or NFS root.

The opt-in is just bootloader.ipxeBinary = "snp.efi"; on
the pxe-infra attrset. The tmpfiles rule in
modules/pxe-infra/default.nix will symlink the new name
into the served TFTP root, and the next DHCP offer from
dnsmasq will hand it to the firmware.
2026-10-13 04:08:58 +03:00
oqyude 3154813d01 config(rydiwo): bump pxe-infra VM to 4G so iPXE can sanboot a 2G image
iPXE's sanboot for an HTTP URL needs to hold the entire image
in its own heap. The raw Alpine image is 2 GB; with the
default 2 GB VM RAM, iPXE's allocator runs out around the
2 GB mark, leaves uninitialised 0xAF...AF fill in the
fresh pages, and the firmware's next read from that area
raises #GP at RIP 0x7EE855FC with RAX = 0xAF...AF.

Bumping pxe-infra.vm.memory to 4G gives iPXE roughly 2G of
heap for the download, which is exactly what a 2G image
needs. The rest goes to OVMF firmware and friends.
2026-10-13 04:01:49 +03:00