20 Commits
Author SHA1 Message Date
oqyude 2980a8e9e8 backup: суточные дампы PostgreSQL на архивный диск, владелец тома — postgres
Симптом (ревью 2026-11-29): `postgresqlBackup` был выключен
(закомментированная строка), то есть единственной защитой живой БД оставалось
rsync-зеркало на тот же диск — копия, снятая с работающих файлов.

Решение владельца 2026-12-03: «через postgresql бэкапы как дополнительная
мера, на этот же диск, куда делается rsync зеркало». Зеркало остаётся.

Правка:
- `services.postgresqlBackup`: `enable`, `location =
  "/mnt/archive/postgresql"`, `startAt = "*-*-* 03:20:00"` (не 00:00, чтобы
  не совпадать с `rsync-archivesta`, у которого `OnCalendar = "daily"`),
  `compression = "zstd"`;
- юнит `postgresqlBackup`: `ConditionPathIsMountPoint`/`RequiresMountsFor`
  на `/mnt/archive` — якорь `mkStorageGuard` переопределён с server-home на
  архивный том, чтобы дамп не ушёл в пустой каталог на корневой ФС;
- `configurations/server.nix`: том `archive` монтируется с
  `ownerUid/ownerGid` пользователя postgres; `lib/xlib/helpers.nix:
  mkExfatMount` получил необязательные `ownerUid`/`ownerGid` (по умолчанию
  прежние uid/gid, остальные тома не меняются).

Почему владелец тома, а не права на каталог: exFAT не хранит uid/gid, они
задаются только опцией монтирования и действуют на все inode; `chmod`/
`chown` на exFAT молча возвращают 0 и ничего не меняют. Сервис работает под
пользователем `postgres` (так задано в модуле nixpkgs), поэтому при
`uid=1000` он не может ни создать каталог, ни открыть файл на запись.
Проверено на тестовом exFAT-образе (loop, mkfs.exfat): при uid/gid=postgres
каталог и дамп создаются, при uid=1000 — EACCES; `chown`/`chmod` на образе —
rc=0 без эффекта. Root (rsync-зеркало) от владельца тома не зависит.

Проверено (nix eval, sapphira):
- `services.postgresqlBackup` → `{enable:true, location:"/mnt/archive/postgresql",
  startAt:"*-*-* 03:20:00", compression:"zstd", backupAll:true}`;
- `systemd.services.postgresqlBackup` → `User=postgres`,
  `ConditionPathIsMountPoint=["/mnt/archive"]`,
  `RequiresMountsFor=["/mnt/archive"]`;
- `fileSystems."/mnt/archive".options` → `["nofail" "uid=71" "gid=71"
  "noauto" "x-systemd.automount"]`.
2026-12-03 15:31:45 +03:00
oqyude ae760f6ab4 домены: реестр xlib.net.domains + синхронизация webDomain 3x-ui (T63, ADR-0012)
nixos flake checks / invariant-checks (push) Successful in 1m44s
test-runner / smoke (push) Successful in 1s
- lib/xlib/net.nix: domains.public/opencodes/internal/ad; все живые
  хостнеймы выводятся из реестра (nginx, coredns, authelia, nextcloud,
  gitea, vds, netbird, open-webui, opencode, nix-cache). Литералы — только
  в комментариях/example/email/trusted-key и в БД панели.
- 3xui-domain-sync.service: before+wantedBy podman-3xui_app, идемпотентно
  приводит settings.webDomain к host."3x-ui".certDomain ДО старта панели
  (R1.19/инвариант 19); контейнер сам не перезапускает.
- config-fingerprint до/после: значения не изменились — 0 отличий на
  rydiwo/atoridu/wsl, на sapphira/otreca только новый юнит и unitConfig.
- epral: убран nginx-mainline из strictModule (nix-on-droid не вычислялся
  с 5712abb); в AGENTS.md исправлен вывод (build.activationPackage) и
  добавлен --impure — T64 (проверить сборку на устройстве).
- .agent: закрыты T10/T49/T50/T54, добавлены T63 (done) и T64 (pending),
  ADR-0012; phases в manifest.json синхронизированы с checkpoints.json.
