Предыдущая редакция (коммит 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: новый раздел «Двухслойная
схема» с эмпирическим сценарием и командами теста.
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
или поднимать выделенный.
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 после «проверяться.»
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).
Also fixes R1 numbering: two items were both labelled '8', so reality443Forwarding counted as ninth while AGENTS.md, traps and f2e70bb already referenced it as R1.10. Verification commands were executed against the live host: '{{json .Ports}}' and 'exec xray version' both fail, corrected to .NetworkSettings.Ports and /app/bin/xray-linux-amd64.
AGENTS.md + project-rules.md trap entries updated: reality443Forwarding
is NOT a 'lost-purpose' option, it is REQUIRED on VDS. The nginx stream
(modules/vds/nginx.nix) routes 443 → 127.0.0.1:15380 → container:443;
removing the option breaks Xray REALITY while SSH and the panel keep
working (which is exactly what the owner observed).
New invariant R1.10 in project-rules.md. T10 manifest entry stays
'pending' pending a proper decision record.
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).