2026-11-26 20:16:09 +03:00
oqyude d2692b752b archive: fsck тома уходит с пути загрузки (noauto + x-systemd.automount)
nixos flake checks / invariant-checks (push) Successful in 1m32s
test-runner / smoke (push) Successful in 1s
Замер 2026-11-24 (после обрыва питания): проверка ФС тома archive
(exfat, 466 ГБ, sda, метка archive) занимала 7 мин 15 с на КАЖДОЙ загрузке —
«Starting File System Check on /dev/disk/by-label/archive… 19:06:18» →
«Finished … 19:13:33», systemd-analyze: userspace 7min 13s, из них 7min 7s —
systemd-fsck@dev-disk-by\x2dlabel-archive.service. Том не держит ни один юнит
(lsof +f -- /mnt/archive пуст), он нужен «когда понадобится».

- lib/xlib/helpers.nix: mkExfatMount получил необязательный options ? [ ],
  который дописывается к nofail/uid=/gid=. Форма вызова у остальных
  потребителей не изменилась.
- configurations/server.nix: только для xlib.dirs.archive-drive —
  options = [ "noauto" "x-systemd.automount" ]. Проверка ФС НЕ отключена
  (noCheck не добавляем): она выполняется при ПЕРВОМ обращении к
  /mnt/archive — её запускает automount, а не путь загрузки. Том mobile
  намеренно не тронут, он грузится как раньше.

Проверено на sapphira: в /etc/fstab строка archive несёт noauto и
x-systemd.automount, строка mobile — нет; mnt-archive.automount active
(waiting), mnt-archive.mount inactive, реальный том не смонтирован (в findmnt
только autofs-заглушка); ls /mnt/archive поднимает том, mnt-archive.mount
показывает TriggeredBy: mnt-archive.automount; проверка ФС отработала при
первом обращении — 371 с (том чистый, но fsck.exfat читает 8.1 ГБ, поэтому
быстро не выходит — он теперь не на пути загрузки). Регрессий нет:
systemctl --failed пуст, /mnt/mobile, /mnt/services и /var/lib/calibre-web на
месте, /mnt/archive читается.
2026-11-24 19:51:03 +03:00
oqyude 0ab45578d1 refactor: реестр адресов флота lib/xlib/net.nix
Один адрес — одно имя. Раньше 192.168.1.20 был написан 41 раз, 100.64.0.0
— семь, а зона CoreDNS и vhost'ы nginx жили в разных файлах и разъезжались
(например, kuma.zeroq.su остался в DNS после отключения uptime-kuma).

Реестр: хосты (LAN/tailscale/public), публичные DNS, сети, общие порты.
Все хардкоды адресов флота переведены на xlib.net.*.

Намеренно не тронуто: 127.0.0.1 и 0.0.0.0 (константы языка, не топология),
сеть 10.66.0.0/24 (у PXE-инфраструктуры своя опционная поверхность) и
home/modules/opencode.nix (рабочая конфигурация агента владельца, её
рефакторинг запрещён ADR-0009).

Поведение не изменилось: config-fingerprint до/после совпадает по всем
шести хостам.
2026-11-15 06:34:12 +03:00
oqyude d6d64d21c3 treefmt + samba dir changed
nixos flake checks / invariant-checks (push) Failing after 7s
test-runner / smoke (push) Successful in 1s
2026-11-07 18:37:42 +03:00
oqyude 69691f96d1 fix(systemd): move the storage guard into [Unit] (T4/T52)
mkStorageGuard returned a serviceConfig fragment, so ConditionPathIsMountPoint
landed in [Service] where systemd ignores it - the guard was dead on 13 units.

- helper now returns a unitConfig fragment ([Unit]); RequiresMountsFor still
  intentionally absent
- consumers re-pointed at the real unit names: samba-smbd, phpfpm-nextcloud,
  immich-server, podman-3xui_app, podman-taperotation-{backend,frontend};
  the old serviceConfig keys silently rendered three empty phantom units
- vds excluded: otreca has no /home/oqyude/External and a live condition would
  skip podman-3xui_app and kill the 3x-ui panel at pubray1.zeroq.su

Verified: sapphira and otreca toplevel builds exit 0; all 13 units carry the
condition under [Unit] (line 3), zero occurrences under [Service].
2026-10-25 02:09:40 +03:00
oqyude 39e1887d78 docs(modules): уточнить пути и счётчики в комментариях
test-runner / smoke (push) Successful in 1s
nixos flake checks / invariant-checks (push) Canceled after 0s
- xlib: mkXlib из lib/xlib/default.nix (было lib/xlib.nix);
- архив: ../../archive/ от modules/server, 12+3 модуля;
- убраны устаревшие номера строк в ссылке на T16.

Проверки: PASS 3, FAIL 0; граф импортов 120 файлов, 119 ссылок.
2026-10-24 02:17:25 +03:00
oqyude d0df318553 feat(ci): add shellcheck to the ci tool set
test-runner / smoke (push) Successful in 0s
work/pxe-infra-automation is adding a Gitea Actions pipeline, and its
checks live in ci/check.sh: shellcheck over the build scripts AND over
the guest payload (image/*.sh, which is copied into the image verbatim),
plus a YAML validation of the workflow files.

That script exits 2 when shellcheck is missing, so on this runner —
where the job PATH is frozen into the systemd unit at activation time
and cannot gain a package without a nixos-rebuild — the linter has to
come from the ci devshell instead. shellcheck is now in lib/ci-tools.nix,
which is the single list both consumers use (the runner's hostPackages
and the devshell), so the two cannot drift apart.

PyYAML did NOT make it in: the obvious fix,
`python3.withPackages (ps: [ ps.pyyaml ])`, is not a valid buildInput
(nix rejects it with 'Dependency is not of a valid type: element N of
buildInputs'), and the devshell is the consumer that breaks. The
workflow YAML stays validated on GitHub and locally, where PyYAML is
present; the Gitea job says so in its log instead of pretending to have
checked it.

The nixos repo's own flake.lock pins nixpkgs; the pipeline uses that
revision instead of a floating nixos-unstable, because the nix registry
on sapphira is empty and 'nixpkgs#...' cannot resolve there.
2026-10-20 16:30:25 +03:00
oqyude 665f38a501 feat(ci): add the ci devshell with the Gitea runner tool set
test-runner / smoke (push) Successful in 1s
Раннер на sapphira отдаёт job'у PATH, равный своему hostPackages, и он
фиксируется в systemd-юните при активации -- чтобы добавить туда инструмент,
нужен nixos-rebuild switch на хосте. Для workflow'ов в oqyude/winos это тупик:
jq (scripts/update-manifest.sh) и pwsh (scripts/update-kvrt.ps1) в наборе
раннера отсутствуют, а nix-shell -p не запасной путь -- реестр nix на sapphira
пустой, каналов нет, -p не находит nixpkgs.

Что сделано:
- lib/ci-tools.nix -- один список инструментов CI.
- devshells/default.nix: devshell `ci` (nix develop .#ci) с этим списком.
  Workflow может взять PATH devshell'а и получить jq/pwsh без пересборки:
    nix develop /etc/nixos#ci --command bash -c 'echo $PATH'
- modules/server/gitea-runner.nix: hostPackages берёт тот же список, чтобы
  набор раннера и devshell не расходились; в списке теперь ещё и powershell.

Проверка: devshell собирается на sapphira (nix develop /etc/nixos#ci) и
отдаёт jq и pwsh.
2026-10-20 15:11:23 +03:00
oqyude 2727d88a12 fix(storage-guard): remove RequiresMountsFor — was causing auto-remount
CRITICAL BUG #2 in storage guard, caught by live test v8 on
sapphira (2026-10-10).

RequiresMountsFor=/home/ooyude/External in the unit file told systemd
that the service depends on the mount. When the mount was gone and
the service was started, systemd's dependency resolver AUTOMATICALLY
REMOUNTED the filesystem to satisfy the dependency — THEN checked
ConditionPathIsMountPoint. The condition saw the just-remounted
filesystem and evaluated to true. Service started on empty
external storage. Guard completely bypassed.

This is a subtle interaction:
- ConditionPathIsMountPoint is a TEST (true/false evaluation)
- RequiresMountsFor is a DEPENDENCY (systemd must make it true)

A guard should be a TEST, not a dependency that makes the test
trivially pass. Remove the dependency. The condition alone is
sufficient for both boot-time and runtime checks:

  - Boot: mount unit starts via local-fs.target, condition is true
  - Runtime: if mount disappears, condition becomes false on next
    start attempt. Without RequiresMountsFor, systemd doesn't
    auto-recover, so the guard fires.

Ordering should be expressed via After= in the consumer's
systemd.services block (not in the shared helper), e.g.:
  systemd.services.postgresql.after = [ "home-ooyude-External.mount" ];

Live test v8 sequence (before this fix):
  1. umount /home/ooyude/External  → OK, gone from /proc/mounts
  2. findmnt /home/ooyude/External → exit=1, not in table
  3. systemctl start postgresql     → STARTED (guard bypassed)
  4. journal: no ConditionPath error (service started successfully)

This is the second guard bug found by live testing in this session.
The first one was the '!' prefix inversion. Both were invisible to
nix eval, both only visible at runtime. Lesson reinforced:
guards MUST be live-tested, not just statically evaluated.

Recovery: v8 test reverted state via emergency_recovery trap
(remount + restart all services). System healthy at 10/10.
2026-10-10 16:31:41 +03:00
oqyude 2a1a30f08d fix(storage-guard): remove '!' from ConditionPathIsMountPoint
CRITICAL BUG FIX caught by live test v6 on sapphira.

The '!' prefix INVERTS the systemd test:
  ConditionPathIsMountPoint=!/path  → test passes if path is NOT a mount
                                     → unit STARTS when storage is unmounted
                                     → exactly the opposite of what we want

Correct semantics for a storage guard:
  ConditionPathIsMountPoint=/path   → test passes if path IS a mount
                                     → unit starts ONLY when storage is mounted
                                     → unit refuses to start when storage is gone

With the inverted condition, postgresql started on empty bind-mount
after lazy-umount of /home/oqyude/External — the exact silent-data-loss
scenario R1.2 is supposed to prevent.

This is the canonical 'bug the test caught' case. Live test v6 on
sapphira (2026-10-10) demonstrated: with '!' the guard does nothing,
without '!' the guard fires correctly.

Lesson: always run a live test of the guard, don't trust nix eval alone
for systemd Condition* semantics — they're evaluated by systemd at
runtime, and '!' inverts the test.
2026-10-10 15:51:12 +03:00
oqyude 61b3724752 metaagent: Wave 1 + T4 + T7 + T3 + T5 + T15 + T16 — 12 tasks of tech-debt reduction
Comprehensive batch addressing the 16-task backlog in
.agent/tasks/manifest.json. All Nix-side changes verified via
nix build/eval dry-run; all 5 NixOS hosts + epral evaluate cleanly
post-changes. No regressions.

Wave 1 (non-functional cleanup):

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

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

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

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

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

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

T4 (storage guard, FUNCTIONAL CHANGE):

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

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

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

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

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

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

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

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

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

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

T5/B2 (backups documentation):

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

T15/E2 (CI checks):

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

T16/E3 (archive commented modules):

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

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

  Verified: nixosConfigurations.sapphira still evaluates.

Post-change state:

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

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

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

Untracked files NOT committed (in .gitignore):

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

Also untracked, committed:

  .agent/reviews/2026-10-10-review-dev-diff-vs-16644fc.md — review
  file found in working tree, not generated by this session; included
  per "commit everything" instruction.
2026-10-10 15:15:22 +03:00
oqyude f3c50e90ba authelia in services 2026-10-09 16:37:03 +03:00
oqyude b2718fd1e7 xlib+users: centralize opencode server.env path
The path '/home/<user>/.config/opencode/server.env' was duplicated
between users.nix (sops materialization) and home/modules/opencode.nix
(programs.opencode.web.environmentFile). Drift between the two was a
silent auth-bypass vector: if one moved, the systemd unit would either
fail to find OPENCODE_SERVER_PASSWORD or skip EnvironmentFile entirely.

Single source in lib/xlib/dirs.nix; both call sites now read from it.
2026-10-07 11:36:55 +03:00
oqyude 509fd3dde0 kokoro-tts 2026-10-03 01:03:50 +03:00
oqyude 958247b22c soft coding 2026-10-02 23:05:00 +03:00
oqyude c05cc88843 restructuring 2026-10-01 15:14:37 +03:00
oqyude d49fd5a358 big refactoring 2026-10-01 14:16:17 +03:00
oqyude 411c118500 br v4 2026-08-11 22:13:53 +03:00
oqyude 871fad26d4 big refactoring 2026-08-11 02:31:00 +03:00