Compare commits

..

71 Commits

Author SHA1 Message Date
Fabio Scotto di Santolo
1a9ecffecf Install Codex and Cline CLI on WSL workstation
Enable Codex and the Cline CLI on deadalus alongside Claude Code, and
stop selecting Codex for removal. Cline's cross-tool instructions and
shared context remain deployed for the devcontainer bind mounts.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-24 15:47:41 +01:00
012cb3534b Install agent CLIs and VS Code extensions in generated devcontainers
The nvm-based node feature put npm outside sudo secure_path and broke the postCreateCommand, so containers with agents now copy Node from the official docker.io/library/node image into /usr/local in every profile. Each selected agent also adds its official VS Code extension to the customizations and the generator captures every extension installed in the local VS Code through code --list-extensions, deduplicated case-insensitively and sorted at generation time.
2026-11-19 00:39:17 +01:00
47acda71b6 Manage VS Code user settings on GNOME hosts
Deploy the full user settings.json as an explicit overlay with a timestamped backup: podman as the Dev Containers engine, the Container Tools clients, the corrected JetBrainsMono Nerd Font editor font, the block cursor and format on paste. Add the material icon theme extension the managed icon theme depends on and drop the deprecated ms-azuretools.vscode-docker pack, which since June 2025 only wraps Container Tools.
2026-11-19 00:39:01 +01:00
Fabio Scotto di Santolo
e74088e85b Deploy devcontainer generator to user local bin with Ansible 2026-11-18 23:13:32 +01:00
Fabio Scotto di Santolo
e2370ec91d Replace Python devcontainer generator with Go CLI 2026-11-18 23:13:30 +01:00
Fabio Scotto di Santolo
59160abf0d Add reusable project devcontainer generator 2026-11-18 23:13:28 +01:00
cdc102a970 Prohibit AI names as Git co-authors in the shared agent context
Add the rule to the always-applied safety directives and make the dispatcher reference safety.md so Codex and Claude Code, which import only the dispatcher, apply it as well.
2026-11-18 22:52:50 +01:00
66925b1d0d Share Cline configuration with the ecaas and cdp devcontainers
Keep Cline deploy-only on deadalus so its rules, the cross-tool AGENTS pointer and the shared ~/.config/ai context are deployed on the WSL host; mount ~/.agents into the containers; list the Cline VS Code extension in the devcontainer customizations. The CLI package stays absent on the host and ships in the images.
2026-11-18 22:52:47 +01:00
3facf61866 Add Desktop Plus and pin it in the Ikaros favorites 2026-11-18 22:52:43 +01:00
0b30890464 Update the GNOME shell extension list on Ikaros
Capture the current live session: enable gnome-shell-extension-maximized-by-default and disable the unused maximize-new-windows entry.
2026-11-18 22:52:37 +01:00
ffa9960c64 Reuse verified Nextcloud bundles within 20h before Borg/USB backups 2026-11-15 22:12:50 +01:00
7b85314cca Update favorite apps on Ikaros 2026-11-15 07:21:02 +01:00
95630f74d3 Extend the GNOME search provider sort order on Ikaros 2026-11-14 23:06:05 +01:00
Fabio Scotto di Santolo
a2dca0e0d1 Merge branch 'wsl-claude-only-agent' 2026-11-13 11:07:25 +01:00
Fabio Scotto di Santolo
269f08a332 Keep only Claude Code as the WSL coding agent
Disable install and deploy and select removal for OpenCode, Codex,
Gemini CLI, Cline, and IBM Bob on deadalus. Expose the OpenCode and
IBM Bob lifecycle flags in group_vars so host overrides can control
them like the other agents.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-13 10:23:39 +01:00
3f3781437b Prefer grouping similar Ansible tasks into looping list variables
Record in both the shared Ansible rules (~/.config/ai/rules/ansible.md)
and the repo Conventions that similar tasks should be declared as list
variables, typically in group_vars, and applied by a single task looping
over the list instead of near-identical one-per-item tasks.

Co-Authored-By: Cline <noreply@anthropic.com>
2026-11-12 23:06:14 +01:00
52c3615d26 Replace Git Flow with trunk-based development
main is the single long-lived branch: land small validated changes fast,
either through direct commits or short-lived branches merged as soon as
validation passes. Do not keep release/ or support/ lines; tag releases
from the trunk and fix production issues on the trunk itself.

Co-Authored-By: Cline <noreply@anthropic.com>
2026-11-12 23:06:02 +01:00
4df3067c38 Bind Cline to the shared AI context through global rules
Add dotfiles/common/.cline/rules/ai-context.md as an always-on global rule that
Cline auto-loads from ~/.cline/rules/ and deploy it through ai_agents_dotfiles
behind cline_deploy_enabled. The rule points at the deployed bootstrap.md,
safety directives, task dispatcher, and the distilled ChatGPT knowledge under
memory/chatgpt/, keeping ~/.config/ai/ the single source of truth. Also add
cline to the AI common config agent list so the shared context is deployed
for Cline-only hosts as well.

Co-Authored-By: Cline <noreply@anthropic.com>
2026-11-12 23:05:53 +01:00
Fabio Scotto di Santolo
94eb555ff3 Merge branch 'feature/vscode-keybindings-devcontainer-history' 2026-11-11 19:04:46 +01:00
Fabio Scotto di Santolo
25a3b97b14 Persist Bash history in WSL devcontainers
Mount a per-devcontainer history directory from the WSL host and point
HISTFILE at it so shell history survives container rebuilds.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-11 19:04:19 +01:00
Fabio Scotto di Santolo
e8db4e5f38 Manage VS Code keybindings for GNOME desktops
Deploy user-level keybindings.json from vscode_keybindings so Alt+J
toggles the terminal and the panel from the terminal. Keys avoid
Ctrl+<letter> to leave Vim motions untouched.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-11 19:04:18 +01:00
Fabio Scotto di Santolo
2cadbf25eb Merge branch 'feature/wsl-devcontainers-remove-mise' 2026-11-10 16:26:54 +01:00
Fabio Scotto di Santolo
d26dddd822 Remove mise from WSL and tidy devcontainer tooling
- Drop mise installation, COPR repository, pinned tool checks and
  dotfiles from the Fedora WSL profile; keep the Maven pin for the
  devcontainers as workstation_maven_version.
- Remove the Claude Code and Cline VS Code extensions from the
  devcontainer definitions; the CLIs and their mounts remain.
- Add the cdp and ecaas devcontainer definitions and their docs.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-10 16:26:06 +01:00
0bd0a4589b Document the shared AI memory and Cline wiring 2026-11-09 22:41:54 +01:00
bc01cd3863 Wire Cline, Codex, OpenCode, and Claude to the shared AI context 2026-11-09 22:41:54 +01:00
9bc8e9bf72 Import ChatGPT conversation memory into the shared AI context 2026-11-09 22:41:54 +01:00
4041af0799 Add ChatGPT export conversion script for shared agent memory 2026-11-09 22:41:54 +01:00
Fabio Scotto di Santolo
4bd3c21295 Fix ecaas path 2026-11-09 12:20:12 +01:00
f09a708fe9 Add lifecycle flags for AI desktop applications
Manage ChatGPT Desktop, OpenCode Desktop, and Cline Desktop with the same install/uninstall lifecycle pattern used by the CLI coding agents: independent flags per app, a shared ai_desktop_apps map, a common pre-task that rejects conflicting install/uninstall pairs, and explicit install and removal task flows.

ChatGPT opts in per host through chatgpt_desktop_install_enabled, Cline opts in through the desktop_gnome group vars, and OpenCode Desktop keeps removal selected so the retired opencode RPM and every cached download converge away on graphical hosts. Removal never touches user data, GNOME favorites, or the npm-managed CLI counterparts.
2026-11-08 22:02:17 +01:00
ccb4a0daa6 Replace OpenCode Desktop with Cline and add ecaas devcontainer setup 2026-11-08 21:30:41 +01:00
695fdf4711 Remove opencode-mobile npm installation 2026-11-07 23:31:16 +01:00
08728f45a1 Fix media mount permissions and update Fedora 45 packages 2026-11-07 23:18:01 +01:00
da13299a8a Configure Codex removal on WSL 2026-11-07 09:17:59 +01:00
da5742e1e1 Add encrypted media volume controls and tolerate unavailable HEIC builds 2026-11-06 08:25:53 +01:00
5e62a02feb Configure GNOME favorites and VS Code extensions 2026-11-05 08:53:03 +01:00
ada83e97d3 Manage native VS Code on Fedora GNOME 2026-11-04 23:11:24 +01:00
667f55b87b Remove explicit Codex model selection 2026-11-04 22:57:32 +01:00
69196460c9 Configure Go workspace for Fedora Bash 2026-11-04 22:57:13 +01:00
e4e99d2a2f Fix ai-media automount 2026-11-04 08:44:59 +01:00
775840d3ef Mount ai-media storage on demand from the Backup volume 2026-11-03 23:31:29 +01:00
bde34e19f4 Remove AI agents (Gemini, Codex Relay and Github Copilot) 2026-11-01 23:35:17 +01:00
849e522287 Preserve Thunderbird profiles and add OpenCode Mobile support 2026-11-01 20:17:00 +01:00
1e40a867e7 Provision the iCloud Thunderbird profile on GNOME desktops
Seed a Thunderbird profile on ikaros and nymph with the iCloud account
already declared: IMAP imap.mail.me.com:993 over SSL/TLS, SMTP
smtp.mail.me.com:587 over STARTTLS, identity and folder mapping, one
CalDAV calendar and one CardDAV address book.

Account defaults are rendered into a managed user.js because Thunderbird
rewrites prefs.js on exit, while user.js is re-applied at every start.
profiles.ini is seeded only when absent so a profile list Thunderbird
already owns is never replaced.

The address comes from vault_icloud_email and the display name from
vault_personal_full_name. The app-specific password is deliberately not
stored: Thunderbird requests it on first use and keeps it in its own
credential store.

Validated by rendering the templates and running Thunderbird 158 headless
against a sandbox profile: the account was accepted, Local Folders was
created by Thunderbird itself, the CalDAV calendar registered as default
and the CardDAV directory instantiated its abook-icloud.sqlite.
2026-11-01 19:30:10 +01:00
4e8665a7d4 Merge pull request #18 from fscotto/feature/gnome-desktop-config
feature/gnome desktop config
2026-11-01 19:09:06 +01:00
146c93c6c6 Deploy the Nextcloud desktop autostart entry on GNOME desktops
Add the XDG autostart entry captured from ikaros' live session and ship
it through a new desktop_gnome_dotfiles list, which the GNOME dotfile
copy task merges with desktop_common_dotfiles.

The list is GNOME-specific on purpose: desktop_common_dotfiles is shared
with the Void minimal desktops, where nextcloud-client is not installed.
Installation itself already comes from fedora_desktop_packages, which
covers ikaros and nymph through the graphical_desktop group.
2026-11-01 19:07:48 +01:00
57c34a6de0 Remove Proton Mail Bridge autostart and app-grid entry
Drop the XDG autostart entry from the desktop dotfiles and the
ch.protonmail.protonmail-bridge.desktop item from ikaros' managed
app-picker-layout, renumbering the remaining positions in that group.

The `XDG autostart entries` item also leaves desktop_common_dotfiles:
with the only file removed, git no longer tracks .config/autostart, so
the shared copy task would fail on a missing source directory. The
directory is still created by the profile roles.

The live ikaros session was updated with the same layout. Bridge support
in scripts/bootstrap_mail.sh and the installed flatpak are unchanged.
2026-11-01 19:07:43 +01:00
7928ff3825 Align ikaros GNOME gsettings with the live session
Capture two preferences changed interactively on ikaros so the declared
state matches reality:

- org.gnome.nautilus.preferences default-folder-viewer is now 'icon-view'
- org.gnome.shell favorite-apps includes ai.opencode.desktop.desktop after
  chatgpt.desktop

Verified all 79 declared keys against `gsettings get` in the running
session: no remaining differences.
2026-11-01 19:07:37 +01:00
90fe7a1671 Merge pull request #17 from fscotto/feature/opencode-desktop
Install pinned OpenCode Desktop on Fedora GNOME desktops
2026-11-01 18:04:38 +01:00
f6ef70a43f Install pinned OpenCode Desktop on Fedora GNOME desktops
Add an opencode_desktop task file to packages_fedora that downloads the
official RPM, verifies a pinned per-architecture SHA-256, and installs it
with DNF. Upstream RPMs are unsigned, so only that task disables GPG
checking; system repository signature policy is unchanged.

Gate the tasks on graphical_desktop plus opencode_desktop_enabled, which
desktop_gnome enables for ikaros and nymph. WSL, Fedora IoT, Void, and
servers stay untouched, and the npm-managed OpenCode CLI keeps its own
configuration and lifecycle flags.

Pin version 2.2.5 with x86_64 and aarch64 digests, and document the
opencode_desktop tag, the cold-cache check-mode limitation, and why the
official download page must confirm the version.
2026-11-01 17:59:14 +01:00
5d5339637d Fix git_work_email in the vault 2026-11-01 10:56:17 +01:00
92a05e1f36 Merge branch 'feature/ai-media-presets' into main 2026-11-01 10:54:16 +01:00
740a3571a6 Update encrypted Ansible vault 2026-11-01 10:36:08 +01:00
6f6dabd532 Document the existing Atlas Gitea container registry 2026-11-01 10:36:08 +01:00
e48b0dce3d Add offline ai-media presets for video and audio workflows 2026-11-01 10:36:07 +01:00
Fabio Scotto di Santolo
8b13e63a35 fix(workstation): configure Gpg4win pinentry 2026-10-29 10:00:12 +01:00
Fabio Scotto di Santolo
272667a20d Manage Claude Code on WSL and retry npm installs 2026-10-28 09:26:58 +01:00
393b633103 Change GPG sign 2026-10-26 20:07:25 +01:00
Fabio Scotto di Santolo
e29b3ed8b4 Fix yt-dlp video download directory 2026-10-25 16:42:58 +01:00
Fabio Scotto di Santolo
7b6d5396ab Add local AI media tools for Fedora desktop 2026-10-25 16:42:58 +01:00
Fabio Scotto di Santolo
479b60f270 Fix effective ACL mask for writable Nextcloud storage 2026-10-25 16:42:58 +01:00
Fabio Scotto di Santolo
45d6e7e3ee Replace Evolution with Thunderbird in desktop profiles 2026-10-25 16:42:57 +01:00
Fabio Scotto di Santolo
d658fb6595 Add rootless Paperless-ngx service to Atlas 2026-10-13 17:54:59 +02:00
Fabio Scotto di Santolo
ed2cd1acd5 Rename the iCloud external mount to Photos 2026-10-11 09:27:26 +02:00
Fabio Scotto di Santolo
d9cee2effe Add private aria2 RPC gateway for authenticated public access 2026-10-10 16:57:34 +02:00
Fabio Scotto di Santolo
5ebf1c1eb6 Add LAN-only aria2 downloads to Atlas 2026-10-10 16:00:44 +02:00
Fabio Scotto di Santolo
5f3792d603 Prepare qBittorrent for reverse proxy access 2026-10-10 14:05:47 +02:00
Fabio Scotto di Santolo
c8df4dde87 Add Atlas qBittorrent service configuration 2026-10-10 13:49:55 +02:00
Fabio Scotto di Santolo
7d80c57570 Add Nextcloud client to GNOME desktop packages 2026-10-10 13:35:26 +02:00
Fabio Scotto di Santolo
7db322039e Enable HEIC previews and document Nextcloud recovery 2026-10-06 20:05:42 +02:00
Fabio Scotto di Santolo
bb67c406da Hide ONLYOFFICE welcome and example endpoints 2026-10-04 17:10:55 +02:00
Fabio Scotto di Santolo
9f95e68190 Integrate consistent Nextcloud backups and recovery 2026-10-04 17:00:48 +02:00
219 changed files with 176484 additions and 325 deletions

View File

@@ -6,9 +6,10 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
- Main orchestration: `ansible/site.yml` - Main orchestration: `ansible/site.yml`
- Inventory and layering inputs: `ansible/inventory/hosts.yml`, `ansible/inventory/group_vars/*.yml`, `ansible/inventory/host_vars/*.yml` - Inventory and layering inputs: `ansible/inventory/hosts.yml`, `ansible/inventory/group_vars/*.yml`, `ansible/inventory/host_vars/*.yml`
- Dotfiles live under `dotfiles/` - Dotfiles live under `dotfiles/`
- AI agent instructions (bootstrap, rules, knowledge) are centralized in `dotfiles/common/.config/ai/` and shared between OpenCode, Codex, and Gemini CLI. - AI agent instructions (bootstrap, dispatcher, knowledge, rules, patterns) are centralized in `dotfiles/common/.config/ai/` and shared between OpenCode, Codex, Gemini CLI, and Cline.
- OpenCode loads its entrypoint configuration from `dotfiles/common/.config/opencode/opencode.json`. - OpenCode loads its entrypoint configuration from `dotfiles/common/.config/opencode/opencode.json`; Codex global instructions deploy from `dotfiles/common/.codex/AGENTS.md`; Cline deploys both the cross-tool `dotfiles/common/.agents/AGENTS.md` pointer (to `~/.agents/AGENTS.md`) and the always-on global rule `dotfiles/common/.cline/rules/ai-context.md` (to `~/.cline/rules/`), which auto-binds the deployed `bootstrap.md`, dispatcher, safety directives, and distilled ChatGPT knowledge.
- Codex config is rendered from `dotfiles/common/.codex/config.toml.j2` so `model_instructions_file` points to the deployed `~/.config/ai/bootstrap.md`. - Codex config is rendered from `dotfiles/common/.codex/config.toml.j2` so `model_instructions_file` points to the deployed `~/.config/ai/bootstrap.md`.
- ChatGPT conversation memory is stored in `dotfiles/common/.config/ai/memory/chatgpt/` and regenerated incrementally by `scripts/chatgpt_export_to_memory.py` from an official ChatGPT data export.
## Topology ## Topology
- Current personal desktop: `ikaros = platform_fedora + role_personal_workstation + graphical_desktop + desktop_gnome` - Current personal desktop: `ikaros = platform_fedora + role_personal_workstation + graphical_desktop + desktop_gnome`
@@ -28,9 +29,10 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
- Keep completed one-time cleanup operations out of the playbook. Execute them directly - Keep completed one-time cleanup operations out of the playbook. Execute them directly
with explicit authorization; retain only the ongoing desired-state configuration and with explicit authorization; retain only the ongoing desired-state configuration and
historical documentation, not permanent cleanup flags or tasks. historical documentation, not permanent cleanup flags or tasks.
- Use Git Flow branch prefixes: `feature/` for new functionality, `bugfix/` for non-urgent fixes, - Use trunk-based development: `main` is the single long-lived branch. Land small,
`hotfix/` for urgent production fixes, `release/` for release preparation, and `support/` for validated changes quickly, either as direct commits or via short-lived branches merged
maintained release lines. Do not use abbreviated prefixes such as `feat/`. as soon as validation passes. Do not maintain `release/`, `support/`, or other
long-lived branch lines: tag releases from the trunk and fix production issues on it.
- Desktop and WSL hosts use `ansible_connection: local`; remote infrastructure hosts use SSH. - Desktop and WSL hosts use `ansible_connection: local`; remote infrastructure hosts use SSH.
- Treat `secrets/` as sensitive. Never print secret values. - Treat `secrets/` as sensitive. Never print secret values.
- Tmux plugins are bootstrapped by TPM on the host; the repo only keeps tmux config and custom helper scripts. - Tmux plugins are bootstrapped by TPM on the host; the repo only keeps tmux config and custom helper scripts.
@@ -56,7 +58,9 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
- Focused checks: - Focused checks:
- Emacs is disabled by default; temporary Emacs check: `ansible-playbook ansible/site.yml --limit <host> --tags emacs --check --diff -e emacs_enabled=true` - Emacs is disabled by default; temporary Emacs check: `ansible-playbook ansible/site.yml --limit <host> --tags emacs --check --diff -e emacs_enabled=true`
- AI coding agents: `ansible-playbook ansible/site.yml --limit <host> --tags ai_agents --check --diff` - AI coding agents: `ansible-playbook ansible/site.yml --limit <host> --tags ai_agents --check --diff`
- AI desktop apps lifecycle: `ansible-playbook ansible/site.yml --limit ikaros --tags chatgpt,opencode_desktop,cline_desktop --check --diff`
- Mail bootstrap: `sh -n scripts/bootstrap_mail.sh` and `shellcheck scripts/bootstrap_mail.sh` - Mail bootstrap: `sh -n scripts/bootstrap_mail.sh` and `shellcheck scripts/bootstrap_mail.sh`
- Thunderbird iCloud profile: `ansible-playbook ansible/site.yml --limit ikaros --tags thunderbird --check --diff`
- Server NPM Quadlet: `systemctl status prometheus-npm.service`; the Compose fallback is retired. - Server NPM Quadlet: `systemctl status prometheus-npm.service`; the Compose fallback is retired.
- Explicit Prometheus legacy cleanup (destructive only without check mode): - Explicit Prometheus legacy cleanup (destructive only without check mode):
`ansible-playbook ansible/site.yml --limit prometheus --tags server_legacy_cleanup --check --diff -e server_legacy_cleanup=true` `ansible-playbook ansible/site.yml --limit prometheus --tags server_legacy_cleanup --check --diff -e server_legacy_cleanup=true`
@@ -68,6 +72,8 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
`ansible-playbook ansible/site.yml --limit atlas --tags gitea_public_domain --check --diff` `ansible-playbook ansible/site.yml --limit atlas --tags gitea_public_domain --check --diff`
- Atlas Nextcloud/ONLYOFFICE steady state: - Atlas Nextcloud/ONLYOFFICE steady state:
`ansible-playbook ansible/site.yml --limit atlas --tags nextcloud --check --diff` `ansible-playbook ansible/site.yml --limit atlas --tags nextcloud --check --diff`
- Atlas recurring consistent Nextcloud backup preparation:
`ansible-playbook ansible/site.yml --limit atlas --tags nextcloud_backup,monitoring --check --diff`
- Atlas iCloudPD storage and boot-started Quadlet: - Atlas iCloudPD storage and boot-started Quadlet:
`ansible-playbook ansible/site.yml --limit atlas --tags icloudpd --check --diff` `ansible-playbook ansible/site.yml --limit atlas --tags icloudpd --check --diff`
- Ongoing Gitea proxy configuration: - Ongoing Gitea proxy configuration:
@@ -99,6 +105,8 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
- Prefer declarative modules over `command`/`shell`; when `shell` is required, make idempotency and failure behavior explicit. - Prefer declarative modules over `command`/`shell`; when `shell` is required, make idempotency and failure behavior explicit.
- Start YAML files with `---`, use 2-space indentation, and keep file modes quoted like `"0644"`. - Start YAML files with `---`, use 2-space indentation, and keep file modes quoted like `"0644"`.
- Keep booleans as booleans and structured vars as YAML lists/maps. - Keep booleans as booleans and structured vars as YAML lists/maps.
- Group similar tasks into list variables (typically in `group_vars`) and apply them
with a single task looping over the list, rather than one near-identical task per item.
- Put host-specific overrides in `host_vars`, not shared `group_vars`. - Put host-specific overrides in `host_vars`, not shared `group_vars`.
- Use `no_log: true` for secret-bearing task inputs or outputs. - Use `no_log: true` for secret-bearing task inputs or outputs.
@@ -114,6 +122,7 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
- `dotfiles/desktop/.config/niri/config.kdl` and `session-env` deployed via `desktop_niri_dotfiles` (Niri / Wayland) - `dotfiles/desktop/.config/niri/config.kdl` and `session-env` deployed via `desktop_niri_dotfiles` (Niri / Wayland)
- Void Niri lives in `profile_desktop_niri`, gated on `'niri' in desktop_sessions_enabled`; it installs the `emptty` `niri.desktop` session, the `/usr/local/bin/start-niri` launcher, and the xdg-desktop-portal config, mirroring `profile_desktop_sway`. - Void Niri lives in `profile_desktop_niri`, gated on `'niri' in desktop_sessions_enabled`; it installs the `emptty` `niri.desktop` session, the `/usr/local/bin/start-niri` launcher, and the xdg-desktop-portal config, mirroring `profile_desktop_sway`.
- Fedora GNOME (`desktop_gnome`) assumes GNOME comes from the Fedora Workstation base install; Ansible deploys shared desktop dotfiles and git/GPG config for `ikaros` and `nymph`, not GNOME settings. - Fedora GNOME (`desktop_gnome`) assumes GNOME comes from the Fedora Workstation base install; Ansible deploys shared desktop dotfiles and git/GPG config for `ikaros` and `nymph`, not GNOME settings.
- `profile_desktop_gnome` first discovers configured Thunderbird accounts in both `~/.thunderbird` and `~/.config/thunderbird` and selects an existing profile without changing its account settings. Only if no account exists does it seed a new iCloud IMAP/SMTP profile with CalDAV and CardDAV through a non-overwriting `user.js`. Registry changes preserve other profiles and create backups; Thunderbird must be closed. The bootstrap address comes from `vault_icloud_email` and the app-specific password is never stored by Ansible.
- Do not switch or restart the display manager during a playbook run from an active graphical session. - Do not switch or restart the display manager during a playbook run from an active graphical session.
- `nymph` is the Fedora/GNOME laptop target; keep GNOME settings unmanaged for now and add host-specific tuning only after real use. - `nymph` is the Fedora/GNOME laptop target; keep GNOME settings unmanaged for now and add host-specific tuning only after real use.
@@ -132,7 +141,6 @@ The dotfile vars follow the same split: `desktop_common_dotfiles` carries mode-i
## Workstation Notes ## Workstation Notes
- `deadalus` is modeled as Windows + Fedora WSL and is the sole workstation target. - `deadalus` is modeled as Windows + Fedora WSL and is the sole workstation target.
- Fedora WSL belongs to `platform_fedora`, `workstation_dev_fedora`, and the shared WSL layer. It must not receive Flatpak or Snap runtimes. - Fedora WSL belongs to `platform_fedora`, `workstation_dev_fedora`, and the shared WSL layer. It must not receive Flatpak or Snap runtimes.
- Fedora WSL installs Mise from the official `jdxcode/mise` COPR and uses its pinned Temurin Java 11 JDK; update the declared Mise version deliberately.
- Windows applications are installed manually and are not managed from the WSL profile. - Windows applications are installed manually and are not managed from the WSL profile.
## Rocky Server Notes ## Rocky Server Notes
@@ -202,6 +210,39 @@ The dotfile vars follow the same split: `desktop_common_dotfiles` carries mode-i
when it is assigned. After a firewalld reload, restore Prometheus' rootful Podman networking with when it is assigned. After a firewalld reload, restore Prometheus' rootful Podman networking with
`podman network reload --all` so the existing proxy stack retains container DNS. `podman network reload --all` so the existing proxy stack retains container DNS.
- Atlas qBittorrent is selected by `atlas_manage_qbittorrent` and managed with the
`qbittorrent` tag as the admin-owned rootless `atlas-qbittorrent.service` Quadlet.
Its Web UI is `http://192.168.178.55:8090` on the LAN and prepared for the manual
NPM HTTPS domain `torrent.fscotto.co`, trusting only Aegis for forwarded client
addresses. DNS and NPM configuration stay manual. Configuration lives in
`services/data/qbittorrent`, and only `Archive/Downloads` is writable as payload
storage. It uses the home Internet connection, not WireGuard or a VPN; no router
forwarding or published torrent peer port is configured. See `docs/atlas-qbittorrent.md`.
- Atlas HTTP downloads use the admin-owned rootless `atlas-aria2.service` and
`atlas-ariang.service` Quadlets, gated by `atlas_manage_aria2` and the `aria2` tag.
AriaNg binds the LAN at `http://192.168.178.55:8091`; direct RPC is LAN-only on TCP/6800
and requires a private target-generated token. State lives in `services/data/aria2`,
with payloads in `Archive/Downloads`; do not expose RPC through the existing
qBittorrent `torrent.fscotto.co` endpoint. Public `downloads.fscotto.co` uses
a manual NPM Access List for both UI and `/jsonrpc`. The `aria2_gateway` tag
manages an admin user service on TCP/8092, accessible only through Aegis,
injecting the private token for JSON-RPC POST clients; keep this route
authenticated and never expose the gateway directly. See `docs/atlas-aria2.md`.
- Atlas Nextcloud backup preparation (`atlas-nextcloud-backup.service`) is an ordered
requirement of the nightly `atlas-borg-backup.service` and the operator-started
`atlas-usb-backup.service`. A structurally complete bundle younger than
`atlas_nextcloud_backup_reuse_max_seconds` (20 h, asserted below 24 h so the nightly
Borg cycle always refreshes it) is reused without pausing the applications: a manual
USB run therefore reaches its LUKS prompt within seconds, while preparation failure
still blocks the dependent job. Force one fresh preparation with
`systemctl set-environment ATLAS_NEXTCLOUD_BACKUP_FORCE=1` before the start and unset
the variable afterwards. Deployed and validated on 2026-11-15: a dependency start reused
a verified bundle 14 h old and skipped preparation in 14 ms, and an operator-started
USB run reached its LUKS prompt in under a second; the FORCE path has not been exercised
in production yet. See `docs/atlas-nextcloud.md`.
## Atlas NAS TODO ## Atlas NAS TODO
Completed validation: the existing RAIDZ2 pool and datasets, SELinux, LAN firewall, SSH, Cockpit with Completed validation: the existing RAIDZ2 pool and datasets, SELinux, LAN firewall, SSH, Cockpit with
the selected 45Drives plugins, encrypted SMB3 `Archive`, the Aegis-only NFSv4 `photobook` export, and the the selected 45Drives plugins, encrypted SMB3 `Archive`, the Aegis-only NFSv4 `photobook` export, and the
@@ -210,15 +251,17 @@ and TCP reachability to Atlas were verified. Temporary Navidrome and Syncthing a
manual NPM Proxy Hosts; Syncthing uses `/data/Org` backed by the SMB-shared Archive dataset. Aegis has also manual NPM Proxy Hosts; Syncthing uses `/data/Org` backed by the SMB-shared Archive dataset. Aegis has also
validated NFSv4.2 read, write, delete, and `all_squash` mapping to UID/GID `1100` end-to-end. The ZFS validated NFSv4.2 read, write, delete, and `all_squash` mapping to UID/GID `1100` end-to-end. The ZFS
snapshot timers are active; a recursive hourly snapshot and scheduled retention prune completed snapshot timers are active; a recursive hourly snapshot and scheduled retention prune completed
successfully. The first monthly scrub remains a runtime check. successfully. The first monthly scrub completed successfully on 2026-10-04;
the actual service result and pool scan were independently verified.
### Priority 1 - Data protection ### Priority 1 - Data protection
- [x] Deploy Ansible-managed recursive ZFS snapshots with 24 hourly, 30 daily, 8 weekly, and 12 monthly - [x] Deploy Ansible-managed recursive ZFS snapshots with 24 hourly, 30 daily, 8 weekly, and 12 monthly
generations, plus a monthly scrub on the first Sunday at 03:00. The timers and first hourly snapshot were generations, plus a monthly scrub on the first Sunday at 03:00. The timers and first hourly snapshot were
verified on Atlas. Cockpit Scheduler is for visibility or manual operations only, and snapshot verified on Atlas. Cockpit Scheduler is for visibility or manual operations only, and snapshot
rollback is never automated. rollback is never automated.
- [ ] Verify the first monthly ZFS scrub from its actual service result. Scheduled retention pruning - [x] Verify the first monthly ZFS scrub from its actual service result. On 2026-10-04
was observed on 2026-09-30; timer activation alone does not establish a successful scrub. it completed at 05:02 CEST after 2:02:04, repairing 0 B with zero errors;
the service exited successfully and the pool reported no known data errors.
- [x] Activate and validate the encrypted offsite Borg backup to the Hetzner Storage Box. Atlas uses the - [x] Activate and validate the encrypted offsite Borg backup to the Hetzner Storage Box. Atlas uses the
dedicated SSH identity, pinned ED25519 host key, Vault-backed `repokey` encryption, and a locked dedicated SSH identity, pinned ED25519 host key, Vault-backed `repokey` encryption, and a locked
non-login `borg` account with no sudo or supplementary groups. The initial snapshot-consistent backup, non-login `borg` account with no sudo or supplementary groups. The initial snapshot-consistent backup,
@@ -376,9 +419,23 @@ successfully. The first monthly scrub remains a runtime check.
web login, WebDAV, private-file isolation, Famiglia cross-user create/read/update/delete and web login, WebDAV, private-file isolation, Famiglia cross-user create/read/update/delete and
CalDAV/CardDAV discovery passed. The Office connector and public health/API asset passed. CalDAV/CardDAV discovery passed. The Office connector and public health/API asset passed.
Temporary test files were removed; no iCloud data was imported. Temporary test files were removed; no iCloud data was imported.
- [ ] Complete Nextcloud desktop/mobile editing and synchronization acceptance, and - [x] Test a manual consistent Nextcloud backup and isolated restore on 2026-10-04.
application-consistent backup/restore validation. Close the first actual scrub and Paused application writers and cron, copied app/config/custom apps/themes and files,
protection checks before importing family data. dumped PostgreSQL, restored database roles and verified authenticated DAV contents,
account recovery and Famiglia permissions. Test containers had no external network,
published ports or live data mounts; they and the temporary restore copy were removed.
See `docs/atlas-nextcloud-recovery-test.md`; this is not recurring Borg/USB recovery evidence.
- [x] Integrate consistent Nextcloud bundles with recurring Borg and operator-started USB
backups, two-version local retention, interruption recovery and failure monitoring.
On 2026-10-04 Borg archive `atlas-20261004T095255Z` succeeded; its new bundle was
extracted from Hetzner and restored in isolation with checksums, accounts, Famiglia
permissions and authenticated DAV verified. No production database was replaced.
- [x] Validate a new USB version and restore its consistent Nextcloud bundle. On
2026-10-04 USB version `20261004T101101Z-3420114` completed successfully; bundle
`20261004T100959Z-3415600` was read-only extracted, checksum-verified and restored
in isolation. Accounts, Famiglia permissions and authenticated DAV passed. The
test copy/containers were removed, LUKS closed and the pool remained healthy.
- [ ] Complete Nextcloud desktop/mobile editing and synchronization acceptance before family import.
iCloud migration and future Uranus transfer remain separate operations, not playbook flags. iCloud migration and future Uranus transfer remain separate operations, not playbook flags.
- [x] Move Gitea canonical HTTPS and SSH hostname to `git.fscotto.co` on - [x] Move Gitea canonical HTTPS and SSH hostname to `git.fscotto.co` on
2026-10-03 through Ansible. Only Gitea restarted; second run changed nothing. 2026-10-03 through Ansible. Only Gitea restarted; second run changed nothing.
@@ -507,9 +564,13 @@ validated exports of older historical data will use a dedicated Atlas NFS datase
- Shared agent dotfiles live in `ai_agents_dotfiles`; rendered configs live in `ai_agents_templates`. - Shared agent dotfiles live in `ai_agents_dotfiles`; rendered configs live in `ai_agents_templates`.
- Every `ai_agents.<agent>` entry has independent `install_enabled`, `deploy_enabled`, and `uninstall_enabled` flags. Installation and removal must not both be true for the same agent; the common pre-task fails before changes when they conflict. - Every `ai_agents.<agent>` entry has independent `install_enabled`, `deploy_enabled`, and `uninstall_enabled` flags. Installation and removal must not both be true for the same agent; the common pre-task fails before changes when they conflict.
- Fedora, Void desktop, and WSL workstation profiles consume the shared agent definitions; do not duplicate package entries in profile-specific vars. IBM Bob on the workstation follows its own flags. - Fedora, Void desktop, and WSL workstation profiles consume the shared agent definitions; do not duplicate package entries in profile-specific vars. IBM Bob on the workstation follows its own flags.
- WSL (`deadalus`) installs Claude Code, Codex and the Cline CLI; every other managed agent (including IBM Bob) is disabled and selected for removal through host overrides. `cline_deploy_enabled: true` also keeps Cline's cross-tool AGENTS pointer, global rules, and shared `~/.config/ai` context deployed on the host for the ecaas/cdp devcontainer bind mounts. Existing user state remains untouched.
- `dotfiles_common` deploys `ai_agents_dotfiles` and renders `ai_agents_templates` only when deployment is enabled. - `dotfiles_common` deploys `ai_agents_dotfiles` and renders `ai_agents_templates` only when deployment is enabled.
- Removal is limited to the managed npm packages and `/usr/local/bin/bob`; never remove agent dotfiles, instructions, credentials, or user data. - Removal is limited to the managed npm packages and `/usr/local/bin/bob`; never remove agent dotfiles, instructions, credentials, or user data.
- Keep `.config/ai/` as the common instruction source; update agent-specific entrypoints to reference it rather than duplicating instruction text. - Keep `.config/ai/` as the common instruction source; update agent-specific entrypoints to reference it rather than duplicating instruction text.
- Fedora desktop AI apps (`chatgpt_desktop`, `opencode_desktop`, `cline_desktop`) follow the same lifecycle pattern through `ai_desktop_apps` in `ansible/inventory/group_vars/fedora.yml`; `install_enabled` and `uninstall_enabled` are independent per app and mutually exclusive (enforced by the common pre-task).
- ChatGPT opts in per host (`ikaros`, `nymph`); Cline opts in through `desktop_gnome` group vars; OpenCode Desktop keeps removal selected by default because Cline replaced it.
- Desktop-app removal deletes only managed artifacts: the RPM package (`chatgpt`, `opencode`, `cline`), ChatGPT's managed repository and signing key, and every cached download; it never removes user data, GNOME favorites, or the npm-managed CLI counterparts.
## Tooling Notes ## Tooling Notes
- Install local tooling with: - Install local tooling with:
@@ -543,3 +604,16 @@ validated exports of older historical data will use a dedicated Atlas NFS datase
not depend on the AdGuard container during startup. not depend on the AdGuard container during startup.
- Aegis iCloudPD has been retired and is no longer managed by this role. Its service, Quadlet, - Aegis iCloudPD has been retired and is no longer managed by this role. Its service, Quadlet,
data, and MFA state were removed with the operator's explicit authorization. data, and MFA state were removed with the operator's explicit authorization.
## Project Devcontainer Generator
- `cmd/devcontainer/` generates standalone per-project language configurations;
it does not replace existing deadalus ecaas/cdp provisioning or remove host tools.
- Keep shared Git/agent behavior documented in `docs/project-devcontainers.md`.
- Focused validation: `go -C cmd/devcontainer test ./...`.
- Real engine builds, host credential forwarding and Fedora SELinux/Podman checks
require target-host validation; do not report generator tests as runtime evidence.
- `devcontainer_generator` builds the CLI natively on Fedora graphical desktops
and development workstations and installs it in `~/.local/bin/devcontainer`.
Validate with `ansible-playbook ansible/site.yml --limit ikaros --tags devcontainer_generator --check --diff`;
check mode skips compilation and binary installation explicitly.

View File

@@ -164,7 +164,6 @@ Lo stato attuale del profilo workstation include:
- installazione pacchetti base Fedora via dnf - installazione pacchetti base Fedora via dnf
- installazione e configurazione di Docker dal repository ufficiale - installazione e configurazione di Docker dal repository ufficiale
- installazione di Mise dal COPR ufficiale con JDK Eclipse Temurin Java 11 fissato
- gestione dei dotfiles workstation e rendering dei template dev condivisi - gestione dei dotfiles workstation e rendering dei template dev condivisi
- preparazione di Fedora WSL con `systemd` per il toolchain di sviluppo - preparazione di Fedora WSL con `systemd` per il toolchain di sviluppo
- attivazione del firewall `firewalld` sui target Fedora che dichiarano regole host-specifiche - attivazione del firewall `firewalld` sui target Fedora che dichiarano regole host-specifiche
@@ -754,7 +753,7 @@ Allo stato attuale `ansible/site.yml` espone questi tag:
| Tag | Scopo | Ambito principale | | Tag | Scopo | Ambito principale |
| --- | --- | --- | | --- | --- | --- |
| `always` | pre-task sempre eseguiti, inclusi caricamento vault e validazioni preliminari | common | | `always` | pre-task sempre eseguiti, inclusi caricamento vault e validazioni preliminari | common |
| `ai_agents` | installazione agenti AI condivisi | Fedora, WSL | | `ai_agents` | installazione agenti AI condivisi e distribuzione del contesto condiviso (bootstrap, regole, memoria ChatGPT) | Fedora, WSL |
| `atlas` | account, storage, condivisioni e container Atlas | NAS Atlas | | `atlas` | account, storage, condivisioni e container Atlas | NAS Atlas |
| `backend_phase1` | Quadlet rootless Navidrome e Syncthing | NAS Atlas | | `backend_phase1` | Quadlet rootless Navidrome e Syncthing | NAS Atlas |
| `containers` | Quadlet rootful Atlas | NAS Atlas | | `containers` | Quadlet rootful Atlas | NAS Atlas |

146
README.md
View File

@@ -63,9 +63,11 @@ nymph is allowed to break
`ikaros` is the stable personal Fedora/GNOME desktop. `nymph` is the laptop and gets the same shared desktop dotfiles while GNOME itself stays close to the Fedora defaults. The legacy `void` and `desktop` groups are compatibility parents; the main axes are `platform_*`, `role_*`, and `desktop_*`. `ikaros` is the stable personal Fedora/GNOME desktop. `nymph` is the laptop and gets the same shared desktop dotfiles while GNOME itself stays close to the Fedora defaults. The legacy `void` and `desktop` groups are compatibility parents; the main axes are `platform_*`, `role_*`, and `desktop_*`.
The official ChatGPT desktop RPM is enabled only on `ikaros` and `nymph`. The The official ChatGPT desktop RPM is installed only on `ikaros` and `nymph`
playbook configures OpenAI's signed RPM repository and imports its pinned RPM through their `chatgpt_desktop_install_enabled` host overrides. The playbook
signing key before installation; subsequent updates are handled by DNF. configures OpenAI's signed RPM repository and imports its pinned RPM signing
key before installation; subsequent updates are handled by DNF. Enabling
`chatgpt_desktop_uninstall_enabled` removes the package, repository, and key.
## Deferred planned node: Cerberus ## Deferred planned node: Cerberus
@@ -114,7 +116,7 @@ The workstation receives two layers:
- Fedora development setup through `workstation_dev_fedora`. - Fedora development setup through `workstation_dev_fedora`.
- WSL setup with `systemd` through `workstation_dev_wsl`. - WSL setup with `systemd` through `workstation_dev_wsl`.
That gives it Fedora packages through DNF, Docker from the official repository, Mise from its official COPR repository with a pinned Eclipse Temurin Java 11 JDK, shared workstation dotfiles and templates, tmux helpers, and WSL systemd configuration. Windows applications are installed manually; the WSL profile does not manage Python remoting components for them. That gives it Fedora packages through DNF, Docker from the official repository, shared workstation dotfiles and templates, tmux helpers, and WSL systemd configuration. Windows applications are installed manually; the WSL profile does not manage Python remoting components for them.
### WSL workflow ### WSL workflow
@@ -575,8 +577,8 @@ ansible-playbook ansible/site.yml --limit <host> --tags emacs -e emacs_enabled=t
## AI coding agents ## AI coding agents
The shared npm-managed agents are OpenCode, Claude Code, Codex, Gemini CLI, and The shared npm-managed agents are OpenCode, Claude Code, Codex, Gemini CLI, and
GitHub Copilot; IBM Bob is also managed on `deadalus`. Codex Relay is installed GitHub Copilot; IBM Bob is also managed on Fedora workstations. Codex Relay is installed
only on `ikaros`. Each agent has its own lifecycle flags in only on `ikaros`. On WSL (`deadalus`), Claude Code is the only installed coding agent. Each agent has its own lifecycle flags in
`ansible/inventory/group_vars/all.yml`, so one agent can be installed, `ansible/inventory/group_vars/all.yml`, so one agent can be installed,
configured, or removed without affecting the others: configured, or removed without affecting the others:
@@ -596,6 +598,48 @@ instructions, credentials, and user data. Installation and removal are mutually
exclusive per agent: the playbook fails before making changes when both flags are exclusive per agent: the playbook fails before making changes when both flags are
true for the same agent. Servers set `ai_agents: {}` and therefore manage none. true for the same agent. Servers set `ai_agents: {}` and therefore manage none.
On WSL (`deadalus`), Claude Code, Codex and the Cline CLI are installed through
`profile_workstation_dev_common`. Every other managed coding agent is disabled through
host overrides and its managed npm package or `bob` binary is selected for removal.
`cline_deploy_enabled: true` also keeps Cline's cross-tool AGENTS pointer, global rules,
and shared `~/.config/ai` context deployed on the WSL host for the ecaas/cdp devcontainers.
Existing configuration, credentials, and user data are left untouched.
The shared agent context is centralized in `dotfiles/common/.config/ai/` and
deployed to `~/.config/ai/` for every enabled agent: `bootstrap.md` (operating
context), `AGENTS.md` (task-specific file dispatcher), plus `knowledge/`,
`rules/`, and `patterns/`. Each agent is wired to it: OpenCode through the
`instructions` array in `opencode.json`, Codex through `model_instructions_file`
plus the global `~/.codex/AGENTS.md`, Gemini CLI through its settings context
files, Claude Code through the `@` imports in `~/.claude/CLAUDE.md`, and Cline
through both the cross-tool `~/.agents/AGENTS.md` pointer and the always-on
global rule `~/.cline/rules/ai-context.md`, which binds `bootstrap.md`, the
dispatcher, the safety directives, and the distilled ChatGPT knowledge under
`memory/chatgpt/` (both deployed with `cline_deploy_enabled: true`). Cline
shows the rule in its Rules panel as `global:ai-context`, where it can be
toggled per project.
ChatGPT conversation memory lives in
`dotfiles/common/.config/ai/memory/chatgpt/`: one Markdown transcript per
conversation, a generated `INDEX.md`, and topic-distilled knowledge files under
`memory/chatgpt/knowledge/` that agents load through the dispatcher. Regenerate
it incrementally from an official ChatGPT data export with:
```bash
python3 scripts/chatgpt_export_to_memory.py --export-dir ~/Downloads/<export>
```
Binary and personal assets (PDFs, images) are deliberately not imported;
textual ones are copied under `memory/chatgpt/assets/`. Non-technical personal
conversations are excluded from import by a privacy blocklist in the script,
which also prunes any previously imported copy.
The `opencode-mobile` npm package is no longer installed on managed hosts: its
agent entry sets `install_enabled: false` and `uninstall_enabled: true`, so the
playbook removes the managed package. The plugin declaration and `/mobile`
command are still deployed with the OpenCode dotfiles, and pairing and
connectivity remain manual; see the [upstream instructions](https://github.com/doza62/opencode-mobile#readme).
Run a focused dry run with: Run a focused dry run with:
```bash ```bash
@@ -610,6 +654,86 @@ only in the entry for the agent being removed, then run:
ansible-playbook ansible/site.yml --limit deadalus --tags ai_agents --check --diff ansible-playbook ansible/site.yml --limit deadalus --tags ai_agents --check --diff
``` ```
### AI desktop applications
The same lifecycle-flag pattern manages the Fedora desktop applications
through `ai_desktop_apps` in `ansible/inventory/group_vars/fedora.yml`.
`chatgpt_desktop`, `opencode_desktop` and `cline_desktop` each expose
`install_enabled` and `uninstall_enabled`, and the common pre-task rejects
both being true for the same app. ChatGPT opts in per host (`ikaros`, `nymph`),
Cline opts in through `desktop_gnome` group vars, and OpenCode Desktop keeps
removal selected because Cline replaced it.
Removal deletes only what the playbook manages — the installed RPM package,
ChatGPT's managed repository and signing key, and every cached download — and
leaves GNOME favorites, user data, and the npm-managed CLI counterparts
untouched. To switch an app between installed and removed, flip exactly one
of its lifecycle flags, then preview with:
```bash
ansible-playbook ansible/site.yml --limit ikaros --tags chatgpt,opencode_desktop,cline_desktop --check --diff
```
### Cline Desktop on Fedora
The [official Cline Desktop RPM](https://cline.bot/desktop) is managed on the
Fedora/GNOME workstations `ikaros` and `nymph`. WSL, Fedora IoT, Void and servers
are excluded. The GNOME profile pins `Cline.desktop` in the position of an old
OpenCode favorite, or appends it if there was no OpenCode favorite. Other
favorites keep their order. Run the playbook from an active GNOME session.
The version and per-architecture SHA-256 digests are pinned in
`ansible/inventory/group_vars/fedora.yml`; update both together from the official
[Desktop release](https://github.com/cline/cline/releases/tag/desktop-v0.0.49).
Only the checksum-verified local RPM installation disables DNF signature
checking; no repository policy is changed. The Cline VS Code extension and
npm-managed CLIs are independent of this app.
```bash
ansible-playbook ansible/site.yml --limit ikaros --tags cline_desktop --check --diff
ansible-playbook ansible/site.yml --limit ikaros --tags cline_desktop -K
```
Run locally on each workstation (`ansible_connection: local`); use `--limit nymph`
on the laptop. With a cold RPM cache, check mode reports that dependency resolution
is not validated; the real run downloads, verifies, and installs the package.
Cline replaced OpenCode Desktop: its `ai_desktop_apps` entry keeps
`opencode_desktop_uninstall_enabled: true` by default, so a previously
installed `opencode` RPM converges away on graphical hosts. Flip the entry's
flags to reinstall the pinned release instead. Neither removal touches the
npm CLI or user data.
### Thunderbird iCloud profile on Fedora
`profile_desktop_gnome` seeds a Thunderbird profile for `ikaros` and `nymph` so the
iCloud account is already declared: IMAP `imap.mail.me.com:993` over SSL/TLS, SMTP
`smtp.mail.me.com:587` over STARTTLS, the identity and folder mapping, one CalDAV
calendar (`caldav.icloud.com`) and one CardDAV address book (`contacts.icloud.com`).
Before provisioning, the role checks both `~/.thunderbird` and
`~/.config/thunderbird`, including registered absolute profile paths. If a profile
already has a configured mail account, it selects that profile without modifying
its account preferences, passwords, calendars or address books. Registered default
profiles take priority over other discovered profiles. The active registry keeps
its other profiles and is backed up before changes, including installation defaults.
Only when no configured account exists does the role create the iCloud profile
and seed `user.js` without overwriting an existing file. Thunderbird must be closed
before applying this tag; the playbook never stops it automatically. No profile or
mail data is deleted or copied. A fresh installation uses `~/.config/thunderbird`;
an existing legacy `~/.thunderbird` directory is retained.
The address comes from `vault_icloud_email` and the display name from
`vault_personal_full_name`. The password is deliberately not stored: iCloud mail
requires an app-specific password, which Thunderbird requests on first use and
keeps in its own credential store. Set `thunderbird_icloud_enabled: false` to stop
managing the profile without deleting it.
```bash
ansible-playbook ansible/site.yml --limit ikaros --tags thunderbird --check --diff
ansible-playbook ansible/site.yml --limit ikaros --tags thunderbird -K
```
## Main roles ## Main roles
| Role | What it does | | Role | What it does |
@@ -769,3 +893,13 @@ For a future Void desktop host:
4. Put hardware-specific details in `host_vars/<host>.yml`. 4. Put hardware-specific details in `host_vars/<host>.yml`.
The legacy `void` and `desktop` groups remain compatibility parents, so hosts in `platform_void` and `graphical_desktop` still receive the existing Void and desktop variables. The legacy `void` and `desktop` groups remain compatibility parents, so hosts in `platform_void` and `graphical_desktop` still receive the existing Void and desktop variables.
## Project devcontainer generator
Generate a reusable language environment for an existing project with
`devcontainer ~/src/project --language python --agents codex,cline`.
Git and selected coding-agent configuration are shared from the development host.
See [profiles, host requirements and validation](docs/project-devcontainers.md).
Deploy `~/.local/bin/devcontainer` on a Fedora desktop/workstation with
`ansible-playbook ansible/site.yml --limit ikaros --tags devcontainer_generator -K`.

View File

@@ -93,43 +93,75 @@ common_dotfiles:
# AI coding-agent lifecycle controls are independent for every agent. # AI coding-agent lifecycle controls are independent for every agent.
# Installation and removal are mutually exclusive per agent; the common # Installation and removal are mutually exclusive per agent; the common
# pre-task enforces this before any changes are made. # pre-task enforces this before any changes are made.
opencode_install_enabled: true
opencode_deploy_enabled: true
opencode_uninstall_enabled: false
codex_install_enabled: true
codex_deploy_enabled: true
codex_uninstall_enabled: false
codex_relay_install_enabled: false codex_relay_install_enabled: false
codex_relay_uninstall_enabled: false
gemini_cli_install_enabled: true
gemini_cli_deploy_enabled: true
gemini_cli_uninstall_enabled: false
claude_code_install_enabled: false
claude_code_uninstall_enabled: true
cline_install_enabled: true
cline_deploy_enabled: true
cline_uninstall_enabled: false
ibm_bob_install_enabled: true
ibm_bob_uninstall_enabled: false
# npm registry requests can be interrupted transiently. Keep retries bounded
# so persistent proxy, DNS, or registry failures still fail the play clearly.
ai_agents_npm_install_retries: 3
ai_agents_npm_install_retry_delay: 10
ai_agents: ai_agents:
opencode: opencode:
npm_package: opencode-ai npm_package: opencode-ai
install_enabled: true install_enabled: "{{ opencode_install_enabled }}"
deploy_enabled: true deploy_enabled: "{{ opencode_deploy_enabled }}"
uninstall_enabled: false uninstall_enabled: "{{ opencode_uninstall_enabled }}"
claude_code: opencode_mobile:
npm_package: "@anthropic-ai/claude-code" npm_package: opencode-mobile
install_enabled: false install_enabled: false
deploy_enabled: false deploy_enabled: false
uninstall_enabled: true uninstall_enabled: true
claude_code:
npm_package: "@anthropic-ai/claude-code"
install_enabled: "{{ claude_code_install_enabled }}"
deploy_enabled: false
uninstall_enabled: "{{ claude_code_uninstall_enabled }}"
codex: codex:
npm_package: "@openai/codex" npm_package: "@openai/codex"
install_enabled: true install_enabled: "{{ codex_install_enabled }}"
deploy_enabled: true deploy_enabled: "{{ codex_deploy_enabled }}"
uninstall_enabled: false uninstall_enabled: "{{ codex_uninstall_enabled }}"
codex_relay: codex_relay:
npm_package: codex-relay npm_package: codex-relay
install_enabled: "{{ codex_relay_install_enabled }}" install_enabled: "{{ codex_relay_install_enabled }}"
deploy_enabled: false deploy_enabled: false
uninstall_enabled: false uninstall_enabled: "{{ codex_relay_uninstall_enabled }}"
gemini_cli: gemini_cli:
npm_package: "@google/gemini-cli" npm_package: "@google/gemini-cli"
install_enabled: true install_enabled: "{{ gemini_cli_install_enabled }}"
deploy_enabled: true deploy_enabled: "{{ gemini_cli_deploy_enabled }}"
uninstall_enabled: false uninstall_enabled: "{{ gemini_cli_uninstall_enabled }}"
cline:
npm_package: cline
install_enabled: "{{ cline_install_enabled }}"
deploy_enabled: "{{ cline_deploy_enabled }}"
uninstall_enabled: "{{ cline_uninstall_enabled }}"
github_copilot: github_copilot:
npm_package: "@github/copilot" npm_package: "@github/copilot"
install_enabled: false install_enabled: false
deploy_enabled: false deploy_enabled: false
uninstall_enabled: true uninstall_enabled: true
ibm_bob: ibm_bob:
install_enabled: true install_enabled: "{{ ibm_bob_install_enabled }}"
deploy_enabled: false deploy_enabled: false
uninstall_enabled: false uninstall_enabled: "{{ ibm_bob_uninstall_enabled }}"
ai_agents_deploy_enabled_names: >- ai_agents_deploy_enabled_names: >-
{{ ai_agents | dict2items | selectattr('value.deploy_enabled') | map(attribute='key') | list }} {{ ai_agents | dict2items | selectattr('value.deploy_enabled') | map(attribute='key') | list }}
@@ -143,6 +175,7 @@ ai_agents_dotfiles:
- opencode - opencode
- codex - codex
- gemini_cli - gemini_cli
- cline
- name: Gemini CLI config - name: Gemini CLI config
src: .gemini/ src: .gemini/
dest: .gemini/ dest: .gemini/
@@ -161,6 +194,24 @@ ai_agents_dotfiles:
mode: preserve mode: preserve
agents: agents:
- claude_code - claude_code
- name: Codex global AGENTS instructions
src: .codex/AGENTS.md
dest: .codex/AGENTS.md
mode: "0644"
agents:
- codex
- name: Cline cross-tool AGENTS instructions
src: .agents/AGENTS.md
dest: .agents/AGENTS.md
mode: "0644"
agents:
- cline
- name: Cline global rules
src: .cline/rules/
dest: .cline/rules/
mode: preserve
agents:
- cline
ai_agents_templates: ai_agents_templates:
- name: Codex config - name: Codex config

View File

@@ -42,10 +42,6 @@ desktop_uv_tools:
- python-lsp-server - python-lsp-server
desktop_common_dotfiles: desktop_common_dotfiles:
- name: XDG autostart entries
src: .config/autostart/
dest: .config/autostart/
mode: preserve
- name: fastfetch config - name: fastfetch config
src: .config/fastfetch/ src: .config/fastfetch/
dest: .config/fastfetch/ dest: .config/fastfetch/
@@ -218,7 +214,6 @@ desktop_niri_dotfiles:
desktop_flatpak_packages: desktop_flatpak_packages:
- be.alexandervanhee.gradia - be.alexandervanhee.gradia
- ch.protonmail.protonmail-bridge
- com.discordapp.Discord - com.discordapp.Discord
- com.calibre_ebook.calibre - com.calibre_ebook.calibre
- com.github.tchx84.Flatseal - com.github.tchx84.Flatseal

View File

@@ -4,6 +4,9 @@ desktop_environment: gnome
desktop_sessions_enabled: [] desktop_sessions_enabled: []
desktop_default_session: gnome desktop_default_session: gnome
emacs_enabled: true emacs_enabled: true
# Cline Desktop is installed (and pinned in the GNOME favorites) on every
# GNOME host; set cline_desktop_uninstall_enabled here to remove it instead.
cline_desktop_install_enabled: true
# Fedora Workstation/GNOME desktop applications. Keep this profile separate from # Fedora Workstation/GNOME desktop applications. Keep this profile separate from
# workstation_* so nymph can remain a desktop laptop rather than a dev workstation. # workstation_* so nymph can remain a desktop laptop rather than a dev workstation.
@@ -22,7 +25,7 @@ fedora_desktop_packages:
- croc - croc
- delve - delve
- dnsmasq - dnsmasq
- evolution - thunderbird
- fastfetch - fastfetch
- poppler-glib - poppler-glib
- poppler-utils - poppler-utils
@@ -42,6 +45,7 @@ fedora_desktop_packages:
- libXft-devel - libXft-devel
- meld - meld
- mpv - mpv
- nextcloud-client
- pdfarranger - pdfarranger
- pinentry-gnome3 - pinentry-gnome3
- plocate - plocate
@@ -72,6 +76,10 @@ fedora_desktop_packages:
- yt-dlp - yt-dlp
- zstd - zstd
fedora_removed_packages:
- evolution
- evolution-langpacks
fedora_nerd_fonts_version: v3.3.0 fedora_nerd_fonts_version: v3.3.0
fedora_nerd_fonts: fedora_nerd_fonts:
- Hack - Hack
@@ -82,7 +90,82 @@ fedora_nerd_fonts:
fedora_flatpak_packages: fedora_flatpak_packages:
- be.alexandervanhee.gradia - be.alexandervanhee.gradia
- ch.protonmail.protonmail-bridge
- com.spotify.Client - com.spotify.Client
- org.desktop_plus.desktop-plus
- org.onlyoffice.desktopeditors - org.onlyoffice.desktopeditors
- org.telegram.desktop - org.telegram.desktop
# GNOME-only dotfiles. Kept out of desktop_common_dotfiles so the Void desktops
# do not receive XDG autostart entries for applications they do not install.
# Nextcloud desktop is the `nextcloud-client` package in fedora_desktop_packages;
# this entry matches what the client itself writes when "Launch on startup" is on.
desktop_gnome_dotfiles:
- name: Nextcloud autostart entry
src: .config/autostart/Nextcloud.desktop
dest: .config/autostart/Nextcloud.desktop
mode: "0644"
# Thunderbird is provisioned from a seeded profile plus a managed user.js:
# Existing Thunderbird accounts are reused without changing their preferences.
# Only a new profile receives account, calendar and address book defaults in user.js.
# The address comes from Vault; the app-specific password is never stored here
# and is requested by Thunderbird on first use.
thunderbird_icloud_enabled: true
thunderbird_profile_name: "{{ username }}"
thunderbird_profile_dir: "{{ username }}.default-release"
thunderbird_full_name: "{{ vault_personal_full_name | default(username) }}"
thunderbird_icloud_email: "{{ vault_icloud_email }}"
thunderbird_icloud_account_name: iCloud
thunderbird_icloud_imap_host: imap.mail.me.com
thunderbird_icloud_imap_port: 993
thunderbird_icloud_smtp_host: smtp.mail.me.com
thunderbird_icloud_smtp_port: 587
thunderbird_icloud_caldav_url: https://caldav.icloud.com/
thunderbird_icloud_carddav_url: https://contacts.icloud.com/
thunderbird_icloud_calendar_id: 4f2c1d6e-9b3a-4f7c-8e21-6d5a0c9b7e13
thunderbird_icloud_addressbook_uid: 9e0b7c4a-2d51-4a8f-b6c3-1f7d5e2a8b46
# Native VS Code; opt in to managing settings only after defining them.
vscode_extensions:
- esbenp.prettier-vscode
- github.remotehub
- ms-azuretools.vscode-containers
# ms-azuretools.vscode-docker is deprecated: since June 2025 it is just an
# extension pack wrapping Container Tools. Only the real extension is kept.
- ms-vscode-remote.remote-containers
- ms-vscode-remote.remote-ssh
- ms-vscode-remote.remote-ssh-edit
- ms-vscode-remote.remote-wsl
- ms-vscode-remote.vscode-remote-extensionpack
- ms-vscode.azure-repos
- ms-vscode.remote-explorer
- ms-vscode.remote-repositories
- ms-vscode.remote-server
- pkief.material-icon-theme
- redhat.vscode-xml
- redhat.vscode-yaml
- saoudrizwan.claude-dev
- vscodevim.vim
# Managed user settings deploy as a full-file overlay with a timestamped backup;
# any manual settings.json edit is converged away on the next run. These keys cover
# the podman Dev Containers engine selection and the Container Tools clients.
# editor.fontFamily uses the canonical 'JetBrainsMono Nerd Font' family name: the
# live 'JetBriansMono NF' was a typo whose fallback chain rendered Liberation Mono.
vscode_settings:
containers.containerClient: com.microsoft.visualstudio.containers.podman
containers.orchestratorClient: com.microsoft.visualstudio.orchestrators.podmancompose
dev.containers.dockerPath: podman
editor.cursorStyle: block
editor.fontFamily: "'JetBrainsMono Nerd Font', 'Droid Sans Mono', monospace"
editor.formatOnPaste: true
workbench.iconTheme: material-icon-theme
workbench.startupEditor: none
# User-level keybindings apply to every window, including Dev Containers, SSH and WSL remotes.
# Keys avoid Ctrl+<letter>, which the Vim extension uses for its motions; Alt is not bound by Vim.
vscode_keybindings:
- key: alt+j
command: workbench.action.terminal.toggleTerminal
when: "!terminalFocus"
- key: alt+j
command: workbench.action.togglePanel
when: terminalFocus

View File

@@ -8,7 +8,10 @@ fedora_packages_base:
- htop - htop
- jq - jq
- make - make
- nodejs # Keep the LTS stream explicit. Fedora 45's rolling `nodejs` package
# conflicts with the nodejs22-bin alternative installed by the F44→F45
# upgrade.
- nodejs22
- openssl - openssl
- ripgrep - ripgrep
@@ -60,10 +63,54 @@ fedora_dev_packages:
fedora_flatpak_remote_name: flathub fedora_flatpak_remote_name: flathub
fedora_flatpak_remote_url: https://dl.flathub.org/repo/flathub.flatpakrepo fedora_flatpak_remote_url: https://dl.flathub.org/repo/flathub.flatpakrepo
chatgpt_desktop_enabled: false cline_desktop_version: "0.0.49"
# Launcher file shipped by the pinned RPM; the GNOME profile pins it in the
# favorites while installation stays enabled.
cline_desktop_launcher: Cline.desktop
# Digests published with the official GitHub release; update with the version.
cline_desktop_rpm_checksums:
x86_64: sha256:e10036a036ee531451695559e2c96feceb3d621408a6615bdd708ffcf9e778ab
aarch64: sha256:aec36edb594bdc400b0c2275230f29de6814a78ad60add4938347d20cfb93b74
cline_desktop_rpm_url: >-
https://github.com/cline/cline/releases/download/desktop-v{{ cline_desktop_version }}/Cline_{{ cline_desktop_version }}_{{ ansible_facts['architecture'] }}.rpm
cline_desktop_rpm_path: "/var/cache/cline-desktop-{{ cline_desktop_version }}-{{ ansible_facts['architecture'] }}.rpm"
# OpenCode Desktop was replaced by Cline Desktop. The pinned release stays
# available for reinstall, while removal is selected in the lifecycle flags
# below so leftovers from the switch converge away on graphical hosts.
opencode_desktop_version: "2.2.5"
# Digests published with the official GitHub release; update with the version.
opencode_desktop_rpm_checksums:
x86_64: sha256:4feb27fe98df9b7579abd31a790d331e9aff87c95f67081beefa2aaaa76ebada
aarch64: sha256:e84b1e03e2b4fb337ddfe015b6457a7aa0dfe171338be08e643ad66b1657033a
opencode_desktop_rpm_url: >-
https://github.com/anomalyco/opencode/releases/download/v{{ opencode_desktop_version }}/opencode-desktop-linux-{{ ansible_facts['architecture'] }}.rpm
opencode_desktop_rpm_path: "/var/cache/opencode-desktop-{{ opencode_desktop_version }}-{{ ansible_facts['architecture'] }}.rpm"
# AI desktop-app lifecycle controls are independent for every app and mirror
# the CLI coding-agent flags. Installation and removal are mutually exclusive
# per app; the common pre-task enforces this before any changes are made.
# ChatGPT opts in per host, Cline opts in through desktop_gnome group vars.
chatgpt_desktop_install_enabled: false
chatgpt_desktop_uninstall_enabled: false
opencode_desktop_install_enabled: false
opencode_desktop_uninstall_enabled: true
ai_desktop_apps:
chatgpt_desktop:
install_enabled: "{{ chatgpt_desktop_install_enabled }}"
uninstall_enabled: "{{ chatgpt_desktop_uninstall_enabled }}"
opencode_desktop:
install_enabled: "{{ opencode_desktop_install_enabled }}"
uninstall_enabled: "{{ opencode_desktop_uninstall_enabled }}"
cline_desktop:
install_enabled: "{{ cline_desktop_install_enabled | default(false) }}"
uninstall_enabled: "{{ cline_desktop_uninstall_enabled | default(false) }}"
chatgpt_desktop_supported_fedora_versions: chatgpt_desktop_supported_fedora_versions:
- "43" - "43"
- "44" - "44"
- "45"
chatgpt_desktop_supported_architectures: chatgpt_desktop_supported_architectures:
- x86_64 - x86_64
- aarch64 - aarch64

View File

@@ -183,7 +183,7 @@ profile_packages:
- deluge-gtk - deluge-gtk
- delve - delve
- dnsmasq - dnsmasq
- evolution - thunderbird
- poppler-glib - poppler-glib
- poppler-utils - poppler-utils
- fontconfig-devel - fontconfig-devel
@@ -224,5 +224,8 @@ profile_packages:
- yaru-plus - yaru-plus
- zstd - zstd
void_removed_packages:
- evolution
profile_emacs_packages: profile_emacs_packages:
- emacs-pgtk - emacs-pgtk

View File

@@ -1,6 +1,12 @@
--- ---
emacs_enabled: true emacs_enabled: true
workstation_git_https_cas:
- url: https://gitlab.ecaas.datacenter.comune.roma
certificate: ecaas.datacenter.comune.roma.crt
- url: https://gitlab.datacenter.comune.roma
certificate: datacenter.comune.roma.crt
workstation_user_directories: workstation_user_directories:
- path: "{{ user_home }}/.config" - path: "{{ user_home }}/.config"
mode: "0755" mode: "0755"

View File

@@ -1,4 +1,8 @@
--- ---
# Claude Code is managed only on the Fedora WSL development profile.
claude_code_install_enabled: true
claude_code_uninstall_enabled: false
enabled_services: enabled_services:
- docker - docker
@@ -7,26 +11,17 @@ workstation_dev_wsl_packages:
- helm - helm
# Fedora ships the kubectl client binary in the kubernetes-client package. # Fedora ships the kubectl client binary in the kubernetes-client package.
- kubernetes-client - kubernetes-client
- mise
- pinentry-curses - pinentry-curses
- python3-pip - python3-pip
- tmux - tmux
# Java 11, Java 25 and Maven are managed by Mise on this Fedora WSL profile. # Maven version pinned in the devcontainer images; update it deliberately.
# Keep their versions pinned; update them deliberately. workstation_maven_version: 3.9.16
workstation_mise_java_version: temurin-11.0.31+11 workstation_cdp_node_version: 20.18.3
workstation_mise_java_25_version: 25.0.2
workstation_mise_maven_version: 3.9.16
workstation_is_wsl: true workstation_is_wsl: true
workstation_wsl_systemd_enabled: true workstation_wsl_systemd_enabled: true
workstation_dev_wsl_dotfiles: workstation_dev_wsl_dotfiles:
- src: .bashrc.d/30-mise.sh
dest: .bashrc.d/30-mise.sh
mode: "0644"
- src: .config/mise/
dest: .config/mise/
mode: preserve
- src: .gnupg/gpg-agent.conf - src: .gnupg/gpg-agent.conf
dest: .gnupg/gpg-agent.conf dest: .gnupg/gpg-agent.conf
mode: "0600" mode: "0600"

View File

@@ -50,6 +50,8 @@ atlas_zfs_dataset_photobook: media/photobook
atlas_mount_root: /zpool atlas_mount_root: /zpool
atlas_manage_storage: true atlas_manage_storage: true
atlas_manage_nextcloud: true atlas_manage_nextcloud: true
# Two local consistent bundles; long-term history stays in Borg/USB and ZFS.
atlas_nextcloud_backup_keep: 2
atlas_nextcloud_domain: cloud.fscotto.co atlas_nextcloud_domain: cloud.fscotto.co
atlas_onlyoffice_domain: office.fscotto.co atlas_onlyoffice_domain: office.fscotto.co
# Resolved official amd64 images on 2026-10-03; updates are deliberate. # Resolved official amd64 images on 2026-10-03; updates are deliberate.
@@ -64,6 +66,19 @@ atlas_nextcloud_users:
- username: chiara - username: chiara
display_name: Chiara display_name: Chiara
password: "{{ vault_nextcloud_chiara_password }}" password: "{{ vault_nextcloud_chiara_password }}"
atlas_nextcloud_external_mounts:
- name: Documenti
user: fabio
source: /zpool/archive/Documents
target: /mnt/archive-documents
readonly: false
# Expose the iCloudPD originals directly in Fabio's canonical Photos folder.
# This remains a read-only external mount; iCloudPD is the sole writer.
- name: Photos
user: fabio
source: /zpool/archive/Pictures/iCloudPD
target: /mnt/archive-icloud
readonly: true
atlas_nextcloud_apps: atlas_nextcloud_apps:
- id: groupfolders - id: groupfolders
version: 21.0.9 version: 21.0.9
@@ -82,6 +97,17 @@ atlas_nextcloud_apps:
url: https://github.com/nextcloud-releases/calendar/releases/download/v6.6.2/calendar-v6.6.2.tar.gz url: https://github.com/nextcloud-releases/calendar/releases/download/v6.6.2/calendar-v6.6.2.tar.gz
checksum: sha256:7e83632d4436d3037a34d1c73cbc06d5ccb6e8fc10f096a86a43a0515588529c checksum: sha256:7e83632d4436d3037a34d1c73cbc06d5ccb6e8fc10f096a86a43a0515588529c
# Rootless Gitea was restored from the stopped-source export before production activation. # Rootless Gitea was restored from the stopped-source export before production activation.
# Paperless runs rootless on dedicated ZFS datasets; NPM remains on Prometheus.
atlas_manage_paperless: true
atlas_paperless_domain: documents.fscotto.co
# Resolved official amd64 images on 2026-10-12; upgrades remain deliberate.
atlas_paperless_image: ghcr.io/paperless-ngx/paperless-ngx:3.2.1@sha256:5fa76604a81df6945086e0837b14b56543d137e8ce4f311cc5d9ebe907e74e79
atlas_paperless_postgres_image: docker.io/library/postgres:17-bookworm@sha256:3645570cccdfa447589da9f57dd740faa29b30938e861289a5574b6ca6b03826
atlas_paperless_valkey_image: docker.io/valkey/valkey:8-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571
atlas_paperless_tika_image: docker.io/apache/tika:3.3.1.0@sha256:90b7fa1dc018434075fce9e1d9b88b1e3d0ea6979d0cf86e116c79a8073ae973
atlas_paperless_gotenberg_image: docker.io/gotenberg/gotenberg:8.37@sha256:f29984bd1e226bf1b93ba90af06000afa8b315853e99d27b9aaa41b93f15c769
atlas_paperless_ollama_image: docker.io/ollama/ollama:0.40.3@sha256:adca95a12c2b386a8f9a995e7fa0600e187e3323b5e5522f5a6c3b1ec73eff99
atlas_manage_gitea: true atlas_manage_gitea: true
atlas_gitea_production_enabled: true atlas_gitea_production_enabled: true
atlas_gitea_public_domain: git.fscotto.co atlas_gitea_public_domain: git.fscotto.co
@@ -244,3 +270,16 @@ host_enabled_services:
- cockpit.socket - cockpit.socket
- pmlogger.service - pmlogger.service
- zfs.target - zfs.target
# Torrent Web UI: LAN and the existing Aegis gateway for the manual NPM proxy.
atlas_manage_qbittorrent: true
atlas_qbittorrent_image: docker.io/qbittorrentofficial/qbittorrent-nox@sha256:92bfd78d731e254ba64f62b77b0696add6447a33642ee5feda106a26b285aa7f
atlas_qbittorrent_reverse_proxy_enabled: true
atlas_qbittorrent_public_domain: torrent.fscotto.co
# LAN-only HTTP downloader; RPC secret is generated and retained privately on Atlas.
atlas_manage_aria2: true
atlas_aria2_gateway_enabled: true
atlas_aria2_public_domain: downloads.fscotto.co
atlas_aria2_image: docker.io/p3terx/aria2-pro@sha256:086d1a37c586edb07ec0fb956bf9edd89d1d38d138ad5309ff96d510c8c9a011
atlas_ariang_image: docker.io/p3terx/ariang@sha256:73849cf75fe9f959229222622e887310df505cbf868eb9c735e2af376523c010

View File

@@ -1,6 +1,30 @@
--- ---
hostname: deadalus hostname: deadalus
workstation_wsl_windows_user_home: /mnt/c/Users/FABIOSCOTTODISANTOLO workstation_wsl_windows_user_home: /mnt/c/Users/FABIOSCOTTODISANTOLO
workstation_ecaas_workspace: "{{ user_home }}/Work/sipo/ecaas"
workstation_cdp_workspace: "{{ user_home }}/Work/sipo/cdp"
workstation_ecaas_git_required_ca: ecaas.datacenter.comune.roma.crt
# Claude Code, Codex and the Cline CLI are the coding agents installed on WSL; every
# other managed agent is disabled. Cline's cross-tool instructions (.agents/AGENTS.md,
# .cline/rules/) and the shared ~/.config/ai context are deployed for the ecaas/cdp
# devcontainers, and the cline npm package is installed by profile_workstation_dev_common.
claude_code_install_enabled: true
claude_code_uninstall_enabled: false
opencode_install_enabled: false
opencode_deploy_enabled: false
opencode_uninstall_enabled: true
codex_install_enabled: true
codex_deploy_enabled: false
codex_uninstall_enabled: false
gemini_cli_install_enabled: false
gemini_cli_deploy_enabled: false
gemini_cli_uninstall_enabled: true
cline_install_enabled: true
cline_deploy_enabled: true
cline_uninstall_enabled: false
ibm_bob_install_enabled: false
ibm_bob_uninstall_enabled: true
host_packages: [] host_packages: []
host_enabled_services: [] host_enabled_services: []

View File

@@ -1,10 +1,20 @@
--- ---
hostname: ikaros hostname: ikaros
codex_relay_install_enabled: true codex_relay_install_enabled: false
chatgpt_desktop_enabled: true codex_relay_uninstall_enabled: true
gemini_cli_install_enabled: false
gemini_cli_deploy_enabled: false
gemini_cli_uninstall_enabled: true
chatgpt_desktop_install_enabled: true
desktop_ai_media_enabled: true
desktop_ai_media_external_storage_enabled: true
desktop_ai_media_external_luks_uuid: 6948c504-2d60-4cc8-9e7f-3ccdf28e80d7
desktop_ai_media_external_mountpoint: /run/media/fscotto/Backup
desktop_ai_media_external_source: /run/media/fscotto/Backup/ai-media
host_packages: host_packages:
- podman
- openssh-clients - openssh-clients
- openssh-server - openssh-server
- mesa-vulkan-drivers - mesa-vulkan-drivers
@@ -141,7 +151,7 @@ gnome_gsettings_settings:
value: "'file:///usr/share/backgrounds/gnome/morphogenesis-l.svg'" value: "'file:///usr/share/backgrounds/gnome/morphogenesis-l.svg'"
- schema: org.gnome.desktop.search-providers - schema: org.gnome.desktop.search-providers
key: sort-order key: sort-order
value: "['org.gnome.Settings.desktop', 'org.gnome.Contacts.desktop', 'org.gnome.Nautilus.desktop']" value: "['org.gnome.Settings.desktop', 'org.gnome.Contacts.desktop', 'org.gnome.Nautilus.desktop', 'org.mozilla.firefox.desktop', 'org.gnome.seahorse.Application.desktop', 'org.gnome.Calculator.desktop', 'org.gnome.Calendar.desktop', 'org.gnome.Software.desktop', 'org.gnome.Characters.desktop', 'org.gnome.Boxes.desktop', 'org.gnome.clocks.desktop', 'com.mattjakeman.ExtensionManager.desktop']"
- schema: org.gnome.desktop.wm.keybindings - schema: org.gnome.desktop.wm.keybindings
key: switch-to-workspace-1 key: switch-to-workspace-1
value: "['<Super>1']" value: "['<Super>1']"
@@ -204,7 +214,7 @@ gnome_gsettings_settings:
value: "false" value: "false"
- schema: org.gnome.nautilus.preferences - schema: org.gnome.nautilus.preferences
key: default-folder-viewer key: default-folder-viewer
value: "'list-view'" value: "'icon-view'"
- schema: org.gnome.nautilus.preferences - schema: org.gnome.nautilus.preferences
key: show-create-link key: show-create-link
value: "true" value: "true"
@@ -232,19 +242,19 @@ gnome_gsettings_settings:
- schema: org.gnome.shell - schema: org.gnome.shell
key: app-picker-layout key: app-picker-layout
value: >- value: >-
[{'System': <{'position': <0>}>, 'Utilities': <{'position': <1>}>, 'org.fedoraproject.MediaWriter.desktop': <{'position': <2>}>, 'org.gnome.Contacts.desktop': <{'position': <3>}>, 'org.gnome.Calendar.desktop': <{'position': <4>}>, 'org.gnome.Calculator.desktop': <{'position': <5>}>, 'org.gnome.Weather.desktop': <{'position': <6>}>, 'org.gnome.clocks.desktop': <{'position': <7>}>, 'org.gnome.Maps.desktop': <{'position': <8>}>, 'org.gnome.SimpleScan.desktop': <{'position': <9>}>, 'org.gnome.TextEditor.desktop': <{'position': <10>}>, 'org.gnome.Settings.desktop': <{'position': <11>}>, 'org.gnome.Boxes.desktop': <{'position': <12>}>, 'org.gnome.Showtime.desktop': <{'position': <13>}>, 'org.gnome.Snapshot.desktop': <{'position': <14>}>, 'org.gnome.Characters.desktop': <{'position': <15>}>, 'org.gnome.Tour.desktop': <{'position': <16>}>, 'org.gnome.Yelp.desktop': <{'position': <17>}>, 'org.gnome.Software.desktop': <{'position': <18>}>, 'be.alexandervanhee.gradia.desktop': <{'position': <19>}>, 'com.github.jeromerobert.pdfarranger.desktop': <{'position': <20>}>, 'org.onlyoffice.desktopeditors.desktop': <{'position': <21>}>, 'org.gnome.Meld.desktop': <{'position': <22>}>, 'com.mattjakeman.ExtensionManager.desktop': <{'position': <23>}>}, {'org.remmina.Remmina.desktop': <{'position': <0>}>, 'ch.protonmail.protonmail-bridge.desktop': <{'position': <1>}>, 'syncthing-start.desktop': <{'position': <2>}>, 'syncthing-ui.desktop': <{'position': <3>}>, 'emacs.desktop': <{'position': <4>}>, 'emacs-client.desktop': <{'position': <5>}>, 'org.gnome.gitlab.somas.Apostrophe.desktop': <{'position': <6>}>, 'mpv.desktop': <{'position': <7>}>, 'htop.desktop': <{'position': <8>}>, 'com.raspberrypi.rpi-imager.desktop': <{'position': <9>}>}] [{'System': <{'position': <0>}>, 'Utilities': <{'position': <1>}>, 'org.fedoraproject.MediaWriter.desktop': <{'position': <2>}>, 'org.gnome.Contacts.desktop': <{'position': <3>}>, 'org.gnome.Calendar.desktop': <{'position': <4>}>, 'org.gnome.Calculator.desktop': <{'position': <5>}>, 'org.gnome.Weather.desktop': <{'position': <6>}>, 'org.gnome.clocks.desktop': <{'position': <7>}>, 'org.gnome.Maps.desktop': <{'position': <8>}>, 'org.gnome.SimpleScan.desktop': <{'position': <9>}>, 'org.gnome.TextEditor.desktop': <{'position': <10>}>, 'org.gnome.Settings.desktop': <{'position': <11>}>, 'org.gnome.Boxes.desktop': <{'position': <12>}>, 'org.gnome.Showtime.desktop': <{'position': <13>}>, 'org.gnome.Snapshot.desktop': <{'position': <14>}>, 'org.gnome.Characters.desktop': <{'position': <15>}>, 'org.gnome.Tour.desktop': <{'position': <16>}>, 'org.gnome.Yelp.desktop': <{'position': <17>}>, 'org.gnome.Software.desktop': <{'position': <18>}>, 'be.alexandervanhee.gradia.desktop': <{'position': <19>}>, 'com.github.jeromerobert.pdfarranger.desktop': <{'position': <20>}>, 'org.onlyoffice.desktopeditors.desktop': <{'position': <21>}>, 'org.gnome.Meld.desktop': <{'position': <22>}>, 'com.mattjakeman.ExtensionManager.desktop': <{'position': <23>}>}, {'com.raspberrypi.rpi-imager.desktop': <{'position': <0>}>, 'org.remmina.Remmina.desktop': <{'position': <1>}>, 'com.nextcloud.desktopclient.nextcloud.desktop': <{'position': <2>}>, 'syncthing-start.desktop': <{'position': <3>}>, 'syncthing-ui.desktop': <{'position': <4>}>, 'emacs.desktop': <{'position': <5>}>, 'emacs-client.desktop': <{'position': <6>}>, 'chatgpt.desktop': <{'position': <7>}>, 'org.gnome.gitlab.somas.Apostrophe.desktop': <{'position': <8>}>, 'mpv.desktop': <{'position': <9>}>, 'htop.desktop': <{'position': <10>}>, 'ai-media-facefusion.desktop': <{'position': <11>}>, 'ai-media-rvc.desktop': <{'position': <12>}>}]
- schema: org.gnome.shell - schema: org.gnome.shell
key: disabled-extensions key: disabled-extensions
value: >- value: >-
['window-list@gnome-shell-extensions.gcampax.github.com', 'background-logo@fedorahosted.org', 'apps-menu@gnome-shell-extensions.gcampax.github.com', 'places-menu@gnome-shell-extensions.gcampax.github.com'] ['window-list@gnome-shell-extensions.gcampax.github.com', 'background-logo@fedorahosted.org', 'apps-menu@gnome-shell-extensions.gcampax.github.com', 'places-menu@gnome-shell-extensions.gcampax.github.com', 'maximize-new-windows@VitalyOstanin']
- schema: org.gnome.shell - schema: org.gnome.shell
key: enabled-extensions key: enabled-extensions
value: >- value: >-
['status-icons@gnome-shell-extensions.gcampax.github.com', 'gnome-ui-tune@itstime.tech', 'appindicatorsupport@rgcjonas.gmail.com', 'bluetooth-battery-monitor@v8v88v8v88.com', 'clipboard-indicator@tudmotu.com', 'status-area-horizontal-spacing@mathematical.coffee.gmail.com', 'MaximizeWindowIntoNewWorkspace@kyleross.com', 'maximize-new-windows@VitalyOstanin'] ['status-icons@gnome-shell-extensions.gcampax.github.com', 'gnome-ui-tune@itstime.tech', 'appindicatorsupport@rgcjonas.gmail.com', 'bluetooth-battery-monitor@v8v88v8v88.com', 'clipboard-indicator@tudmotu.com', 'status-area-horizontal-spacing@mathematical.coffee.gmail.com', 'MaximizeWindowIntoNewWorkspace@kyleross.com', 'gnome-shell-extension-maximized-by-default@stiggimy.github.com']
- schema: org.gnome.shell - schema: org.gnome.shell
key: favorite-apps key: favorite-apps
value: >- value: >-
['org.gnome.Nautilus.desktop', 'org.mozilla.firefox.desktop', 'com.spotify.Client.desktop', 'org.gnome.Evolution.desktop', 'org.telegram.desktop.desktop', 'chatgpt.desktop', 'org.gnome.Ptyxis.desktop', 'virt-manager.desktop'] ['org.gnome.Nautilus.desktop', 'org.mozilla.firefox.desktop', 'com.spotify.Client.desktop', 'net.thunderbird.Thunderbird.desktop', 'org.telegram.desktop.desktop', 'Cline.desktop', 'org.desktop_plus.desktop-plus.desktop', 'com.microsoft.VSCode.desktop', 'org.gnome.Ptyxis.desktop', 'virt-manager.desktop']
- schema: org.gnome.shell - schema: org.gnome.shell
key: remember-mount-password key: remember-mount-password
value: "true" value: "true"

View File

@@ -1,7 +1,13 @@
--- ---
hostname: nymph hostname: nymph
chatgpt_desktop_enabled: true codex_relay_install_enabled: false
codex_relay_uninstall_enabled: true
gemini_cli_install_enabled: false
gemini_cli_deploy_enabled: false
gemini_cli_uninstall_enabled: true
chatgpt_desktop_install_enabled: true
# Fedora Workstation/GNOME laptop target. GNOME is provided by the base Fedora # Fedora Workstation/GNOME laptop target. GNOME is provided by the base Fedora
# Workstation install; Ansible deploys shared desktop dotfiles but leaves GNOME # Workstation install; Ansible deploys shared desktop dotfiles but leaves GNOME

View File

@@ -0,0 +1,14 @@
---
desktop_ai_media_enabled: false
desktop_ai_media_root: "{{ user_home }}/.local/share/ai-media"
desktop_ai_media_build_root: "{{ user_home }}/.local/share/ai-media-build"
desktop_ai_media_external_storage_enabled: false
desktop_ai_media_external_luks_uuid: ""
desktop_ai_media_external_mountpoint: ""
desktop_ai_media_external_source: ""
desktop_ai_media_debian_snapshot: "20261013T000000Z"
desktop_ai_media_base_image: >-
docker.io/library/python@sha256:34386ef0cb081344d7ec1c103ba398e6e9f64e9ab3a1509accc92a4e24a07258
desktop_ai_media_facefusion_revision: 72470819a0373be3388b3929c8f8f311f418fc3c
desktop_ai_media_rvc_revision: 81eed5e8f68b6bed1789f682fe78cdd324495afc
desktop_ai_media_apps: [facefusion, rvc]

View File

@@ -0,0 +1,56 @@
import configparser
import pathlib
import re
import sys
import xml.etree.ElementTree as ET
root = pathlib.Path(sys.argv[1]).resolve()
home = pathlib.Path.home()
local_filesystems = {
"btrfs", "ext2", "ext3", "ext4", "xfs", "zfs", "tmpfs", "overlay",
"ramfs", "ntfs3", "vfat", "exfat",
}
mounts = []
for line in pathlib.Path("/proc/self/mountinfo").read_text().splitlines():
fields, description = line.split(" - ", 1)
mount = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields.split()[4])
mounts.append((pathlib.Path(mount), description.split()[0]))
automount_at_root = any(p == root and kind == "autofs" for p, kind in mounts)
backing_mount_at_root = any(
p == root and kind != "autofs" for p, kind in mounts
)
if automount_at_root and not backing_mount_at_root:
raise SystemExit("Media storage is not mounted; refusing to start")
covering = [
(p, kind) for p, kind in mounts
if kind != "autofs" and (root == p or root.is_relative_to(p))
]
if covering:
selected = max(covering, key=lambda entry: len(entry[0].parts))
if selected[1] not in local_filesystems:
raise SystemExit("Media storage is not on a local filesystem; refusing to start")
for mount, kind in mounts:
if mount == root and kind == "autofs":
continue
if mount.is_relative_to(root) and kind not in local_filesystems:
raise SystemExit("Non-local mount beneath media storage; refusing to start")
sync_roots = []
nextcloud = home / ".config/Nextcloud/nextcloud.cfg"
if nextcloud.exists():
configuration = configparser.ConfigParser(interpolation=None, strict=False)
configuration.read(nextcloud)
for section in configuration.sections():
for key, value in configuration.items(section):
if key.lower().endswith("localpath"):
sync_roots.append(pathlib.Path(value).expanduser().resolve())
for configuration in (
home / ".config/syncthing/config.xml",
home / ".local/state/syncthing/config.xml",
):
if configuration.exists():
for folder in ET.parse(configuration).getroot().findall("folder"):
if folder.get("path"):
sync_roots.append(pathlib.Path(folder.get("path")).expanduser().resolve())
for path in sync_roots:
if root == path or root.is_relative_to(path) or path.is_relative_to(root):
raise SystemExit("Media storage overlaps a Nextcloud/Syncthing folder; refusing to start")

View File

@@ -0,0 +1,88 @@
import hashlib
import pathlib
import sys
import zipfile
app = sys.argv[1]
root = pathlib.Path("/opt/app")
if app == "facefusion":
sys.path.insert(0, str(root))
from facefusion import state_manager
from facefusion.args import apply_args
from facefusion.program import create_program
from facefusion.core import common_pre_check, processors_pre_check
args = vars(create_program().parse_args([
"run", "--execution-providers", "cpu",
"--processors", "face_swapper",
]))
apply_args(args, state_manager.init_item)
if not common_pre_check() or not processors_pre_check():
raise RuntimeError("FaceFusion model preparation failed")
else:
for relative in (
"hubert_base/config.json",
"hubert_base/preprocessor_config.json",
"hubert_base/pytorch_model.bin",
"rmvpe.pt",
):
destination = root / "assets" / relative
if relative == "rmvpe.pt":
destination = root / "assets/rmvpe/rmvpe.pt"
destination.parent.mkdir(parents=True, exist_ok=True)
if not destination.is_file():
raise FileNotFoundError("Missing checksum-pinned public model: " + str(destination))
for directory in ("weights", "indices", "pretrained", "pretrained_v2", "pymss_weights"):
(root / "assets" / directory).mkdir(parents=True, exist_ok=True)
# Mutable working data stays outside the immutable application tree.
for name, destination in (
("TEMP", "/tmp/rvc-temp"),
("assets/weights", "/work/state/weights"),
("logs", "/work/state"),
):
path = root / name
if path.exists():
import shutil
shutil.rmtree(path)
path.symlink_to(destination)
# Expose only separation models that are actually baked into this image.
separation = root / "tools/pymss_webui.py"
original = "PYMSS_MODEL_CHOICES = [spec.label for spec in MODEL_SPECS]"
replacement = """PYMSS_MODEL_CHOICES = [
spec.label for spec in MODEL_SPECS
if (weight_pymss_root / spec.model_file).is_file()
and (weight_pymss_root / spec.config_file).is_file()
]"""
code = separation.read_text()
if code.count(original) != 1:
raise RuntimeError("Pinned RVC separation model selector has changed")
separation.write_text(code.replace(original, replacement))
webui = root / "webui.py"
code = webui.read_text()
for label, destination in (
("主结果文件夹", "/work/output/vocals"),
("分离残余文件夹", "/work/output/instrumental"),
):
original = 'label=i18n("' + label + '"), value="opt"'
if code.count(original) != 1:
raise RuntimeError("Pinned RVC separation output selector has changed")
code = code.replace(original, 'label=i18n("' + label + '"), value="' + destination + '"')
webui.write_text(code)
# Bake only the public silence fixture; personal datasets never enter the build.
with zipfile.ZipFile(root / "assets/mute.zip") as archive:
destination = pathlib.Path("/opt/training-fixture")
for entry in archive.infolist():
target = (destination / entry.filename).resolve()
if not target.is_relative_to(destination):
raise ValueError("Invalid public silence archive member")
archive.extractall(destination)
with open("/opt/model-checksums.sha256", "w") as manifest:
for directory in (root / ".assets", root / "assets"):
if directory.exists():
for path in sorted(directory.rglob("*")):
if path.is_file():
digest = hashlib.file_digest(path.open("rb"), "sha256").hexdigest()
manifest.write(digest + " " + str(path) + "\n")

View File

@@ -0,0 +1,384 @@
"""Small host-side orchestrator for offline ai-media presets."""
import argparse
from datetime import datetime
import ipaddress
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
from urllib.parse import urlsplit
import uuid
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z")
SOURCE_NAMES = tuple(f"source{number}.jpg" for number in range(11, 19))
def video_url(value):
parsed = urlsplit(value)
if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password:
raise ValueError("Use an HTTP(S) video URL without embedded credentials")
host = parsed.hostname.lower().rstrip(".")
if host == "localhost" or host.endswith(".localhost"):
raise ValueError("Local URLs are not accepted")
try:
address = ipaddress.ip_address(host)
except ValueError:
pass
else:
if not address.is_global:
raise ValueError("Private or local IP URLs are not accepted")
return value
def media_file(root, name, *, video=False):
if not NAME.fullmatch(name) or name in (".", ".."):
raise ValueError("Use a simple filename in the ai-media input directory")
path = root / "input" / name
if not path.is_file() or path.is_symlink():
raise FileNotFoundError(path)
if video and path.suffix.lower() != ".mp4":
raise ValueError("The video must be an MP4 file")
return path
def audio_file(root, name):
if not name or any(not NAME.fullmatch(part) or part in (".", "..")
for part in name.split("/")):
raise ValueError("Use an audio path relative to input/ or output/ without traversal")
matches = [root / directory / name for directory in ("input", "output")]
matches = [path for path in matches if path.is_file() and path.resolve() == path]
if len(matches) != 1:
raise ValueError("Audio must exist in exactly one of input/ or output/")
return matches[0]
def container_path(root, path):
directory = path.relative_to(root).parts[0]
if directory not in ("input", "output"):
raise ValueError("Media path outside input/output")
return "/work/" + str(path.relative_to(root))
def run(*command):
print("+", " ".join(map(str, command)), flush=True)
subprocess.run([str(part) for part in command], check=True)
def has_stream(path, kind):
result = subprocess.run([
"ffprobe", "-v", "error", "-show_entries", "stream=codec_type",
"-of", "json", str(path),
], check=True, capture_output=True, text=True)
return kind in [stream["codec_type"] for stream in json.loads(result.stdout)["streams"]]
def probe(path, kind):
if not has_stream(path, kind):
raise RuntimeError(f"Missing {kind} stream: {path}")
def duration(path):
result = subprocess.run([
"ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", str(path),
], check=True, capture_output=True, text=True)
return float(result.stdout.strip())
def output_path(root, video, suffix, extension="mp4"):
return root / "output" / f"{video.stem}-{suffix}.{extension}"
def mix_target(root, args):
name = args.output or f"{Path(args.vocals).stem}-mix.wav"
return wav_target(root, name)
def wav_target(root, name):
if not NAME.fullmatch(name) or Path(name).suffix.lower() != ".wav":
raise ValueError("Use a simple WAV output filename")
target = root / "output" / name
if target.exists() or target.is_symlink():
raise FileExistsError(target)
return target
def process_voice(args, root, launcher):
source = audio_file(root, args.audio)
probe(source, "audio")
target = wav_target(root, args.output or f"{source.stem}-mia_voce.wav")
job = root / "output" / f".{source.stem}-voice-convert-{args.job_id}"
job.mkdir(mode=0o700)
print("Working directory:", job, flush=True)
prepared = job / "audio.wav"
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
"-i", container_path(root, source), "-map", "0:a:0", "-vn",
"-c:a", "pcm_s16le", container_path(root, prepared))
run(launcher, "rvc", "cli", container_path(root, prepared),
container_path(root, job), "--convert-only")
converted = job / "vocals-mia_voce.wav"
probe(converted, "audio")
os.link(converted, target)
return target
def process_mix(args, root, launcher):
vocals = audio_file(root, args.vocals)
instrumental = audio_file(root, args.instrumental)
target = mix_target(root, args)
for source in (vocals, instrumental):
probe(source, "audio")
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
"-i", container_path(root, vocals), "-i", container_path(root, instrumental),
"-filter_complex", "[0:a][1:a]amix=inputs=2:duration=longest:normalize=0[a]",
"-map", "[a]", "-c:a", "pcm_s16le", container_path(root, target))
probe(target, "audio")
return target
def mux(launcher, root, video, audio, target):
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
"-i", container_path(root, video), "-i", container_path(root, audio),
"-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac",
"-b:a", "192k", "-shortest", "-movflags", "+faststart",
container_path(root, target))
probe(target, "video")
probe(target, "audio")
def download_video(root, url, job_id):
video_url(url)
if not job_id or not NAME.fullmatch(job_id):
raise ValueError("Invalid job ID")
if shutil.which("yt-dlp") is None:
raise RuntimeError("yt-dlp is required for URL downloads")
prefix = f"download-{job_id}"
destination = root / "input" / f"{prefix}.mp4"
if list((root / "input").glob(prefix + ".*")):
raise FileExistsError(destination)
print("Downloading one video into input/ with yt-dlp", flush=True)
subprocess.run([
"yt-dlp", "--ignore-config", "--no-playlist", "--no-overwrites",
"--no-progress", "-t", "mp4", "--recode-video", "mp4",
"--output", str(root / "input" / f"{prefix}.%(ext)s"), url,
], check=True)
if not destination.is_file() or destination.is_symlink():
raise RuntimeError("yt-dlp did not produce the expected MP4 in input/")
probe(destination, "video")
return destination
def process_split(args, root, launcher, video):
probe(video, "audio")
target = root / "output" / f"{video.stem}-{args.preset}"
if target.exists():
raise FileExistsError(target)
job = root / "output" / f".{video.stem}-{args.preset}-{args.job_id}"
job.mkdir(mode=0o700)
print("Working directory:", job, flush=True)
silent = job / "video.mp4"
audio = job / "audio.wav"
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
"-i", container_path(root, video), "-map", "0:v:0", "-c:v", "copy",
"-an", "-movflags", "+faststart", container_path(root, silent))
probe(silent, "video")
if has_stream(silent, "audio"):
raise RuntimeError("Unexpected audio stream in split video")
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
"-i", container_path(root, video), "-map", "0:a:0", "-vn",
"-c:a", "pcm_s16le", container_path(root, audio))
probe(audio, "audio")
files = {"video.mp4": silent, "audio.wav": audio}
if args.preset == "split-stems":
run(launcher, "rvc", "cli", container_path(root, audio),
container_path(root, job), "--separate-only")
for stem in ("vocals", "instrumental"):
matches = list((job / stem).glob("*.wav"))
if len(matches) != 1:
raise RuntimeError(f"Expected exactly one {stem} stem")
probe(matches[0], "audio")
files[f"{stem}.wav"] = matches[0]
# Publish only after every processing step and stream check succeeded.
target.mkdir(mode=0o700)
for name, source in files.items():
os.link(source, target / name)
return target
def process(args, root, launcher):
video = media_file(root, args.video, video=True)
probe(video, "video")
if args.preset in ("split", "split-stems"):
return process_split(args, root, launcher, video)
if args.preset == "merge":
audio = audio_file(root, args.audio)
probe(audio, "audio")
target = output_path(root, video, "unito")
if target.exists():
raise FileExistsError(target)
mux(launcher, root, video, audio, target)
return target
suffix = "mia_voce" if args.preset == "audio-convert" else "facefusion"
target = output_path(root, video, suffix, "wav" if args.preset == "audio-convert" else "mp4")
if target.exists():
raise FileExistsError(target)
job = root / "output" / f".{video.stem}-{suffix}-{args.job_id}"
job.mkdir(mode=0o700)
print("Working directory:", job, flush=True)
if args.preset == "audio-convert":
probe(video, "audio")
extracted = job / "audio.wav"
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
"-i", container_path(root, video), "-vn", "-c:a", "pcm_s16le",
container_path(root, extracted))
run(launcher, "rvc", "cli", container_path(root, extracted), container_path(root, job))
instrumental = list((job / "instrumental").glob("*.wav"))
if len(instrumental) != 1:
raise RuntimeError("Expected exactly one instrumental stem")
converted = job / "vocals-mia_voce.wav"
probe(converted, "audio")
mixed = job / "mix.wav"
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
"-i", container_path(root, instrumental[0]),
"-i", container_path(root, converted),
"-filter_complex", "[0:a][1:a]amix=inputs=2:duration=longest:normalize=0[a]",
"-map", "[a]", "-c:a", "pcm_s16le", container_path(root, mixed))
probe(mixed, "audio")
os.link(mixed, target)
else:
original_has_audio = has_stream(video, "audio")
sources = [media_file(root, name) for name in SOURCE_NAMES]
processed = job / "swapped.mp4"
run(launcher, "facefusion", "cli", "headless-run",
"--source-paths", *[container_path(root, path) for path in sources],
"--target-path", container_path(root, video),
"--output-path", container_path(root, processed),
"--processors", "face_swapper", "--face-swapper-model", "hyperswap_1a_256",
"--face-swapper-pixel-boost", "256x256", "--face-swapper-weight", "0.5",
"--face-detector-model", "yolo_face", "--face-detector-size", "640x640",
"--face-detector-angles", "0", "90", "180", "270",
"--face-detector-score", "0.5", "--face-selector-mode", "one",
"--face-selector-order", "large-small", "--face-selector-gender", "female",
"--face-selector-race", "white",
"--face-mask-types", "occlusion", "region", "area", "box",
"--face-occluder-model", "xseg_1",
"--face-parser-model", "bisenet_resnet_34", "--face-mask-blur", "0.3",
"--output-video-encoder", "libx264", "--output-video-preset", "veryfast",
"--output-video-quality", "80", "--output-video-fps", "30",
"--execution-providers", "cpu", "--output-audio-encoder", "aac",
"--jobs-path", "/work/state", "--temp-path", "/work/state/tmp")
probe(processed, "video")
if abs(duration(processed) - duration(video)) > 0.5:
raise RuntimeError("FaceFusion output duration differs from the input; refusing a partial result")
if original_has_audio:
# Restore the original soundtrack explicitly. Some completed
# FaceFusion jobs have produced video-only MP4 files.
mux(launcher, root, processed, video, target)
else:
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
"-i", container_path(root, processed), "-map", "0:v:0",
"-c:v", "copy", "-an", "-movflags", "+faststart",
container_path(root, target))
probe(target, "video")
if has_stream(target, "audio"):
raise RuntimeError("Unexpected audio stream in silent FaceFusion output")
return target
def process_complete(args, root, launcher):
video = media_file(root, args.video, video=True)
if not has_stream(video, "audio"):
raise RuntimeError("The video has no audio to convert")
common = {"video": video.name, "job_id": args.job_id}
audio = process(argparse.Namespace(preset="audio-convert", **common), root, launcher)
swapped = process(argparse.Namespace(preset="video-convert", **common), root, launcher)
target = output_path(root, video, "completo")
if target.exists():
raise FileExistsError(target)
mux(launcher, root, swapped, audio, target)
return target
def main():
parser = argparse.ArgumentParser(prog="ai-media preset")
parser.add_argument("root", type=Path, help=argparse.SUPPRESS)
parser.add_argument("launcher", type=Path, help=argparse.SUPPRESS)
parser.add_argument("--run", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--job-id", help=argparse.SUPPRESS)
sub = parser.add_subparsers(dest="preset", required=True)
for name in ("audio-convert", "video-convert", "merge", "split", "split-stems", "convert"):
command = sub.add_parser(name)
command.add_argument("video", help="MP4 filename inside input/ or HTTP(S) video URL")
if name == "merge":
command.add_argument("audio", help="unique audio filename in input/ or output/")
mix = sub.add_parser("mix", help="mix vocal and instrumental audio into one WAV")
mix.add_argument("vocals", help="vocal audio path relative to input/ or output/")
mix.add_argument("instrumental", help="instrumental audio path relative to input/ or output/")
mix.add_argument("--output", help="WAV filename in output/ (default: <vocals>-mix.wav)")
voice = sub.add_parser("voice-convert", help="apply mia_voce directly to an audio file")
voice.add_argument("audio", help="audio path relative to input/ or output/")
voice.add_argument("--output", help="WAV filename in output/ (default: <audio>-mia_voce.wav)")
args = parser.parse_args()
root = args.root.resolve(strict=True)
launcher = args.launcher.resolve(strict=True)
audio_only = args.preset in ("mix", "voice-convert")
remote_video = not audio_only and not NAME.fullmatch(args.video)
if args.preset == "voice-convert":
source = audio_file(root, args.audio)
wav_target(root, args.output or f"{source.stem}-mia_voce.wav")
preset_inputs = [args.audio]
if args.output:
preset_inputs += ["--output", args.output]
elif args.preset == "mix":
audio_file(root, args.vocals)
audio_file(root, args.instrumental)
mix_target(root, args)
preset_inputs = [args.vocals, args.instrumental]
if args.output:
preset_inputs += ["--output", args.output]
elif remote_video:
video_url(args.video)
if shutil.which("yt-dlp") is None:
raise RuntimeError("yt-dlp is required for URL downloads")
else:
media_file(root, args.video, video=True)
if not audio_only:
preset_inputs = [args.video] + ([args.audio] if args.preset == "merge" else [])
if args.preset == "merge":
audio_file(root, args.audio)
if args.preset in ("video-convert", "convert"):
for name in SOURCE_NAMES:
media_file(root, name)
if args.run:
if remote_video:
args.video = download_video(root, args.video, args.job_id).name
if args.preset == "voice-convert":
result = process_voice(args, root, launcher)
elif args.preset == "mix":
result = process_mix(args, root, launcher)
else:
result = (process_complete(args, root, launcher)
if args.preset == "convert" else process(args, root, launcher))
print("Completed:", result, flush=True)
return
unit = "ai-media-preset-" + datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]
subprocess.run(["systemd-run", "--user", "--collect", f"--unit={unit}",
"--property=Type=exec", "--property=Restart=no",
"/usr/bin/python3", str(Path(__file__).resolve()), str(root), str(launcher),
"--run", "--job-id", unit, args.preset,
*preset_inputs], check=True)
print("Job:", unit)
print("Logs: journalctl --user -fu", unit)
if __name__ == "__main__":
try:
main()
except (ValueError, FileNotFoundError, FileExistsError, subprocess.CalledProcessError) as error:
raise SystemExit(str(error)) from error

View File

@@ -0,0 +1,94 @@
"""Offline RVC worker for the voice preset (runs inside the RVC container)."""
import argparse
import os
from pathlib import Path
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument("input_wav", type=Path)
parser.add_argument("job_dir", type=Path)
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--separate-only", action="store_true")
mode.add_argument("--convert-only", action="store_true")
args = parser.parse_args()
source = args.input_wav.resolve(strict=True)
job = args.job_dir.resolve(strict=True)
output = Path("/work/output").resolve(strict=True)
if not source.is_relative_to(output) or not job.is_relative_to(output):
raise ValueError("RVC preset paths must be inside /work/output")
if source.parent != job or not source.is_file():
raise ValueError("Expected the extracted WAV inside the job directory")
weights = Path("/work/state/weights/mia_voce.pth")
index = Path("/work/state/mia_voce/added_IVF256_Flat_nprobe_1_mia_voce_v2.index")
if not args.separate_only and not weights.is_file():
raise FileNotFoundError(weights)
if not args.separate_only and not index.is_file():
raise FileNotFoundError(index)
os.environ.update(
weight_root="/work/state/weights",
outside_index_root="/work/models/indices",
index_root="/work/state",
weight_pymss_root="/opt/app/assets/pymss_weights",
rmvpe_root="/opt/app/assets/rmvpe",
OMP_NUM_THREADS="4",
MKL_NUM_THREADS="4",
)
# The pinned WebUI imports its own argparse configuration at module load.
sys.argv = sys.argv[:1]
vocal_source = source
if not args.convert_only:
from tools.pymss_webui import pymss_separate
vocals_dir = job / "vocals"
instrumental_dir = job / "instrumental"
vocals_dir.mkdir()
instrumental_dir.mkdir()
failures = []
def on_event(event):
if event.get("event") in ("fatal", "cancelled", "busy"):
failures.append(event.get("message", str(event)))
for progress in pymss_separate(
"vocals-bs-roformer-368", str(source), str(vocals_dir), None,
str(instrumental_dir), "wav", event_callback=on_event,
):
print(progress, flush=True)
if failures:
raise RuntimeError("RVC separation failed: " + "; ".join(failures))
vocals = list(vocals_dir.glob("*.wav"))
instrumental = list(instrumental_dir.glob("*.wav"))
if len(vocals) != 1 or len(instrumental) != 1:
raise RuntimeError("RVC did not produce exactly one vocal and instrumental stem")
if args.separate_only:
print("Vocal and instrumental stems ready (no voice conversion)", flush=True)
return
vocal_source = vocals[0]
from configs.config import Config
from infer.vc.modules import VC
import soundfile as sf
voice = VC(Config())
voice.get_vc(weights.name)
status, result = voice.vc_single(
0, str(vocal_source), 0, "rmvpe", str(index), 0.75, 0, 1, 0.33,
)
if result is None or result[0] is None or result[1] is None:
raise RuntimeError("RVC voice conversion failed: " + str(status))
converted = job / "vocals-mia_voce.wav"
sf.write(converted, result[1], result[0])
if converted.stat().st_size == 0:
raise RuntimeError("RVC produced an empty converted voice")
print("RVC converted voice ready", flush=True)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,63 @@
--index-url https://pypi.org/simple
aiofiles==24.1.0
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.15.1
brotli==1.2.0
certifi==2026.7.22
click==8.5.0
fastapi==0.143.0
ffmpy==1.0.0
filelock==4.1.1
flatbuffers==25.12.19
fsspec==2026.9.0
gradio==5.50.0
gradio_client==1.14.0
gradio_rangeslider==0.0.8
groovy==0.1.2
h11==0.16.0
hf-xet==1.7.0
httpcore==1.0.9
httpx==0.28.1
huggingface_hub==1.33.0
idna==3.20
Jinja2==3.1.6
markdown-it-py==4.2.0
MarkupSafe==3.0.4
mdurl==0.1.2
ml_dtypes==0.6.0
numpy==2.4.6
onnx==1.23.1
onnxruntime==1.30.0
opencv-python-headless==5.0.0.93
opentelemetry-api==1.45.1
orjson==3.13.0
packaging==26.3
pandas==2.3.3
pillow==11.3.0
pip==25.0.1
protobuf==7.36.2
pydantic==2.12.3
pydantic_core==2.41.4
pydub==0.25.1
Pygments==2.21.0
python-dateutil==2.9.0.post0
python-multipart==0.0.32
pytz==2026.5
PyYAML==6.0.3
rich==15.0.0
ruff==0.17.0
safehttpx==0.1.7
scipy==1.18.1
semantic-version==2.10.0
shellingham==1.5.4
six==1.17.0
starlette==0.52.1
tomlkit==0.13.3
tqdm==4.70.1
typer==0.27.3
typing-inspection==0.4.4
typing_extensions==4.16.0
tzdata==2026.5
uvicorn==0.54.0
websockets==15.0.1

View File

@@ -0,0 +1,120 @@
--index-url https://pypi.org/simple
--extra-index-url https://download.pytorch.org/whl/cpu
absl-py==2.5.1
aiohappyeyeballs==2.7.1
aiohttp==3.14.5
aiosignal==1.4.0
altair==4.2.2
anyio==3.7.1
attrs==26.1.0
audioread==3.1.0
av==15.1.0
certifi==2026.7.22
cffi==2.1.1
charset-normalizer==3.5.2
click==8.5.0
cloudpickle==3.1.2
coloredlogs==15.0.1
contourpy==1.3.3
cycler==0.12.1
decorator==5.3.1
einops==0.8.2
entrypoints==0.4
faiss-cpu==1.15.1
fastapi==0.99.1
ffmpeg-python==0.2.0
ffmpy==1.0.0
filelock==4.1.1
flatbuffers==25.12.19
fonttools==4.66.1
FreeSimpleGUI==5.1.1
frozenlist==1.8.0
fsspec==2026.9.0
future==1.0.0
gradio==3.14.0
grpcio==1.84.0
h11==0.14.0
hf-xet==1.7.0
httpcore==0.16.3
httpx==0.23.3
huggingface_hub==0.36.2
humanfriendly==10.0
hyper-connections==0.4.2
idna==3.20
Jinja2==3.1.6
joblib==1.6.0
jsonschema==4.26.0
jsonschema-specifications==2025.9.1
kiwisolver==1.5.1
lazy-loader==0.6
librosa==0.10.2.post1
linkify-it-py==2.2.0
llvmlite==0.50.0
local-attention==1.11.2
Markdown==3.11
markdown-it-py==2.2.0
MarkupSafe==3.0.4
matplotlib==3.11.2
mdit-py-plugins==0.3.5
mdurl==0.1.2
mpmath==1.3.0
msgpack==1.2.3
multidict==7.1.0
narwhals==2.27.1
networkx==3.7
numba==0.68.0
numpy==1.26.4
onnxruntime==1.31.0
opencv-python-headless==4.11.0.86
orjson==3.13.0
packaging==26.3
pandas==3.0.6
pillow==12.3.0
pip==25.0.1
platformdirs==4.13.0
pooch==1.9.0
praat-parselmouth==0.4.7
propcache==0.5.4
protobuf==7.36.2
pycparser==3.11
pycryptodome==3.24.1
pydantic==1.10.26
pydub==0.25.1
pyparsing==3.0.9
python-dateutil==2.9.0.post0
python-multipart==0.0.32
PyYAML==6.0.3
referencing==0.37.0
regex==2026.9.29
requests==2.34.2
rfc3986==1.5.0
rpds-py==2026.9.1
safetensors==0.8.0
scikit-learn==1.9.1
scipy==1.17.1
setuptools==80.10.2
six==1.17.0
sniffio==1.3.1
sounddevice==0.5.6
soundfile==0.14.0
soxr==1.1.0
starlette==0.27.0
sympy==1.14.0
tensorboard==2.21.0
tensorboard-data-server==0.7.2
threadpoolctl==3.7.0
tokenizers==0.21.4
toolz==1.2.0
torch==2.4.1+cpu
torchaudio==2.4.1+cpu
torchfcpe==0.0.4
torchvision==0.19.1+cpu
tqdm==4.70.1
transformers==4.49.0
typing_extensions==4.16.0
urllib3==2.8.0
uvicorn==0.22.0
websockets==10.4
Werkzeug==3.1.9
wheel==0.48.0
yarl==1.25.1

View File

@@ -0,0 +1,111 @@
import os
import pathlib
import signal
import shutil
import subprocess
import sys
import time
import urllib.request
app = os.environ["APP"]
os.chdir("/opt/app")
if sys.argv[1:] == ["verify"]:
os.execv(sys.executable, [sys.executable, "/opt/verify.py"])
if sys.argv[1:2] == ["ffmpeg"]:
os.execv("/usr/bin/ffmpeg", ["ffmpeg", *sys.argv[2:]])
if sys.argv[1:2] == ["cli"]:
if app != "facefusion":
raise SystemExit("CLI is available for FaceFusion only")
os.execv(sys.executable, [sys.executable, "facefusion.py", *sys.argv[2:]])
if app == "facefusion":
command = [
sys.executable, "facefusion.py", "run",
"--execution-providers", "cpu", "--processors", "face_swapper",
"--temp-path", "/work/state/tmp", "--jobs-path", "/work/state",
"--output-path", "/work/output",
]
port = 7860
else:
pathlib.Path("/tmp/rvc-temp").mkdir(exist_ok=True)
weights = pathlib.Path("/work/state/weights")
weights.mkdir(exist_ok=True)
for source in pathlib.Path("/work/models/weights").glob("*.pth"):
target = weights / source.name
if not target.exists() and not target.is_symlink():
target.symlink_to(source)
fixture = pathlib.Path("/opt/training-fixture/mute")
for source in fixture.rglob("*"):
target = pathlib.Path("/work/state/mute") / source.relative_to(fixture)
if source.is_dir():
target.mkdir(parents=True, exist_ok=True)
elif not target.exists():
shutil.copyfile(source, target)
os.environ.update(
weight_root="/work/state/weights",
outside_index_root="/work/models/indices",
index_root="/work/state",
weight_pymss_root="/opt/app/assets/pymss_weights",
)
command = [sys.executable, "webui.py", "--noautoopen", "--port", "7865"]
port = 7865
server = subprocess.Popen(command)
browser = None
profile = pathlib.Path("/tmp/browser")
profile.mkdir(exist_ok=True)
(profile / "user.js").write_text('''
user_pref("browser.download.folderList", 2);
user_pref("browser.download.dir", "/work/output");
user_pref("browser.download.useDownloadDir", true);
user_pref("widget.use-xdg-desktop-portal.file-picker", 0);
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.aboutwelcome.enabled", false);
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("toolkit.telemetry.enabled", false);
''')
bookmarks = pathlib.Path.home() / ".config/gtk-3.0/bookmarks"
bookmarks.parent.mkdir(parents=True, exist_ok=True)
bookmarks.write_text("file:///work/input Input\nfile:///work/output Output\nfile:///work/models Models\n")
def stop(*_):
if browser is not None and browser.poll() is None:
browser.terminate()
if server.poll() is None:
server.terminate()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
try:
url = f"http://127.0.0.1:{port}"
for _ in range(180):
if server.poll() is not None:
raise RuntimeError(f"{app} exited: {server.returncode}")
try:
with urllib.request.urlopen(url, timeout=1) as response:
if response.status == 200:
break
except OSError:
time.sleep(1)
else:
raise RuntimeError("Offline WebUI did not become ready")
print(f"{app}: offline WebUI ready", flush=True)
if sys.argv[1:] == ["smoke"]:
subprocess.run([
"firefox-esr", "--headless", "--no-remote", "--profile", "/tmp/browser",
"--screenshot", "/tmp/offline-ui.png", url,
], check=True, timeout=90)
assert pathlib.Path("/tmp/offline-ui.png").stat().st_size > 1000
raise SystemExit(0)
browser = subprocess.Popen([
"firefox-esr", "--no-remote", "--profile", "/tmp/browser", url,
])
while browser.poll() is None:
if server.poll() is not None:
raise RuntimeError("WebUI terminated unexpectedly")
time.sleep(1)
finally:
stop()
if browser is not None:
browser.wait(timeout=15)
server.wait(timeout=15)

View File

@@ -0,0 +1,139 @@
import os
import gc
import pathlib
import socket
import subprocess
import sys
import tempfile
interfaces = {p.name for p in pathlib.Path("/sys/class/net").iterdir()}
assert interfaces == {"lo"}, interfaces
for family, address in (
(socket.AF_INET, ("1.1.1.1", 443)),
(socket.AF_INET6, ("2606:4700:4700::1111", 443, 0, 0)),
):
with socket.socket(family, socket.SOCK_STREAM) as connection:
connection.settimeout(2)
try:
connection.connect(address)
except OSError:
pass
else:
raise RuntimeError("External networking is available")
subprocess.run(["sha256sum", "--quiet", "--check", "/opt/model-checksums.sha256"], check=True)
if os.environ["APP"] == "facefusion":
sys.path.insert(0, "/opt/app")
from facefusion import state_manager
from facefusion.args import apply_args
from facefusion.program import create_program
from facefusion.core import common_pre_check, processors_pre_check
args = vars(create_program().parse_args([
"run", "--execution-providers", "cpu", "--processors", "face_swapper",
]))
apply_args(args, state_manager.init_item)
assert common_pre_check() and processors_pre_check()
import numpy as np
import onnxruntime as ort
options = ort.SessionOptions()
options.intra_op_num_threads = 4
options.inter_op_num_threads = 1
model = ort.InferenceSession(
"/opt/app/.assets/models/hyperswap_1a_256.onnx",
sess_options=options, providers=["CPUExecutionProvider"],
)
feeds = {}
for argument in model.get_inputs():
assert argument.type == "tensor(float)"
shape = [size if isinstance(size, int) and size > 0 else 1 for size in argument.shape]
feeds[argument.name] = np.full(shape, 0.01, dtype=np.float32)
assert all(np.isfinite(result).all() for result in model.run(None, feeds))
else:
sys.path.insert(0, "/opt/app")
import numpy as np
import torch
import transformers
import onnxruntime
assert not torch.cuda.is_available()
torch.set_num_threads(4)
from infer.hubert import load_hubert_model, extract_hubert_features
from infer.rmvpe import RMVPE
with torch.inference_mode():
hubert = load_hubert_model("cpu", False)
features = extract_hubert_features(hubert, torch.zeros(1, 16000), "v2")
assert torch.isfinite(features).all()
del hubert, features
pitch = RMVPE("/opt/app/assets/rmvpe/rmvpe.pt", False, "cpu")
result = pitch.infer_from_audio(np.zeros(16000, dtype=np.float32))
assert len(result) > 0 and np.isfinite(result).all()
del pitch
gc.collect()
# Exercise the exact WebUI subprocess entrypoint, not only in-process imports.
from scipy.io import wavfile
with tempfile.TemporaryDirectory(prefix="rvc-slicing-") as temporary:
directory = pathlib.Path(temporary)
dataset = directory / "input"
experiment = directory / "experiment"
dataset.mkdir()
experiment.mkdir()
samples = np.arange(4 * 40000, dtype=np.float32) / 40000
waveform = (0.2 * np.sin(2 * np.pi * 220 * samples)).astype(np.float32)
wavfile.write(dataset / "synthetic.wav", 40000, waveform)
subprocess.run([
sys.executable, "train/preprocess.py", str(dataset), "40000", "1",
str(experiment), "False", "3.7",
], check=True, timeout=120)
assert list((experiment / "0_gt_wavs").glob("*.wav"))
assert list((experiment / "1_16k_wavs").glob("*.wav"))
print("rvc: synthetic data slicing subprocess verified", flush=True)
# Check the v2/40k training baseline and writable inference-model export.
from train.utils import get_hparams_from_file
from train.process_ckpt import savee
hps = get_hparams_from_file("configs/v1/40k.json")
checkpoint = torch.load("assets/pretrained_v2/f0G40k.pth", map_location="cpu")
assert checkpoint["model"]
pathlib.Path("/work/state/weights").mkdir(exist_ok=True)
savee(checkpoint["model"], "40k", 1, "offline-readiness", 0, "v2", hps)
exported = pathlib.Path("assets/weights/offline-readiness.pth")
assert exported.is_file()
exported.unlink()
del checkpoint
checkpoint = torch.load("assets/pretrained_v2/f0D40k.pth", map_location="cpu")
assert checkpoint["model"]
del checkpoint
assert pathlib.Path("/opt/training-fixture/mute/0_gt_wavs/mute40k.wav").is_file()
print("rvc: v2/40k training assets and model export verified", flush=True)
# Exercise the WebUI's real worker and encoder on a synthetic stereo mix.
with tempfile.TemporaryDirectory(prefix="rvc-separation-") as temporary:
directory = pathlib.Path(temporary)
sample_rate = 44100
time_axis = np.arange(2 * sample_rate, dtype=np.float32) / sample_rate
left = 0.1 * np.sin(2 * np.pi * 220 * time_axis)
right = 0.1 * np.sin(2 * np.pi * 330 * time_axis)
mix = np.stack((left, right), axis=1).astype(np.float32)
wavfile.write(directory / "synthetic.wav", sample_rate, mix)
subprocess.run([
sys.executable, "-c",
"import sys; from pathlib import Path; p=Path(sys.argv[1]); sys.argv=sys.argv[:1]; "
"from tools.pymss_webui import pymss_separate, resolve_model, PYMSS_MODEL_CHOICES; "
"assert PYMSS_MODEL_CHOICES == [resolve_model('vocals-bs-roformer-368').label]; "
"list(pymss_separate('vocals-bs-roformer-368', str(p/'synthetic.wav'), "
"str(p/'vocals'), None, str(p/'instrumental'), 'wav'))",
str(directory),
], check=True, timeout=600, env={
**os.environ, "OMP_NUM_THREADS": "4", "MKL_NUM_THREADS": "4",
})
import soundfile as sf
stems = []
for name in ("vocals", "instrumental"):
files = list((directory / name).glob("*.wav"))
assert len(files) == 1, (name, files)
data, rate = sf.read(files[0], dtype="float32", always_2d=True)
assert rate == sample_rate and data.shape == mix.shape
assert np.isfinite(data).all()
stems.append(data)
assert np.allclose(stems[0] + stems[1], mix, atol=1e-4)
print("rvc: offline stereo vocal/instrumental separation verified", flush=True)
gc.collect()
subprocess.run([sys.executable, "/opt/session.py", "smoke"], check=True)
print(os.environ["APP"] + ": models verified, offline UI ready, IPv4/IPv6 egress blocked")

View File

@@ -0,0 +1,4 @@
---
- name: Reload systemd units
ansible.builtin.systemd_service:
daemon_reload: true

View File

@@ -0,0 +1,343 @@
---
- name: Configure on-demand external ai-media storage
become: true
when: desktop_ai_media_external_storage_enabled | bool
tags: [ai_media, ai_media_storage]
block:
- name: Validate external ai-media storage paths
ansible.builtin.assert:
that:
- desktop_ai_media_external_mountpoint is match('^/run/media/[^/]+/[^/]+$')
- >-
not desktop_ai_media_external_luks_uuid or
desktop_ai_media_external_luks_uuid is match('^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$')
- desktop_ai_media_external_source.startswith(desktop_ai_media_external_mountpoint + '/')
- desktop_ai_media_external_source != desktop_ai_media_external_mountpoint
- desktop_ai_media_root.startswith(user_home + '/')
- desktop_ai_media_root != user_home
- name: Derive external source mount unit name
ansible.builtin.command:
argv:
- systemd-escape
- -p
- --suffix=mount
- "{{ desktop_ai_media_external_mountpoint }}"
register: desktop_ai_media_external_source_mount_unit
changed_when: false
check_mode: false
- name: Derive ai-media bind mount unit name
ansible.builtin.command:
argv:
- systemd-escape
- -p
- --suffix=mount
- "{{ desktop_ai_media_root }}"
register: desktop_ai_media_bind_mount_unit
changed_when: false
check_mode: false
- name: Derive ai-media bind automount unit name
ansible.builtin.command:
argv:
- systemd-escape
- -p
- --suffix=automount
- "{{ desktop_ai_media_root }}"
register: desktop_ai_media_bind_automount_unit
changed_when: false
check_mode: false
- name: Create ai-media mount destination in the user home
ansible.builtin.file:
path: "{{ desktop_ai_media_root }}"
state: directory
owner: "{{ username }}"
group: "{{ username }}"
mode: "0700"
- name: Install ai-media bind mount unit
ansible.builtin.template:
src: ai-media-bind.mount.j2
dest: "/etc/systemd/system/{{ desktop_ai_media_bind_mount_unit.stdout }}"
owner: root
group: root
mode: "0644"
notify: Reload systemd units
- name: Install ai-media bind automount unit
ansible.builtin.template:
src: ai-media-bind.automount.j2
dest: "/etc/systemd/system/{{ desktop_ai_media_bind_automount_unit.stdout }}"
owner: root
group: root
mode: "0644"
notify: Reload systemd units
- name: Install ai-media bind automount failure restarter
ansible.builtin.template:
src: ai-media-bind-restarter.service.j2
dest: /etc/systemd/system/ai-media-bind-restarter.service
owner: root
group: root
mode: "0644"
notify: Reload systemd units
- name: Flush systemd unit changes
ansible.builtin.meta: flush_handlers
- name: Stop a stale ai-media bind mount when the Backup source is absent
ansible.builtin.systemd_service:
name: "{{ desktop_ai_media_bind_mount_unit.stdout }}"
state: stopped
when:
- desktop_ai_media_root in (ansible_facts['mounts'] | default([]) | selectattr('fstype', 'ne', 'autofs') | map(attribute='mount') | list)
- desktop_ai_media_external_mountpoint not in (ansible_facts['mounts'] | default([]) | map(attribute='mount') | list)
- name: Enable and start ai-media bind automount
ansible.builtin.systemd_service:
name: "{{ desktop_ai_media_bind_automount_unit.stdout }}"
enabled: true
state: started
- name: Configure isolated desktop media tools as the desktop user
become: false
block:
- name: Determine whether the ai-media storage source is currently available
ansible.builtin.set_fact:
desktop_ai_media_external_available: >-
{{ (not (desktop_ai_media_external_storage_enabled | bool)) or
(desktop_ai_media_external_mountpoint in
(ansible_facts['mounts'] | default([]) | map(attribute='mount') | list)) }}
- name: Load pinned public model manifest
ansible.builtin.include_vars: models.yml
- name: Identify unprivileged desktop user
ansible.builtin.command:
argv: [id, -un]
register: desktop_ai_media_user
changed_when: false
check_mode: false
- name: Verify local Fedora desktop scope
ansible.builtin.assert:
that:
- "'platform_fedora' in group_names"
- "'desktop_gnome' in group_names"
- ansible_connection == 'local'
- desktop_ai_media_user.stdout == username
- ansible_facts.architecture == 'x86_64'
- desktop_ai_media_root.startswith(user_home + '/')
- desktop_ai_media_root != user_home
- desktop_ai_media_build_root != desktop_ai_media_root
- desktop_ai_media_facefusion_revision is match('^[0-9a-f]{40}$')
- desktop_ai_media_rvc_revision is match('^[0-9a-f]{40}$')
- "'@sha256:' in desktop_ai_media_base_image"
- desktop_ai_media_debian_snapshot is match('^[0-9]{8}T[0-9]{6}Z$')
- desktop_ai_media_public_models | length > 0
- >-
desktop_ai_media_apps | difference(
desktop_ai_media_public_models | map(attribute='app') | list) | length == 0
- name: Verify existing rootless Podman runtime
ansible.builtin.command:
argv: [podman, --remote=false, info, --format, "{{ '{{.Host.Security.Rootless}}' }}"]
register: desktop_ai_media_podman
changed_when: false
check_mode: false
- name: Require rootless containers
ansible.builtin.assert:
that: desktop_ai_media_podman.stdout == 'true'
- name: Reject remote or synchronized media storage before provisioning
ansible.builtin.command:
argv: [python3, "-", "{{ desktop_ai_media_root }}"]
stdin: "{{ lookup('ansible.builtin.file', role_path + '/files/check_storage.py') }}"
changed_when: false
check_mode: false
when: desktop_ai_media_external_available | bool
- name: Create the data-free local build context
ansible.builtin.file:
path: "{{ desktop_ai_media_build_root }}"
state: directory
mode: "0700"
- name: Create private application and media directories on mounted media storage
ansible.builtin.file:
path: "{{ item }}"
state: directory
mode: "0700"
loop:
- "{{ desktop_ai_media_root }}"
- "{{ desktop_ai_media_root }}/input"
- "{{ desktop_ai_media_root }}/input/voice"
- "{{ desktop_ai_media_root }}/output"
- "{{ desktop_ai_media_root }}/models"
- "{{ desktop_ai_media_root }}/models/weights"
- "{{ desktop_ai_media_root }}/models/indices"
- "{{ desktop_ai_media_root }}/state"
- "{{ desktop_ai_media_root }}/state/facefusion"
- "{{ desktop_ai_media_root }}/state/rvc"
when: desktop_ai_media_external_available | bool
- name: Ensure user launcher directories exist without changing existing permissions
ansible.builtin.file:
path: "{{ item }}"
state: directory
loop:
- "{{ user_home }}/.local/bin"
- "{{ user_home }}/.local/share/applications"
- name: Install runtime and model preparation code into the data-free build context
ansible.builtin.copy:
src: "{{ item }}"
dest: "{{ desktop_ai_media_build_root }}/{{ item }}"
mode: "0644"
loop: [session.py, prepare.py, verify.py, check_storage.py]
register: desktop_ai_media_support
- name: Install host-side offline preset workers without rebuilding images
tags: [ai_media_presets]
ansible.builtin.copy:
src: "{{ item }}"
dest: "{{ desktop_ai_media_build_root }}/{{ item }}"
mode: "0644"
loop: [preset.py, preset_rvc.py]
- name: Create public model cache directories
ansible.builtin.file:
path: "{{ desktop_ai_media_build_root }}/models/{{ item.app }}/{{ item.path | dirname }}"
state: directory
mode: "0700"
loop: "{{ desktop_ai_media_public_models }}"
loop_control:
label: "{{ item.app }}/{{ item.path }}"
- name: Cache public models using pinned SHA256 checksums without personal data
ansible.builtin.get_url:
url: "{{ item.url }}"
dest: "{{ desktop_ai_media_build_root }}/models/{{ item.app }}/{{ item.path }}"
checksum: "sha256:{{ item.sha256 }}"
mode: "0644"
timeout: 60
use_netrc: false
use_proxy: false
loop: "{{ desktop_ai_media_public_models }}"
loop_control:
label: "{{ item.app }}/{{ item.path }}"
register: desktop_ai_media_model_cache
- name: Install complete Python dependency locks
ansible.builtin.copy:
src: "requirements-{{ item }}.lock"
dest: "{{ desktop_ai_media_build_root }}/requirements-{{ item }}.lock"
mode: "0644"
loop: "{{ desktop_ai_media_apps }}"
register: desktop_ai_media_locks
- name: Restrict the build context to code and checksum-pinned public models
ansible.builtin.template:
src: containerignore.j2
dest: "{{ desktop_ai_media_build_root }}/.containerignore"
mode: "0644"
register: desktop_ai_media_ignore
- name: Render separate pinned application builds
ansible.builtin.template:
src: Containerfile.j2
dest: "{{ desktop_ai_media_build_root }}/Containerfile.{{ item }}"
mode: "0644"
loop: "{{ desktop_ai_media_apps }}"
register: desktop_ai_media_containerfiles
- name: Fingerprint the complete application build specification
ansible.builtin.set_fact:
desktop_ai_media_build_keys: >-
{{ desktop_ai_media_build_keys | default({}) | combine({
item: (
lookup('ansible.builtin.template', role_path + '/templates/Containerfile.j2')
+ lookup('ansible.builtin.file', role_path + '/files/prepare.py')
+ lookup('ansible.builtin.file', role_path + '/files/session.py')
+ lookup('ansible.builtin.file', role_path + '/files/verify.py')
+ lookup('ansible.builtin.file', role_path + '/files/requirements-' + item + '.lock')
+ lookup('ansible.builtin.file', role_path + '/templates/containerignore.j2')
) | hash('sha256')
}) }}
loop: "{{ desktop_ai_media_apps }}"
- name: Inspect installed media images
ansible.builtin.command:
argv: [podman, --remote=false, image, exists, "localhost/ai-media-{{ item }}:managed"]
loop: "{{ desktop_ai_media_apps }}"
register: desktop_ai_media_images
failed_when: desktop_ai_media_images.rc not in [0, 1]
changed_when: false
check_mode: false
- name: Inspect committed image build fingerprints
ansible.builtin.command:
argv:
- podman
- --remote=false
- image
- inspect
- --format
- "{{ '{{ index .Labels \"io.fscotto.ai-media.build-key\" }}' }}"
- "localhost/ai-media-{{ item.item }}:managed"
loop: "{{ desktop_ai_media_images.results }}"
loop_control:
label: "{{ item.item }}"
when: item.rc == 0
register: desktop_ai_media_image_keys
changed_when: false
check_mode: false
- name: Build media images without mounting personal data
ansible.builtin.command:
argv:
- podman
- --remote=false
- build
- --http-proxy=false
- --pull=missing
- --label
- "io.fscotto.ai-media.build-key={{ desktop_ai_media_build_keys[item.item] }}"
- --tag
- "localhost/ai-media-{{ item.item }}:managed"
- --file
- "{{ desktop_ai_media_build_root }}/Containerfile.{{ item.item }}"
- "{{ desktop_ai_media_build_root }}"
loop: "{{ desktop_ai_media_images.results }}"
loop_control:
label: "{{ item.item }}"
when: >-
item.rc != 0 or
desktop_ai_media_image_keys.results[desktop_ai_media_apps.index(item.item)].stdout | default('') !=
desktop_ai_media_build_keys[item.item]
changed_when: true
timeout: 3600
- name: Install offline launcher
tags: [ai_media_launcher]
ansible.builtin.template:
src: ai-media.j2
dest: "{{ user_home }}/.local/bin/ai-media"
mode: "0755"
validate: /usr/bin/bash -n %s
- name: Install manual offline desktop entries
ansible.builtin.template:
src: application.desktop.j2
dest: "{{ user_home }}/.local/share/applications/ai-media-{{ item }}.desktop"
mode: "0644"
loop: "{{ desktop_ai_media_apps }}"
- name: Verify offline networking and application readiness without personal files
ansible.builtin.command:
argv: ["{{ user_home }}/.local/bin/ai-media", verify]
changed_when: false
when: not ansible_check_mode

View File

@@ -0,0 +1,40 @@
FROM {{ desktop_ai_media_base_image }}
LABEL io.fscotto.ai-media.models="{{ desktop_ai_media_public_models | selectattr('app', 'equalto', item) | list | to_json | hash('sha256') }}"
ENV DEBIAN_FRONTEND=noninteractive PIP_DISABLE_PIP_VERSION_CHECK=1
RUN sed -i \
-e 's|http://deb.debian.org/debian$|https://snapshot.debian.org/archive/debian/{{ desktop_ai_media_debian_snapshot }}/|' \
-e 's|http://deb.debian.org/debian-security$|https://snapshot.debian.org/archive/debian-security/{{ desktop_ai_media_debian_snapshot }}/|' \
/etc/apt/sources.list.d/debian.sources \
&& apt-get -o Acquire::Check-Valid-Until=false update \
&& apt-get install -y --no-install-recommends \
ca-certificates curl git ffmpeg firefox-esr fonts-dejavu-core libgl1 libglib2.0-0 libportaudio2 \
&& rm -rf /var/lib/apt/lists/*
COPY requirements-{{ item }}.lock /opt/requirements.lock
WORKDIR /opt/app
{% if item == 'facefusion' %}
RUN git init . && git remote add origin https://github.com/facefusion/facefusion.git \
&& git fetch --depth 1 origin {{ desktop_ai_media_facefusion_revision }} \
&& git checkout --detach FETCH_HEAD && rm -rf .git \
&& pip install --no-cache-dir -r /opt/requirements.lock
{% else %}
RUN git init . && git remote add origin https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git \
&& git fetch --depth 1 origin {{ desktop_ai_media_rvc_revision }} \
&& git checkout --detach FETCH_HEAD && rm -rf .git \
&& pip install --no-cache-dir -r /opt/requirements.lock
{% endif %}
{% for model in desktop_ai_media_public_models if model.app == item %}
COPY models/{{ model.app }}/{{ model.path }} /opt/app/{{ model.path }}
{% endfor %}
COPY prepare.py /opt/
RUN python /opt/prepare.py {{ item }} \
&& pip freeze --all > /opt/python-requirements.lock \
&& test -s /opt/model-checksums.sha256
COPY session.py verify.py /opt/
RUN mkdir -p /work/input /work/output /work/state /work/models /home/media
ENV GRADIO_ANALYTICS_ENABLED=False HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
HF_HUB_DISABLE_TELEMETRY=1 DO_NOT_TRACK=1 HOME=/home/media \
XDG_RUNTIME_DIR=/run/media MOZ_ENABLE_WAYLAND=1 GTK_USE_PORTAL=0 \
LIBGL_ALWAYS_SOFTWARE=1 GRADIO_SERVER_NAME=127.0.0.1 GRADIO_SERVER_PORT=7860 \
PYTHONPATH=/opt/app PYTHONSAFEPATH=1 PYTHONDONTWRITEBYTECODE=1 NUMBA_CACHE_DIR=/tmp/numba MPLCONFIGDIR=/tmp/matplotlib \
GRADIO_TEMP_DIR=/tmp/gradio APP={{ item }}
ENTRYPOINT ["python", "/opt/session.py"]

View File

@@ -0,0 +1,7 @@
[Unit]
Description=Recover the ai-media bind automount after an unavailable Backup volume
[Service]
Type=oneshot
ExecStartPre=/usr/bin/sleep 3
ExecStart=/usr/bin/bash -c '/usr/bin/systemctl restart "$(/usr/bin/systemd-escape -p --suffix=automount {{ desktop_ai_media_root }})"'

View File

@@ -0,0 +1,11 @@
[Unit]
Description=On-demand ai-media bind mount from the Backup LUKS volume
ConditionPathIsDirectory={{ desktop_ai_media_root }}
OnFailure=ai-media-bind-restarter.service
[Automount]
Where={{ desktop_ai_media_root }}
TimeoutIdleSec=5min
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,12 @@
[Unit]
Description=Bind mount ai-media from the Backup LUKS volume
RequiresMountsFor={{ desktop_ai_media_external_mountpoint }}
After={{ desktop_ai_media_external_source_mount_unit.stdout }}
BindsTo={{ desktop_ai_media_external_source_mount_unit.stdout }}
ConditionPathIsMountPoint={{ desktop_ai_media_external_mountpoint }}
ConditionPathIsDirectory={{ desktop_ai_media_external_source }}
[Mount]
What={{ desktop_ai_media_external_source }}
Where={{ desktop_ai_media_root }}
Options=bind

View File

@@ -0,0 +1,193 @@
#!/usr/bin/env bash
set -euo pipefail
root={{ desktop_ai_media_root | quote }}
build_root={{ desktop_ai_media_build_root | quote }}
{% set manage_luks = desktop_ai_media_external_storage_enabled | default(false) and desktop_ai_media_external_luks_uuid | default('') %}
{% if manage_luks %}
encrypted={{ ('/dev/disk/by-uuid/' + desktop_ai_media_external_luks_uuid) | quote }}
external_mount={{ desktop_ai_media_external_mountpoint | quote }}
bind_fsroot={{ (desktop_ai_media_external_source | replace(desktop_ai_media_external_mountpoint, '', 1)) | quote }}
fail() { echo "$*" >&2; exit 1; }
read_mapper() {
local devices mapping
devices=$(lsblk -nrpo NAME,TYPE,MAJ:MIN -- "$encrypted") ||
fail "The configured LUKS volume is not available: $encrypted"
mapping=$(awk '$2 == "crypt" {print $1, $3}' <<< "$devices")
[[ "$mapping" != *$'\n'* ]] || fail "Multiple mappings for $encrypted; refusing to continue"
read -r mapper mapper_id <<< "$mapping"
}
mount_info() {
# Inspect the kernel mount table without following the automount path.
findmnt -krnC --mountpoint "$1" --types noautofs --output MAJ:MIN,FSROOT || [[ $? == 1 ]]
}
volume_mounts() {
[[ -n "$mapper_id" ]] || return 0
findmnt -krnC --source "$mapper_id" --output TARGET || [[ $? == 1 ]]
}
require_external_bind() {
read_mapper
[[ -n "$mapper_id" && "$(mount_info "$root")" == "$mapper_id $bind_fsroot" ]] ||
fail "Encrypted media storage is not mounted; run ai-media mount first"
}
manage_volume() {
local action=$1 mapper mapper_id bind_unit automount_unit mounted bind jobs containers
[[ $# == 1 ]] || fail "Usage: ai-media $action"
bind_unit=$(systemd-escape -p --suffix=mount -- "$root")
automount_unit=$(systemd-escape -p --suffix=automount -- "$root")
read_mapper
mounted=$(mount_info "$external_mount")
bind=$(mount_info "$root")
[[ -z "$mounted" || "$mounted" == "$mapper_id /" ]] ||
fail "Unexpected filesystem at $external_mount; refusing to continue"
[[ -z "$bind" || "$bind" == "$mapper_id $bind_fsroot" ]] ||
fail "Unexpected filesystem at $root; refusing to continue"
if [[ "$action" == mount ]]; then
if [[ -z "$mapper" ]]; then
udisksctl unlock --block-device "$encrypted"
read_mapper
[[ -n "$mapper" ]] || fail "No decrypted block device found after unlock"
fi
if [[ -z "$mounted" ]]; then
[[ -z "$(volume_mounts)" ]] || fail "The LUKS volume is already mounted elsewhere"
udisksctl mount --block-device "$mapper"
fi
[[ "$(mount_info "$external_mount")" == "$mapper_id /" ]] ||
fail "The LUKS volume is not mounted at the expected path: $external_mount"
sudo systemctl start "$automount_unit" "$bind_unit"
require_external_bind
echo "Encrypted media storage mounted at $root"
else
jobs=$(systemctl --user list-units --type=service --state=active,activating,deactivating \
--no-legend --no-pager 'ai-media-*.service')
containers=$(podman --remote=false ps -q \
--filter ancestor=localhost/ai-media-facefusion:managed \
--filter ancestor=localhost/ai-media-rvc:managed)
[[ -z "$jobs" && -z "$containers" ]] ||
fail "Stop the running ai-media jobs and applications before unmounting"
sudo systemctl stop ai-media-bind-restarter.service "$automount_unit" "$bind_unit"
[[ -z "$(mount_info "$root")" ]] || fail "The media bind mount is still in use"
mounted=$(volume_mounts)
if [[ -n "$mounted" ]]; then
[[ "$mounted" == "$external_mount" && "$(mount_info "$external_mount")" == "$mapper_id /" ]] ||
fail "The LUKS volume has other mounts; refusing to unmount or lock it"
udisksctl unmount --block-device "$mapper"
fi
if [[ -n "$mapper" ]]; then
[[ -z "$(volume_mounts)" ]] || fail "The LUKS volume is still mounted"
udisksctl lock --block-device "$encrypted"
fi
echo "Encrypted media storage unmounted and locked"
fi
}
{% endif %}
app="${1:-}"
case "$app" in
{% if manage_luks %}
mount|umount) manage_volume "$@"; exit ;;
{% endif %}
facefusion|rvc) shift ;;
ffmpeg) app=facefusion; shift; set -- ffmpeg "$@" ;;
preset)
shift
for path in "$root" "$root/input" "$root/output"; do
[[ -d "$path" && "$(realpath -- "$path")" == "$path" ]] || {
echo "Unsafe or missing media directory: $path" >&2; exit 1;
}
done
{% if manage_luks %}
require_external_bind
{% endif %}
python3 "$build_root/check_storage.py" "$root"
exec python3 "$build_root/preset.py" "$root" "$(realpath -- "$0")" "$@" ;;
verify)
for tool in facefusion rvc; do
podman --remote=false run --rm --pull=never --network=none --read-only \
--cap-drop=ALL --cap-add=SYS_CHROOT \
--security-opt=no-new-privileges --userns=keep-id --http-proxy=false \
--tmpfs "/tmp:rw,nosuid,nodev,size=4g,mode=1777" \
--tmpfs "/home/media:rw,nosuid,nodev,size=128m,mode=1777" \
--tmpfs "/work/state:rw,nosuid,nodev,size=128m,mode=1777" \
--tmpfs "/work/models:rw,nosuid,nodev,size=128m,mode=1777" \
"localhost/ai-media-$tool:managed" verify
done
exit 0 ;;
*) echo "Usage: ai-media {facefusion|rvc|ffmpeg|preset|verify{% if manage_luks %}|mount|umount{% endif %}} [args ...]" >&2; exit 2 ;;
esac
# Fail closed if an existing data path was replaced by a symlink.
for path in "$root" "$root/input" "$root/output" "$root/models" "$root/state/$app"; do
[[ -d "$path" && "$(realpath -- "$path")" == "$path" ]] || {
echo "Unsafe or missing media directory: $path" >&2; exit 1;
}
done
{% if manage_luks %}
require_external_bind
{% endif %}
python3 {{ (desktop_ai_media_build_root + "/check_storage.py") | quote }} "$root"
# Run interactive sessions under the user manager, not the launching terminal.
# No autostart or automatic restart: recovering a training run remains explicit.
if [[ "$app" == rvc || "$app" == facefusion ]] && [[ $# -eq 0 ]]; then
: "${XDG_RUNTIME_DIR:?Run this launcher from the GNOME Wayland session}"
: "${WAYLAND_DISPLAY:?A Wayland session is required}"
[[ "$WAYLAND_DISPLAY" != */* && -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]] || exit 1
active=$(podman --remote=false ps --filter "ancestor=localhost/ai-media-$app:managed" --format '{{ '{{.ID}}' }}')
if [[ -n "$active" ]]; then
echo "$app is already running; leave its training session open." >&2
exit 1
fi
exec systemd-run --user --collect --unit="ai-media-$app" \
--property=Type=exec --property=Restart=no --property=Delegate=yes \
--setenv="XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR" --setenv="WAYLAND_DISPLAY=$WAYLAND_DISPLAY" \
-- /usr/bin/bash "$(realpath -- "$0")" "$app" --foreground
fi
if [[ "${1:-}" == --foreground ]]; then
shift
fi
if [[ "$app" == rvc && "${1:-}" == cli ]]; then
shift
rvc_cli=1
set -- /opt/preset_rvc.py "$@"
else
rvc_cli=0
fi
args=(
run --rm --pull=never --network=none --read-only --userns=keep-id --http-proxy=false
--cap-drop=ALL --security-opt=no-new-privileges
--tmpfs "/tmp:rw,nosuid,nodev,size=8g,mode=1777"
--tmpfs "/home/media:rw,nosuid,nodev,size=128m,mode=1777"
--shm-size=512m
--volume "$root/input:/work/input:ro,Z"
--volume "$root/output:/work/output:rw,Z"
--volume "$root/models:/work/models:ro,Z"
--volume "$root/state/$app:/work/state:rw,Z"
)
if [[ "$rvc_cli" == 1 ]]; then
args+=(--volume "$build_root/preset_rvc.py:/opt/preset_rvc.py:ro,Z" --entrypoint python)
fi
if [[ "$rvc_cli" != 1 && "${1:-}" != cli && "${1:-}" != ffmpeg ]]; then
: "${XDG_RUNTIME_DIR:?Run this launcher from the GNOME Wayland session}"
: "${WAYLAND_DISPLAY:?A Wayland session is required}"
[[ "$WAYLAND_DISPLAY" != */* && -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]] || exit 1
# Share only the display socket, never the runtime directory, D-Bus, home
# directory or host browser. Do not relabel the compositor's socket.
args+=(
--cap-add=SYS_CHROOT
--security-opt label=disable
--tmpfs "/run/media:rw,nosuid,nodev,size=1m,mode=1777"
--volume "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY:/run/media/wayland-0:ro"
--env WAYLAND_DISPLAY=wayland-0
)
if [[ -S "$XDG_RUNTIME_DIR/pulse/native" ]]; then
args+=(
--volume "$XDG_RUNTIME_DIR/pulse/native:/run/media/pulse-native:ro"
--env PULSE_SERVER=unix:/run/media/pulse-native
)
fi
fi
exec podman --remote=false "${args[@]}" "localhost/ai-media-$app:managed" "$@"

View File

@@ -0,0 +1,7 @@
[Desktop Entry]
Type=Application
Name={{ 'FaceFusion' if item == 'facefusion' else 'RVC Voice Conversion' }} (offline)
Exec={{ user_home }}/.local/bin/ai-media {{ item }}
Terminal=false
Categories=AudioVideo;
StartupNotify=false

View File

@@ -0,0 +1,15 @@
*
!Containerfile.*
!prepare.py
!session.py
!verify.py
!requirements-facefusion.lock
!requirements-rvc.lock
!models/
{% for model in desktop_ai_media_public_models %}
!models/{{ model.app }}/
{% for depth in range(1, model.path.split('/') | length) %}
!models/{{ model.app }}/{{ model.path.split('/')[:depth] | join('/') }}/
{% endfor %}
!models/{{ model.app }}/{{ model.path }}
{% endfor %}

View File

@@ -0,0 +1,584 @@
import json
import os
from pathlib import Path
import socket
import subprocess
import tempfile
import unittest
import wave
import struct
from jinja2 import Environment
import shlex
ROLE = Path(__file__).resolve().parents[1]
class LauncherTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.media = self.root / '.local/share/ai-media'
for directory in ('input', 'output', 'models', 'state/facefusion', 'state/rvc'):
(self.media / directory).mkdir(parents=True)
environment = Environment()
environment.filters['quote'] = shlex.quote
self.launcher = self.root / 'ai-media'
self.launcher.write_text(environment.from_string(
(ROLE / 'templates/ai-media.j2').read_text()
).render(desktop_ai_media_root=str(self.media), desktop_ai_media_build_root=str(self.root)))
(self.root / 'check_storage.py').write_text((ROLE / 'files/check_storage.py').read_text())
for name in ('preset.py', 'preset_rvc.py'):
(self.root / name).write_text((ROLE / 'files' / name).read_text())
self.log = self.root / 'podman.json'
podman = self.root / 'podman'
podman.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
podman.chmod(0o755)
self.env = dict(os.environ, PATH=str(self.root) + ':' + os.environ['PATH'],
TEST_LOG=str(self.log), HOME=str(self.root))
def launch(self, *args):
return subprocess.run(['bash', str(self.launcher), *args], env=self.env,
capture_output=True, text=True)
def fake_media_launcher(self):
fake = self.root / 'fake-ai-media'
fake.write_text('''#!/usr/bin/python3
import os
from pathlib import Path
import shutil
import sys
root = Path(os.environ["TEST_MEDIA"])
def host(path):
return str(path).replace("/work/input/", str(root / "input") + "/").replace(
"/work/output/", str(root / "output") + "/")
tool = sys.argv[1]
args = sys.argv[2:]
if tool == "ffmpeg":
os.execvp("ffmpeg", ["ffmpeg", *[host(arg) for arg in args]])
if tool == "facefusion":
(root / "facefusion-args.json").write_text(__import__("json").dumps(args))
shutil.copyfile(host(args[args.index("--target-path") + 1]),
host(args[args.index("--output-path") + 1]))
raise SystemExit(0)
if tool == "rvc":
(root / "rvc-args.json").write_text(__import__("json").dumps(args))
source = Path(host(args[1]))
job = Path(host(args[2]))
if "--convert-only" not in args:
(job / "instrumental").mkdir()
shutil.copyfile(source, job / "instrumental/stem.wav")
if "--separate-only" in args:
(job / "vocals").mkdir()
shutil.copyfile(source, job / "vocals/stem.wav")
else:
shutil.copyfile(source, job / "vocals-mia_voce.wav")
raise SystemExit(0)
raise SystemExit("Unexpected tool: " + tool)
''')
fake.chmod(0o755)
return fake
def fake_downloader(self, fixture):
downloader = self.root / 'yt-dlp'
downloader.write_text('''#!/usr/bin/python3
import json
import os
from pathlib import Path
import shutil
import sys
args = sys.argv[1:]
Path(os.environ["TEST_LOG"]).write_text(json.dumps(args))
destination = args[args.index("--output") + 1].replace("%(ext)s", "mp4")
shutil.copyfile(os.environ["TEST_DOWNLOAD_FIXTURE"], destination)
''')
downloader.chmod(0o755)
self.env['TEST_DOWNLOAD_FIXTURE'] = str(fixture)
return downloader
def run_preset(self, fake, *args, job_id='test'):
return subprocess.run(['python3', str(self.root / 'preset.py'),
str(self.media), str(fake), '--run', '--job-id', job_id, *args],
env={**self.env, 'TEST_MEDIA': str(self.media)},
capture_output=True, text=True)
def create_video(self, *, audio=False):
video = self.media / 'input/video1.mp4'
command = ['ffmpeg', '-hide_banner', '-loglevel', 'error', '-f', 'lavfi',
'-i', 'color=c=black:s=64x64:d=1']
if audio:
command += ['-f', 'lavfi', '-i', 'sine=frequency=440:duration=1']
command += ['-c:v', 'mpeg4']
if audio:
command += ['-c:a', 'aac', '-shortest']
subprocess.run([*command, str(video)], check=True)
return video
def stream_types(self, path):
probe = subprocess.check_output(['ffprobe', '-v', 'error', '-show_entries',
'stream=codec_type', '-of', 'json', str(path)])
return {stream['codec_type'] for stream in json.loads(probe)['streams']}
def create_audio(self, relative, sample=1000, seconds=1):
path = self.media / relative
path.parent.mkdir(parents=True, exist_ok=True)
with wave.open(str(path), 'wb') as audio:
audio.setparams((1, 2, 8000, 0, 'NONE', 'not compressed'))
audio.writeframes(struct.pack('<h', sample) * (8000 * seconds))
return path
def test_mix_sums_stems_and_preserves_longest_duration(self):
vocals = self.create_audio('output/video1-split-stems/vocals.wav')
instrumental = self.create_audio('output/video1-split-stems/instrumental.wav',
sample=2000, seconds=2)
before = [path.read_bytes() for path in (vocals, instrumental)]
result = self.run_preset(self.fake_media_launcher(), 'mix',
'video1-split-stems/vocals.wav',
'video1-split-stems/instrumental.wav', '--output', 'song.wav')
self.assertEqual(result.returncode, 0, result.stderr)
output = self.media / 'output/song.wav'
self.assertEqual(self.stream_types(output), {'audio'})
with wave.open(str(output), 'rb') as audio:
self.assertEqual(audio.getnframes(), 16000)
samples = struct.unpack('<16000h', audio.readframes(16000))
self.assertAlmostEqual(samples[4000], 3000, delta=1)
self.assertAlmostEqual(samples[12000], 2000, delta=1)
self.assertEqual([path.read_bytes() for path in (vocals, instrumental)], before)
def test_voice_convert_audio_skips_separation_and_preserves_input(self):
source = self.create_audio('output/video1-split-stems/vocals.wav')
before = source.read_bytes()
result = self.run_preset(self.fake_media_launcher(), 'voice-convert',
'video1-split-stems/vocals.wav')
self.assertEqual(result.returncode, 0, result.stderr)
output = self.media / 'output/vocals-mia_voce.wav'
self.assertEqual(self.stream_types(output), {'audio'})
args = json.loads((self.media / 'rvc-args.json').read_text())
self.assertIn('--convert-only', args)
self.assertFalse(list((self.media / 'output').rglob('instrumental')))
self.assertFalse((self.media / 'facefusion-args.json').exists())
self.assertEqual(source.read_bytes(), before)
repeated = self.run_preset(self.fake_media_launcher(), 'voice-convert',
'video1-split-stems/vocals.wav')
self.assertNotEqual(repeated.returncode, 0)
def test_voice_convert_dispatches_with_custom_output(self):
self.create_audio('input/voice.wav')
runner = self.root / 'systemd-run'
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
runner.chmod(0o755)
result = self.launch('preset', 'voice-convert', 'voice.wav', '--output', 'mine.wav')
self.assertEqual(result.returncode, 0, result.stderr)
args = json.loads(self.log.read_text())
self.assertIn('--user', args)
self.assertEqual(args[-4:], ['voice-convert', 'voice.wav', '--output', 'mine.wav'])
def test_voice_convert_rejects_invalid_audio_and_output(self):
self.create_audio('input/voice.wav')
for name in ('missing.wav', '../voice.wav', 'https://example.org/audio.wav'):
self.assertNotEqual(self.launch('preset', 'voice-convert', name).returncode, 0)
for name in ('../mine.wav', 'mine.mp3'):
self.assertNotEqual(self.launch('preset', 'voice-convert', 'voice.wav',
'--output', name).returncode, 0)
self.create_audio('output/voice.wav')
self.assertNotEqual(self.launch('preset', 'voice-convert', 'voice.wav').returncode, 0)
self.assertFalse(self.log.exists())
def test_mix_default_output_and_no_overwrite(self):
self.create_audio('input/voice.wav')
self.create_audio('output/instrumental.wav')
args = ('mix', 'voice.wav', 'instrumental.wav')
result = self.run_preset(self.fake_media_launcher(), *args)
self.assertEqual(result.returncode, 0, result.stderr)
target = self.media / 'output/voice-mix.wav'
original = target.read_bytes()
result = self.run_preset(self.fake_media_launcher(), *args)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(target.read_bytes(), original)
def test_mix_dispatches_audio_only_background_job(self):
self.create_audio('input/voice.wav')
self.create_audio('output/instrumental.wav')
runner = self.root / 'systemd-run'
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
runner.chmod(0o755)
result = self.launch('preset', 'mix', 'voice.wav', 'instrumental.wav',
'--output', 'song.wav')
self.assertEqual(result.returncode, 0, result.stderr)
args = json.loads(self.log.read_text())
self.assertIn('--user', args)
self.assertEqual(args[-5:], ['mix', 'voice.wav', 'instrumental.wav',
'--output', 'song.wav'])
self.assertFalse((self.media / 'output/song.wav').exists())
def test_mix_rejects_unsafe_paths_and_ambiguous_audio(self):
self.create_audio('input/voice.wav')
self.create_audio('output/instrumental.wav')
for unsafe in ('../voice.wav', '/tmp/voice.wav', 'https://example.org/voice.wav'):
result = self.launch('preset', 'mix', unsafe, 'instrumental.wav')
self.assertNotEqual(result.returncode, 0)
for unsafe in ('../song.wav', '/tmp/song.wav', 'song.mp3'):
result = self.launch('preset', 'mix', 'voice.wav', 'instrumental.wav',
'--output', unsafe)
self.assertNotEqual(result.returncode, 0)
(self.media / 'output/linked').symlink_to(self.media / 'input', target_is_directory=True)
self.assertNotEqual(self.launch('preset', 'mix', 'linked/voice.wav',
'instrumental.wav').returncode, 0)
self.create_audio('output/voice.wav')
self.assertNotEqual(self.launch('preset', 'mix', 'voice.wav',
'instrumental.wav').returncode, 0)
self.assertFalse(self.log.exists())
def test_mix_rejects_missing_audio_stream(self):
video = self.create_video()
self.create_audio('output/instrumental.wav')
result = self.run_preset(self.fake_media_launcher(), 'mix', video.name,
'instrumental.wav')
self.assertNotEqual(result.returncode, 0)
self.assertFalse((self.media / 'output/video1-mix.wav').exists())
def test_cli_has_no_network_or_host_home(self):
result = self.launch('facefusion', 'cli', '--help')
self.assertEqual(result.returncode, 0, result.stderr)
args = json.loads(self.log.read_text())
for flag in ('--network=none', '--pull=never', '--read-only',
'--security-opt=no-new-privileges', '--cap-drop=ALL'):
self.assertIn(flag, args)
self.assertIn(str(self.media / 'input') + ':/work/input:ro,Z', args)
self.assertNotIn('--privileged', args)
self.assertNotIn('--security-opt', args)
self.assertNotIn('label=disable', args)
def test_gui_exposes_only_wayland_socket(self):
self.env.update(XDG_RUNTIME_DIR=str(self.root), WAYLAND_DISPLAY='wayland-0')
with socket.socket(socket.AF_UNIX) as sock:
sock.bind(str(self.root / 'wayland-0'))
result = self.launch('rvc', '--foreground')
self.assertEqual(result.returncode, 0, result.stderr)
args = json.loads(self.log.read_text())
self.assertIn('--network=none', args)
self.assertIn(str(self.root / 'wayland-0') + ':/run/media/wayland-0:ro', args)
self.assertIn('/run/media:rw,nosuid,nodev,size=1m,mode=1777', args)
self.assertFalse(any('uid=' in arg or 'gid=' in arg for arg in args))
self.assertNotIn('--publish', args)
self.assertFalse(any('dbus' in arg for arg in args))
def test_rvc_cli_is_offline_and_mounts_only_preset_code(self):
result = self.launch('rvc', 'cli', '/work/output/job/audio.wav', '/work/output/job')
self.assertEqual(result.returncode, 0, result.stderr)
args = json.loads(self.log.read_text())
self.assertIn('--network=none', args)
self.assertIn('--entrypoint', args)
self.assertIn('python', args)
self.assertIn(str(self.root / 'preset_rvc.py') + ':/opt/preset_rvc.py:ro,Z', args)
self.assertIn('/opt/preset_rvc.py', args)
self.assertNotIn('label=disable', args)
def test_voice_preset_dispatches_to_user_service(self):
(self.media / 'input/video1.mp4').write_bytes(b'not processed in dispatch')
runner = self.root / 'systemd-run'
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
runner.chmod(0o755)
result = self.launch('preset', 'audio-convert', 'video1.mp4')
self.assertEqual(result.returncode, 0, result.stderr)
args = json.loads(self.log.read_text())
self.assertIn('--user', args)
self.assertIn('--property=Restart=no', args)
self.assertIn('audio-convert', args)
self.assertIn('video1.mp4', args)
def test_face_preset_requires_all_sources(self):
(self.media / 'input/video1.mp4').write_bytes(b'video')
self.assertNotEqual(self.launch('preset', 'video-convert', 'video1.mp4').returncode, 0)
self.assertFalse(self.log.exists())
def test_complete_preset_rejects_local_url(self):
result = self.launch('preset', 'convert', 'file:///tmp/video.mp4')
self.assertNotEqual(result.returncode, 0)
self.assertFalse(self.log.exists())
def test_old_preset_names_are_rejected(self):
for name in ('voce', 'volti', 'unisci', 'completo'):
with self.subTest(name=name):
self.assertEqual(self.launch('preset', name, 'video1.mp4').returncode, 2)
def test_all_url_presets_dispatch_one_background_job(self):
for number in range(11, 19):
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
runner = self.root / 'systemd-run'
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
runner.chmod(0o755)
(self.media / 'input/audio.wav').write_bytes(b'audio')
for preset in ('audio-convert', 'video-convert', 'merge', 'split',
'split-stems', 'convert'):
with self.subTest(preset=preset):
extra = ['audio.wav'] if preset == 'merge' else []
result = self.launch('preset', preset, 'https://example.org/video', *extra)
self.assertEqual(result.returncode, 0, result.stderr)
args = json.loads(self.log.read_text())
self.assertIn('--user', args)
self.assertIn(preset, args)
self.assertIn('https://example.org/video', args)
if extra:
self.assertEqual(args[-1], 'audio.wav')
self.assertFalse(list((self.media / 'input').glob('download-*')))
def test_mux_preset_rejects_ambiguous_audio(self):
(self.media / 'input/video1.mp4').write_bytes(b'video')
(self.media / 'input/audio.wav').write_bytes(b'audio')
(self.media / 'output/audio.wav').write_bytes(b'audio')
self.assertNotEqual(self.launch('preset', 'merge', 'video1.mp4', 'audio.wav').returncode, 0)
self.assertFalse(self.log.exists())
def test_mux_preset_creates_audio_video_with_streams(self):
if subprocess.run(['bash', '-c', 'command -v ffmpeg && command -v ffprobe'],
capture_output=True).returncode != 0:
self.skipTest('ffmpeg and ffprobe required')
self.create_video()
audio = self.media / 'input/audio.wav'
subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-f', 'lavfi',
'-i', 'sine=frequency=440:duration=1', str(audio)], check=True)
result = self.run_preset(self.fake_media_launcher(), 'merge', 'video1.mp4', 'audio.wav')
self.assertEqual(result.returncode, 0, result.stderr)
output = self.media / 'output/video1-unito.mp4'
self.assertTrue(output.is_file())
self.assertEqual(self.stream_types(output), {'video', 'audio'})
def test_voice_preset_outputs_audio_only(self):
self.create_video(audio=True)
result = self.run_preset(self.fake_media_launcher(), 'audio-convert', 'video1.mp4')
self.assertEqual(result.returncode, 0, result.stderr)
output = self.media / 'output/video1-mia_voce.wav'
self.assertEqual(self.stream_types(output), {'audio'})
self.assertFalse((self.media / 'output/video1-mia_voce.mp4').exists())
def test_split_presets_output_separate_streams_without_conversion(self):
original = self.create_video(audio=True).read_bytes()
for preset in ('split', 'split-stems'):
with self.subTest(preset=preset):
result = self.run_preset(self.fake_media_launcher(), preset, 'video1.mp4')
self.assertEqual(result.returncode, 0, result.stderr)
output = self.media / 'output' / f'video1-{preset}'
expected = {'video.mp4', 'audio.wav'}
if preset == 'split-stems':
expected |= {'vocals.wav', 'instrumental.wav'}
args = json.loads((self.media / 'rvc-args.json').read_text())
self.assertIn('--separate-only', args)
else:
self.assertFalse((self.media / 'rvc-args.json').exists())
self.assertEqual({p.name for p in output.iterdir()}, expected)
for name in expected:
self.assertEqual(self.stream_types(output / name),
{'video'} if name == 'video.mp4' else {'audio'})
self.assertEqual((self.media / 'input/video1.mp4').read_bytes(), original)
self.assertFalse(list((self.media / 'output').rglob('*mia_voce*')))
before = {p.name: p.read_bytes() for p in output.iterdir()}
repeated = self.run_preset(self.fake_media_launcher(), preset, 'video1.mp4',
job_id='repeat')
self.assertNotEqual(repeated.returncode, 0)
self.assertEqual({p.name: p.read_bytes() for p in output.iterdir()}, before)
def test_split_presets_reject_video_without_audio(self):
self.create_video()
for preset in ('split', 'split-stems'):
result = self.run_preset(self.fake_media_launcher(), preset, 'video1.mp4')
self.assertNotEqual(result.returncode, 0)
self.assertFalse(list((self.media / 'output').iterdir()))
def test_face_preset_preserves_audio_only_when_present(self):
for audio in (False, True):
with self.subTest(audio=audio):
video = self.media / 'input/video1.mp4'
if video.exists():
video.unlink()
self.create_video(audio=audio)
for number in range(11, 19):
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
output = self.media / 'output/video1-facefusion.mp4'
if output.exists():
output.unlink()
result = self.run_preset(self.fake_media_launcher(), 'video-convert', 'video1.mp4',
job_id=f'test-{audio}')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.stream_types(output),
{'video', 'audio'} if audio else {'video'})
def test_face_preset_uses_requested_options(self):
self.create_video(audio=True)
for number in range(11, 19):
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
result = self.run_preset(self.fake_media_launcher(), 'video-convert', 'video1.mp4')
self.assertEqual(result.returncode, 0, result.stderr)
args = json.loads((self.media / 'facefusion-args.json').read_text())
source_start = args.index('--source-paths') + 1
self.assertEqual(args[source_start:source_start + 8],
[f'/work/input/source{number}.jpg' for number in range(11, 19)])
expected = {
'--processors': ['face_swapper'],
'--face-swapper-model': ['hyperswap_1a_256'],
'--face-swapper-pixel-boost': ['256x256'],
'--face-swapper-weight': ['0.5'],
'--face-detector-model': ['yolo_face'],
'--face-detector-size': ['640x640'],
'--face-detector-angles': ['0', '90', '180', '270'],
'--face-detector-score': ['0.5'],
'--face-selector-mode': ['one'],
'--face-selector-order': ['large-small'],
'--face-selector-gender': ['female'],
'--face-selector-race': ['white'],
'--face-mask-types': ['occlusion', 'region', 'area', 'box'],
'--face-occluder-model': ['xseg_1'],
'--face-parser-model': ['bisenet_resnet_34'],
'--face-mask-blur': ['0.3'],
'--output-video-encoder': ['libx264'],
'--output-video-preset': ['veryfast'],
'--output-video-quality': ['80'],
'--output-video-fps': ['30'],
'--execution-providers': ['cpu'],
'--output-audio-encoder': ['aac'],
'--jobs-path': ['/work/state'],
'--temp-path': ['/work/state/tmp'],
}
for flag, values in expected.items():
with self.subTest(flag=flag):
start = args.index(flag) + 1
self.assertEqual(args[start:start + len(values)], values)
def test_complete_preset_downloads_and_combines_both_results(self):
fixture = self.create_video(audio=True)
for number in range(11, 19):
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
self.fake_downloader(fixture)
result = self.run_preset(self.fake_media_launcher(), 'convert',
'https://example.org/video', job_id='test')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertTrue((self.media / 'input/download-test.mp4').is_file())
self.assertEqual(self.stream_types(self.media / 'output/download-test-mia_voce.wav'),
{'audio'})
self.assertEqual(self.stream_types(self.media / 'output/download-test-facefusion.mp4'),
{'video', 'audio'})
self.assertEqual(self.stream_types(self.media / 'output/download-test-completo.mp4'),
{'video', 'audio'})
face_args = json.loads((self.media / 'facefusion-args.json').read_text())
self.assertEqual(face_args[face_args.index('--face-selector-gender') + 1], 'female')
self.assertEqual(face_args[face_args.index('--output-video-fps') + 1], '30')
downloader_args = json.loads(self.log.read_text())
self.assertIn('--ignore-config', downloader_args)
self.assertIn('--no-playlist', downloader_args)
def test_default_gui_uses_independent_user_service(self):
self.env.update(XDG_RUNTIME_DIR=str(self.root), WAYLAND_DISPLAY='wayland-0')
runner = self.root / 'systemd-run'
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
runner.chmod(0o755)
with socket.socket(socket.AF_UNIX) as sock:
sock.bind(str(self.root / 'wayland-0'))
result = self.launch('rvc')
self.assertEqual(result.returncode, 0, result.stderr)
args = json.loads(self.log.read_text())
self.assertIn('--user', args)
self.assertIn('--unit=ai-media-rvc', args)
self.assertIn('--property=Restart=no', args)
self.assertIn('--foreground', args)
self.assertNotIn('--scope', args)
self.assertNotIn('--pty', args)
self.assertNotIn('--wait', args)
def test_all_presets_download_url_before_processing(self):
fixture = self.create_video(audio=True)
self.fake_downloader(fixture)
for number in range(11, 19):
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
audio = self.media / 'input/audio.wav'
subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-i',
str(fixture), '-vn', str(audio)], check=True)
outputs = {
'audio-convert': 'mia_voce.wav', 'video-convert': 'facefusion.mp4',
'merge': 'unito.mp4', 'split': 'split', 'split-stems': 'split-stems',
'convert': 'completo.mp4',
}
for preset, suffix in outputs.items():
with self.subTest(preset=preset):
extra = ['audio.wav'] if preset == 'merge' else []
result = self.run_preset(self.fake_media_launcher(), preset,
'https://example.org/video?a=1&b=2', *extra,
job_id=preset)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.count('Downloading one video'), 1)
self.assertTrue((self.media / f'input/download-{preset}.mp4').is_file())
output = self.media / f'output/download-{preset}-{suffix}'
self.assertTrue(output.exists())
if preset in ('split', 'split-stems'):
self.assertEqual(self.stream_types(output / 'video.mp4'), {'video'})
self.assertEqual(self.stream_types(output / 'audio.wav'), {'audio'})
else:
self.assertEqual(self.stream_types(output), {'audio'} if
preset == 'audio-convert' else {'video', 'audio'})
download_args = json.loads(self.log.read_text())
self.assertEqual(download_args[-1], 'https://example.org/video?a=1&b=2')
for flag in ('--ignore-config', '--no-playlist', '--no-overwrites'):
self.assertIn(flag, download_args)
def test_convert_also_accepts_local_video_without_download(self):
fixture = self.create_video(audio=True)
self.fake_downloader(fixture)
for number in range(11, 19):
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
result = self.run_preset(self.fake_media_launcher(), 'convert', fixture.name)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertFalse(self.log.exists())
self.assertEqual(self.stream_types(self.media / 'output/video1-completo.mp4'),
{'video', 'audio'})
def test_all_presets_reject_invalid_urls_before_dispatch(self):
for preset in ('split', 'split-stems', 'audio-convert', 'video-convert',
'merge', 'convert'):
for url in ('file:///tmp/video.mp4', 'https://localhost/video',
'http://192.168.1.1/video', 'https://user:password@example.org/video'):
with self.subTest(preset=preset, url=url):
extra = ['audio.wav'] if preset == 'merge' else []
result = self.launch('preset', preset, url, *extra)
self.assertNotEqual(result.returncode, 0)
self.assertFalse(self.log.exists())
def test_failed_url_download_does_not_start_processing(self):
downloader = self.root / 'yt-dlp'
downloader.write_text('#!/bin/sh\nexit 1\n')
downloader.chmod(0o755)
result = self.run_preset(self.fake_media_launcher(), 'split',
'https://example.org/video')
self.assertNotEqual(result.returncode, 0)
self.assertFalse(list((self.media / 'output').iterdir()))
def test_symlinked_input_is_rejected(self):
(self.media / 'input').rmdir()
(self.media / 'input').symlink_to(self.root)
self.assertNotEqual(self.launch('facefusion', 'cli', '--help').returncode, 0)
self.assertFalse(self.log.exists())
def test_synced_storage_is_rejected(self):
directory = self.root / '.config/Nextcloud'
directory.mkdir(parents=True)
(directory / 'nextcloud.cfg').write_text(
'[Accounts]\n0\\Folders\\1\\localPath=' + str(self.media) + '\n'
)
self.assertNotEqual(self.launch('facefusion', 'cli', '--help').returncode, 0)
self.assertFalse(self.log.exists())
def test_invalid_tool_is_rejected(self):
self.assertEqual(self.launch('--network=host').returncode, 2)
self.assertFalse(self.log.exists())
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,93 @@
import importlib.util
import os
from pathlib import Path
import sys
import tempfile
from types import ModuleType
import unittest
from unittest.mock import Mock, patch
class SeparationWorkerTest(unittest.TestCase):
def test_convert_only_applies_mia_voce_without_importing_separator(self):
spec = importlib.util.spec_from_file_location(
'preset_rvc', Path(__file__).resolve().parents[1] / 'files/preset_rvc.py')
worker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(worker)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
output = root / 'output'
job = output / 'job'
job.mkdir(parents=True)
source = job / 'audio.wav'
source.write_bytes(b'audio')
weights = root / 'state/weights/mia_voce.pth'
index = root / 'state/mia_voce/added_IVF256_Flat_nprobe_1_mia_voce_v2.index'
for path in (weights, index):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'model')
def mapped_path(value):
return root / str(value).removeprefix('/work/') if str(value).startswith(
'/work/') else Path(value)
config = ModuleType('configs.config')
config.Config = Mock()
vc = ModuleType('infer.vc.modules')
voice = Mock()
voice.vc_single.return_value = ('Success', (40000, [0.1, 0.2]))
vc.VC = Mock(return_value=voice)
sf = ModuleType('soundfile')
sf.write = Mock(side_effect=lambda path, data, rate: path.write_bytes(b'converted'))
modules = {'configs.config': config, 'infer.vc.modules': vc,
'soundfile': sf, 'tools.pymss_webui': None}
with patch.object(worker, 'Path', mapped_path), \
patch.object(sys, 'argv', ['preset_rvc.py', str(source), str(job),
'--convert-only']), \
patch.dict(sys.modules, modules), patch.dict(os.environ):
worker.main()
voice.get_vc.assert_called_once_with('mia_voce.pth')
self.assertEqual(voice.vc_single.call_args.args[1], str(source))
self.assertEqual(voice.vc_single.call_args.args[4], str(index))
self.assertEqual((job / 'vocals-mia_voce.wav').read_bytes(), b'converted')
self.assertFalse((job / 'vocals').exists())
self.assertFalse((job / 'instrumental').exists())
def test_separate_only_does_not_require_personal_voice_weights(self):
spec = importlib.util.spec_from_file_location(
'preset_rvc', Path(__file__).resolve().parents[1] / 'files/preset_rvc.py')
worker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(worker)
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)
job = output / 'job'
job.mkdir()
source = job / 'audio.wav'
source.write_bytes(b'fixture')
separator = ModuleType('tools.pymss_webui')
def separate(model, audio, vocals, unused, instrumental, fmt, **kwargs):
self.assertEqual(model, 'vocals-bs-roformer-368')
self.assertEqual(audio, str(source))
(Path(vocals) / 'stem.wav').write_bytes(b'vocals')
(Path(instrumental) / 'stem.wav').write_bytes(b'instrumental')
yield 'Separated'
separator.pymss_separate = separate
def mapped_path(value):
return output if str(value) == '/work/output' else Path(value)
with patch.object(worker, 'Path', mapped_path), \
patch.object(sys, 'argv', ['preset_rvc.py', str(source), str(job),
'--separate-only']), \
patch.dict(sys.modules, {'tools.pymss_webui': separator}), \
patch.dict(os.environ):
worker.main()
self.assertTrue((job / 'vocals/stem.wav').is_file())
self.assertTrue((job / 'instrumental/stem.wav').is_file())
self.assertFalse((job / 'vocals-mia_voce.wav').exists())
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,183 @@
import json
import os
from pathlib import Path
import shlex
import subprocess
import tempfile
import unittest
from jinja2 import Environment
TEMPLATE = Path(__file__).resolve().parents[1] / "templates/ai-media.j2"
UUID = "6948c504-2d60-4cc8-9e7f-3ccdf28e80d7"
class StorageCommandsTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.media = self.root / "media"
for directory in ("input", "output"):
(self.media / directory).mkdir(parents=True)
env = Environment()
env.filters["quote"] = shlex.quote
self.launcher = self.root / "ai-media"
self.launcher.write_text(env.from_string(TEMPLATE.read_text()).render(
desktop_ai_media_root=str(self.media),
desktop_ai_media_build_root=str(self.root),
desktop_ai_media_external_storage_enabled=True,
desktop_ai_media_external_luks_uuid=UUID,
desktop_ai_media_external_mountpoint="/run/media/test/Backup",
desktop_ai_media_external_source="/run/media/test/Backup/ai-media",
))
self.state = self.root / "state.json"
self.log = self.root / "commands.jsonl"
mock = self.root / "mock"
mock.write_text('''#!/usr/bin/env python3
import json
import os
from pathlib import Path
import sys
cmd = Path(sys.argv[0]).name
args = sys.argv[1:]
state_file = Path(os.environ["STORAGE_TEST_STATE"])
state = json.loads(state_file.read_text())
root = os.environ["STORAGE_TEST_ROOT"]
external = "/run/media/test/Backup"
with open(os.environ["STORAGE_TEST_LOG"], "a") as log:
log.write(json.dumps([cmd, *args]) + "\\n")
if cmd == "sudo":
os.execvp(args[0], args)
elif cmd == "lsblk":
if state.get("missing"):
sys.exit(1)
print("/dev/sda1 part 8:1")
if state.get("unlocked"):
print("/dev/dm-0 crypt 252:0")
elif cmd == "findmnt":
if "--mountpoint" in args:
target = args[args.index("--mountpoint") + 1]
match = state.get("bind" if target == root else "mounted")
if not match:
sys.exit(1)
print(match)
elif "--source" in args:
assert args[args.index("--source") + 1] == "252:0"
mounts = ([external] if state.get("mounted") else []) + (
[root] if state.get("bind") else []) + state.get("other_mounts", [])
if not mounts:
sys.exit(1)
print(*mounts, sep="\\n")
else:
sys.exit(2)
elif cmd == "systemctl":
if args[0] == "--user":
if state.get("running"):
print("ai-media-preset-test.service loaded active running")
elif args[0] == "start":
state["bind"] = "252:0 /ai-media"
elif args[0] == "stop":
state.pop("bind", None)
elif cmd == "podman":
assert args[:3] == ["--remote=false", "ps", "-q"]
if state.get("container"):
print("abcdef")
elif cmd == "udisksctl":
if args[0] == "unlock":
state["unlocked"] = True
elif args[0] == "mount":
state["mounted"] = "252:0 /"
elif args[0] == "unmount":
if state.get("busy"):
sys.exit("Device is busy")
state.pop("mounted", None)
elif args[0] == "lock":
assert not state.get("mounted")
state.pop("unlocked")
state_file.write_text(json.dumps(state))
''')
mock.chmod(0o755)
for command in ("lsblk", "findmnt", "systemctl", "podman", "udisksctl", "sudo"):
(self.root / command).symlink_to(mock)
self.env = dict(os.environ, PATH=f"{self.root}:{os.environ['PATH']}",
STORAGE_TEST_STATE=str(self.state), STORAGE_TEST_LOG=str(self.log),
STORAGE_TEST_ROOT=str(self.media))
def units(self):
return [subprocess.check_output(["systemd-escape", "-p", "--suffix=" + suffix, "--", str(self.media)], text=True).strip()
for suffix in ("automount", "mount")]
def launch(self, *args, **state):
self.state.write_text(json.dumps(state))
self.log.write_text("")
result = subprocess.run(["bash", str(self.launcher), *args], env=self.env,
capture_output=True, text=True, timeout=10)
operations = [row[:2] if row[0] == "systemctl" else row
for line in self.log.read_text().splitlines()
if (row := json.loads(line))[0] in ("udisksctl", "systemctl", "sudo")]
return result, operations
def test_mount_unlocks_only_the_configured_volume_then_starts_bind(self):
result, operations = self.launch("mount")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(operations, [
["udisksctl", "unlock", "--block-device", f"/dev/disk/by-uuid/{UUID}"],
["udisksctl", "mount", "--block-device", "/dev/dm-0"],
["sudo", "systemctl", "start", *self.units()],
["systemctl", "start"],
])
def test_mount_does_not_reopen_already_mounted_volume(self):
result, operations = self.launch("mount", unlocked=True, mounted="252:0 /")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(operations, [["sudo", "systemctl", "start", *self.units()], ["systemctl", "start"]])
def test_umount_stops_bind_before_unmount_and_lock(self):
result, operations = self.launch("umount", unlocked=True, mounted="252:0 /",
bind="252:0 /ai-media")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(operations, [
["systemctl", "--user"], ["sudo", "systemctl", "stop", "ai-media-bind-restarter.service", *self.units()], ["systemctl", "stop"],
["udisksctl", "unmount", "--block-device", "/dev/dm-0"],
["udisksctl", "lock", "--block-device", f"/dev/disk/by-uuid/{UUID}"],
])
def test_umount_refuses_running_jobs_and_containers(self):
for condition in ("running", "container"):
with self.subTest(condition=condition):
result, operations = self.launch("umount", **{condition: True})
self.assertNotEqual(result.returncode, 0)
self.assertIn("running ai-media jobs", result.stderr)
self.assertEqual(operations, [["systemctl", "--user"]])
def test_umount_does_not_lock_if_busy(self):
result, operations = self.launch("umount", unlocked=True, mounted="252:0 /", busy=True)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(operations[-1][:2], ["udisksctl", "unmount"])
def test_umount_does_not_touch_other_mounts(self):
result, operations = self.launch("umount", unlocked=True, mounted="252:0 /",
other_mounts=["/mnt/other"])
self.assertNotEqual(result.returncode, 0)
self.assertEqual(operations, [["systemctl", "--user"], ["sudo", "systemctl", "stop", "ai-media-bind-restarter.service", *self.units()], ["systemctl", "stop"]])
def test_rejects_foreign_mount_missing_device_and_extra_arguments(self):
for args, state in [
(("mount",), {"mounted": "8:2 /"}),
(("umount",), {"bind": "8:2 /ai-media"}),
(("mount",), {"missing": True}),
(("umount", "/dev/sdb"), {}),
]:
with self.subTest(args=args, state=state):
result, operations = self.launch(*args, **state)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(operations, [])
def test_preset_refuses_local_fallback_when_bind_is_stopped(self):
result, operations = self.launch("preset", "split", "test.mp4")
self.assertNotEqual(result.returncode, 0)
self.assertIn("run ai-media mount first", result.stderr)
self.assertEqual(operations, [])

View File

@@ -0,0 +1,134 @@
---
desktop_ai_media_public_models:
- app: facefusion
path: .assets/models/2dfan4.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/2dfan4.hash
sha256: e6a6ef99b10b9fdb790c790879ca201f7afbe52560e4379248922324a9d503e8
- app: facefusion
path: .assets/models/2dfan4.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/2dfan4.onnx
sha256: 678c6fa539d52335a31c980feefdf4a6e02d781d83dce00af8a894f114557285
- app: facefusion
path: .assets/models/arcface_w600k_r50.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/arcface_w600k_r50.hash
sha256: e3a6d709939a81fe09e71c7d36f96d54a0deede904e31a38c191a1904e808371
- app: facefusion
path: .assets/models/arcface_w600k_r50.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/arcface_w600k_r50.onnx
sha256: f1f79dc3b0b79a69f94799af1fffebff09fbd78fd96a275fd8f0cbbea23270d1
- app: facefusion
path: .assets/models/bisenet_resnet_34.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/bisenet_resnet_34.hash
sha256: bfca5e43ca55110701ab691d864cacfddccad324dc42043aea8c001a949ce1f8
- app: facefusion
path: .assets/models/bisenet_resnet_34.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/bisenet_resnet_34.onnx
sha256: 4a0b8c958a3c938913bd06a8365dbb3c8761afba6ecbf0d14b3b1f77eb230c96
- app: facefusion
path: .assets/models/fairface.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fairface.hash
sha256: e232c933114a6c9ce446195e4a96bf1c3327dd31c13165849cd00f9f19a2ea62
- app: facefusion
path: .assets/models/fairface.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fairface.onnx
sha256: b176b1e4b0739496e7943af7ba4ff306271fecf837bca5ec5d9a48201959db37
- app: facefusion
path: .assets/models/fan_68_5.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fan_68_5.hash
sha256: 092d902410959b3ce01294d7c1ad157f1c602e3918238117e7ef87157be9534e
- app: facefusion
path: .assets/models/fan_68_5.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fan_68_5.onnx
sha256: ea05f7d9d014ae1d9cdc6e9c72643d8f00d198b5db3fdd384148ddff499a613e
- app: facefusion
path: .assets/models/hyperswap_1a_256.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/hyperswap_1a_256.hash
sha256: 70b33d0a9d6044847d9b29f9d08ce7afc140a2cada5b4b5f532bbd6440ba48c1
- app: facefusion
path: .assets/models/hyperswap_1a_256.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/hyperswap_1a_256.onnx
sha256: c0e98a8a03a238f461ed3d2570e426b49f46745ee400854a60dceeb70c246add
- app: facefusion
path: .assets/models/kim_vocal_2.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/kim_vocal_2.hash
sha256: fcd81ca30adf430b697fe58d60183031173c8ab0ca82efef308d652b1afb4197
- app: facefusion
path: .assets/models/kim_vocal_2.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/kim_vocal_2.onnx
sha256: fbde1fd7d35a6b1785add2225ce03255a01ccef6c8a5fb7b2ccd4e0c1e9097f7
- app: facefusion
path: .assets/models/nsfw_1.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_1.hash
sha256: 48c61a15ffcda1ae9e6d4c790224072c8e5648d4ba2f767cf4cfe0be7e282853
- app: facefusion
path: .assets/models/nsfw_1.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_1.onnx
sha256: 3debfd72763bc931dd308f57d1e9299ae13bb309d14ddbdc17ce8f1fd42f96af
- app: facefusion
path: .assets/models/nsfw_2.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_2.hash
sha256: 64cbc0c1a4d72e181fae364281b6d2130be3b87d5784909c5a29adf436f09a01
- app: facefusion
path: .assets/models/nsfw_2.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_2.onnx
sha256: 5aae1806ce44e3c27fab0a7d44eed581dd25ca71a4387ff809a191c98239c1be
- app: facefusion
path: .assets/models/nsfw_3.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_3.hash
sha256: b15c591d8177511959174a0c6761827e3bf9c0aa1d63aaa79645d9fc9a4e774b
- app: facefusion
path: .assets/models/nsfw_3.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_3.onnx
sha256: 778139fb930240ac39812a1480295bfc5dc2cec8a8e46ee6b453481d600c0fa2
- app: facefusion
path: .assets/models/xseg_1.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.1.0/xseg_1.hash
sha256: da3648ccecaa79f3be5ca0e1c3713f775504dd5c5dff716c095925132c02b08e
- app: facefusion
path: .assets/models/xseg_1.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.1.0/xseg_1.onnx
sha256: c4d1498b8a03b5fe2a3a5d2ef2a0402ab03bd51edaf5b2d8d5fb764702a97dd3
- app: facefusion
path: .assets/models/yoloface_8n.hash
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/yoloface_8n.hash
sha256: 7a4bd7e1a8cd938db2234dba41d4a8b7719bedbf7496d35510927cbd4b71683f
- app: facefusion
path: .assets/models/yoloface_8n.onnx
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/yoloface_8n.onnx
sha256: 821cdbb1e65fbbabdde7dd0933f754797a343e56fd962729c61ffcefcd135929
- app: rvc
path: assets/hubert_base/config.json
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/hubert_base/config.json
sha256: 0346950779dfb7f9316fa74ed846e2b8a22a08eedfdc5387b73f327cb1a4a7cf
- app: rvc
path: assets/hubert_base/preprocessor_config.json
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/hubert_base/preprocessor_config.json
sha256: 7c1976a680fb7acc757cd36fb08eef878fa36c70b4c9d2d595df9c608bbbbf0e
- app: rvc
path: assets/hubert_base/pytorch_model.bin
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/hubert_base/pytorch_model.bin
sha256: cc8c20f4b90a520757260197a3ff2505705a7adbd20ad9eeaa4e1a9b38442ef5
- app: rvc
path: assets/rmvpe/rmvpe.pt
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/rmvpe.pt
sha256: 6d62215f4306e3ca278246188607209f09af3dc77ed4232efdd069798c4ec193
- app: rvc
path: assets/mute.zip
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/mute.zip
sha256: ee948e85213e4ed2f2ba2f8dfcee810bfd0b63131d91450e920bbe1cbd0321d0
- app: rvc
path: assets/pretrained_v2/f0D40k.pth
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pretrained_v2/f0D40k.pth
sha256: 6b6ab091e70801b28e3f41f335f2fc5f3f35c75b39ae2628d419644ec2b0fa09
- app: rvc
path: assets/pretrained_v2/f0G40k.pth
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pretrained_v2/f0G40k.pth
sha256: 3b2c44035e782c4b14ddc0bede9e2f4a724d025cd073f736d4f43708453adfcb
- app: rvc
path: assets/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.ckpt
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.ckpt
sha256: 97c9e1011924ff647d147b474638c161b80586fd5b9e83fab59cbbb70014bf62
- app: rvc
path: assets/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.yaml
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.yaml
sha256: 105fd8e6a1ef1b038db2aa657a9f9696283d506dbc815bd7134a57aa80ec9f10

View File

@@ -0,0 +1,4 @@
---
devcontainer_generator_go_binary: /usr/bin/go
devcontainer_generator_install_go: true
devcontainer_generator_build_dir: "{{ user_home }}/.cache/infra/devcontainer-generator"

View File

@@ -0,0 +1,64 @@
---
- name: Install Go compiler for the devcontainer generator
ansible.builtin.dnf:
name: golang
state: present
when: devcontainer_generator_install_go | bool
- name: Ensure devcontainer generator directories exist
ansible.builtin.file:
path: "{{ item }}"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0755"
loop:
- "{{ user_home }}/.local/bin"
- "{{ devcontainer_generator_build_dir }}"
- name: Copy devcontainer generator sources
ansible.builtin.copy:
src: "{{ playbook_dir }}/../cmd/devcontainer/"
dest: "{{ devcontainer_generator_build_dir }}/src/"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: preserve
- name: Build devcontainer generator for the target host
ansible.builtin.command:
argv:
- "{{ devcontainer_generator_go_binary }}"
- build
- -trimpath
- -buildvcs=false
- -o
- "{{ devcontainer_generator_build_dir }}/devcontainer"
- .
chdir: "{{ devcontainer_generator_build_dir }}/src"
become_user: "{{ username }}"
environment:
GOCACHE: "{{ devcontainer_generator_build_dir }}/go-cache"
GOTOOLCHAIN: local
GOPROXY: "off"
GOSUMDB: "off"
CGO_ENABLED: "0"
# Compilation refreshes a cached artifact; copy below reports installation changes.
changed_when: false
when: not ansible_check_mode
- name: Install devcontainer generator in the user PATH
ansible.builtin.copy:
src: "{{ devcontainer_generator_build_dir }}/devcontainer"
remote_src: true
dest: "{{ user_home }}/.local/bin/devcontainer"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0755"
when: not ansible_check_mode
- name: Explain devcontainer generator check-mode behavior
ansible.builtin.debug:
msg: >-
Check mode validates package and source deployment only. Compilation and
installation of {{ user_home }}/.local/bin/devcontainer require a normal run.
when: ansible_check_mode

View File

@@ -91,6 +91,20 @@
loop_control: loop_control:
label: "{{ item.dest }}" label: "{{ item.dest }}"
- name: Ensure AI coding-agent dotfile parent directories exist
tags: [dotfiles, dotfiles:common, ai_agents]
ansible.builtin.file:
path: "{{ (effective_user_home ~ '/' ~ item.dest) | dirname }}"
state: directory
owner: "{{ effective_username }}"
group: "{{ effective_user_group }}"
mode: "0755"
loop: "{{ ai_agents_dotfiles | default([]) }}"
loop_control:
label: "{{ item.dest }}"
when:
- (item.agents | intersect(ai_agents_deploy_enabled_names)) | length > 0
- name: Deploy AI coding-agent dotfiles - name: Deploy AI coding-agent dotfiles
tags: [dotfiles, dotfiles:common, ai_agents] tags: [dotfiles, dotfiles:common, ai_agents]
ansible.builtin.copy: ansible.builtin.copy:

View File

@@ -0,0 +1,92 @@
---
# ChatGPT desktop is installed from OpenAI's signed RPM repository; removal
# must clean up the package, the managed repository and its signing key.
- name: Validate ChatGPT desktop architecture on Fedora
tags: [packages, chatgpt]
ansible.builtin.assert:
that:
- ansible_facts['architecture'] in chatgpt_desktop_supported_architectures
- ansible_facts['distribution_major_version'] in chatgpt_desktop_supported_fedora_versions
fail_msg: >-
ChatGPT desktop supports Fedora {{ chatgpt_desktop_supported_fedora_versions | join(' and ') }}
on x86_64 or aarch64; detected Fedora {{ ansible_facts['distribution_major_version'] }}
on {{ ansible_facts['architecture'] }}.
when: chatgpt_desktop_install_enabled | default(false) | bool
- name: Install ChatGPT desktop RPM signing key
tags: [packages, chatgpt]
ansible.builtin.copy:
src: "{{ chatgpt_desktop_rpm_gpg_key }}"
dest: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
owner: root
group: root
mode: "0644"
when: chatgpt_desktop_install_enabled | default(false) | bool
- name: Import ChatGPT desktop RPM signing key
tags: [packages, chatgpt]
ansible.builtin.rpm_key:
state: present
key: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
when: chatgpt_desktop_install_enabled | default(false) | bool
- name: Configure ChatGPT desktop RPM repository
tags: [packages, chatgpt]
ansible.builtin.yum_repository:
name: openai-chatgpt
description: ChatGPT
baseurl: "{{ chatgpt_desktop_rpm_repository }}"
enabled: true
gpgcheck: true
repo_gpgcheck: true
gpgkey: "file:///etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
state: present
when: chatgpt_desktop_install_enabled | default(false) | bool
- name: Install ChatGPT desktop on selected Fedora hosts
tags: [packages, chatgpt]
ansible.builtin.dnf:
name: chatgpt
state: latest
update_cache: true
when: chatgpt_desktop_install_enabled | default(false) | bool
- name: Check for the installed ChatGPT desktop signing key
tags: [packages, chatgpt]
ansible.builtin.stat:
path: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
get_checksum: false
register: chatgpt_desktop_signing_key
when: chatgpt_desktop_uninstall_enabled | default(false) | bool
- name: Remove ChatGPT desktop from selected Fedora hosts
tags: [packages, chatgpt]
ansible.builtin.dnf:
name: chatgpt
state: absent
when: chatgpt_desktop_uninstall_enabled | default(false) | bool
- name: Remove ChatGPT desktop RPM repository
tags: [packages, chatgpt]
ansible.builtin.yum_repository:
name: openai-chatgpt
state: absent
when: chatgpt_desktop_uninstall_enabled | default(false) | bool
# rpm_key reads the identifier from the key file, so only remove the key from
# the RPM database while the deployed file is still present.
- name: Remove ChatGPT desktop RPM signing key from the RPM database
tags: [packages, chatgpt]
ansible.builtin.rpm_key:
state: absent
key: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
when:
- chatgpt_desktop_uninstall_enabled | default(false) | bool
- chatgpt_desktop_signing_key.stat.exists | default(false)
- name: Remove ChatGPT desktop RPM signing key file
tags: [packages, chatgpt]
ansible.builtin.file:
path: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
state: absent
when: chatgpt_desktop_uninstall_enabled | default(false) | bool

View File

@@ -0,0 +1,78 @@
---
# Cline Desktop ships unsigned RPMs from its GitHub releases; only the
# checksum-verified download makes the local installation trustworthy.
- name: Validate Cline Desktop architecture on Fedora
ansible.builtin.assert:
that:
- ansible_facts['architecture'] in cline_desktop_rpm_checksums
fail_msg: "No verified Cline Desktop RPM for {{ ansible_facts['architecture'] }}."
when: cline_desktop_install_enabled | default(false) | bool
# Runs for both flows so the register below is always valid.
- name: Check for cached Cline Desktop RPM
ansible.builtin.stat:
path: "{{ cline_desktop_rpm_path }}"
get_checksum: false
register: cline_desktop_rpm_cache
- name: Download verified Cline Desktop RPM
ansible.builtin.get_url:
url: "{{ cline_desktop_rpm_url }}"
dest: "{{ cline_desktop_rpm_path }}"
checksum: "{{ cline_desktop_rpm_checksums[ansible_facts['architecture']] }}"
owner: root
group: root
mode: "0644"
# get_url only sends HEAD in check mode and cannot populate a cold cache.
when:
- cline_desktop_install_enabled | default(false) | bool
- not ansible_check_mode
- name: Install Cline Desktop on Fedora
ansible.builtin.dnf:
name: "{{ cline_desktop_rpm_path }}"
state: present
# Upstream ships an unsigned RPM. The download above verifies its pinned
# SHA-256; do not disable signature checks in system repository settings.
disable_gpg_check: true
when:
- cline_desktop_install_enabled | default(false) | bool
- not ansible_check_mode
or cline_desktop_rpm_cache.stat.exists
- name: Explain Cline Desktop cold-cache check-mode limitation
ansible.builtin.debug:
msg: >-
A real run will download and SHA-256 verify Cline Desktop
{{ cline_desktop_version }} before ensuring it is installed.
The RPM is not cached, so this dry run cannot validate DNF dependencies.
when:
- cline_desktop_install_enabled | default(false) | bool
- ansible_check_mode
- not cline_desktop_rpm_cache.stat.exists
# The `cline` RPM package name is verified from the pinned release header;
# removal never touches the npm-managed cline CLI or user data.
- name: Remove Cline Desktop from Fedora
ansible.builtin.dnf:
name: cline
state: absent
when: cline_desktop_uninstall_enabled | default(false) | bool
# Clean every cached download so retirement also removes outdated pins.
- name: Find cached Cline Desktop RPM downloads
ansible.builtin.find:
paths: /var/cache
patterns: "cline-desktop-*.rpm"
file_type: file
register: cline_desktop_cached_rpms
when: cline_desktop_uninstall_enabled | default(false) | bool
- name: Remove cached Cline Desktop RPM downloads
ansible.builtin.file:
path: "{{ item.path }}"
state: absent
loop: "{{ cline_desktop_cached_rpms.files | default([]) }}"
loop_control:
label: "{{ item.path }}"
when: cline_desktop_uninstall_enabled | default(false) | bool

View File

@@ -25,20 +25,6 @@
- "'workstation_dev_fedora' in group_names" - "'workstation_dev_fedora' in group_names"
- fedora_manage_docker_repo | default(false) - fedora_manage_docker_repo | default(false)
- name: Install COPR support on Fedora WSL
tags: [packages, mise]
ansible.builtin.dnf:
name: dnf-plugins-core
state: present
when: "'workstation_dev_wsl' in group_names"
- name: Configure Mise COPR repository on Fedora WSL
tags: [packages, mise]
community.general.copr:
name: jdxcode/mise
state: enabled
when: "'workstation_dev_wsl' in group_names"
- name: Install distribution signing keys for Fedora desktop codecs - name: Install distribution signing keys for Fedora desktop codecs
tags: [packages, heic] tags: [packages, heic]
ansible.builtin.dnf: ansible.builtin.dnf:
@@ -66,12 +52,16 @@
ansible.builtin.dnf: ansible.builtin.dnf:
update_cache: true update_cache: true
- name: Install HEIC decoder on Fedora desktops - name: Install HEIC decoder when RPM Fusion has a compatible build
tags: [packages, heic] tags: [packages, heic]
ansible.builtin.dnf: ansible.builtin.dnf:
name: libheif-freeworld name: libheif-freeworld
state: present state: present
update_cache: true update_cache: true
# libheif-freeworld requires the exact libheif build. RPM Fusion can lag
# Fedora Updates, so retry on later runs instead of blocking all desktop
# package convergence while the matching build is unavailable.
skip_broken: true
when: "'graphical_desktop' in group_names" when: "'graphical_desktop' in group_names"
- name: Install packages on Fedora - name: Install packages on Fedora
@@ -140,6 +130,10 @@
name: "{{ item.value.npm_package }}" name: "{{ item.value.npm_package }}"
global: true global: true
state: latest state: latest
register: ai_agent_npm_install
retries: "{{ ai_agents_npm_install_retries }}"
delay: "{{ ai_agents_npm_install_retry_delay }}"
until: ai_agent_npm_install is succeeded
loop: "{{ ai_agents | dict2items | selectattr('value.npm_package', 'defined') | list }}" loop: "{{ ai_agents | dict2items | selectattr('value.npm_package', 'defined') | list }}"
when: when:
- item.value.install_enabled | bool - item.value.install_enabled | bool
@@ -160,55 +154,29 @@
loop_control: loop_control:
label: "{{ item.key }}" label: "{{ item.key }}"
- name: Validate ChatGPT desktop architecture on Fedora - name: Manage ChatGPT desktop lifecycle on Fedora graphical hosts
tags: [packages, chatgpt] tags: [packages, chatgpt]
ansible.builtin.assert: ansible.builtin.import_tasks: chatgpt_desktop.yml
that: when:
- ansible_facts['architecture'] in chatgpt_desktop_supported_architectures - "'graphical_desktop' in group_names"
- ansible_facts['distribution_major_version'] in chatgpt_desktop_supported_fedora_versions - chatgpt_desktop_install_enabled | default(false) | bool
fail_msg: >- or chatgpt_desktop_uninstall_enabled | default(false) | bool
ChatGPT desktop supports Fedora {{ chatgpt_desktop_supported_fedora_versions | join(' and ') }}
on x86_64 or aarch64; detected Fedora {{ ansible_facts['distribution_major_version'] }}
on {{ ansible_facts['architecture'] }}.
when: chatgpt_desktop_enabled | bool
- name: Install ChatGPT desktop RPM signing key - name: Manage OpenCode Desktop lifecycle on Fedora graphical hosts
tags: [packages, chatgpt] tags: [packages, opencode_desktop]
ansible.builtin.copy: ansible.builtin.import_tasks: opencode_desktop.yml
src: "{{ chatgpt_desktop_rpm_gpg_key }}" when:
dest: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}" - "'graphical_desktop' in group_names"
owner: root - opencode_desktop_install_enabled | default(false) | bool
group: root or opencode_desktop_uninstall_enabled | default(false) | bool
mode: "0644"
when: chatgpt_desktop_enabled | bool
- name: Import ChatGPT desktop RPM signing key - name: Manage Cline Desktop lifecycle on Fedora graphical hosts
tags: [packages, chatgpt] tags: [packages, cline_desktop]
ansible.builtin.rpm_key: ansible.builtin.import_tasks: cline_desktop.yml
state: present when:
key: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}" - "'graphical_desktop' in group_names"
when: chatgpt_desktop_enabled | bool - cline_desktop_install_enabled | default(false) | bool
or cline_desktop_uninstall_enabled | default(false) | bool
- name: Configure ChatGPT desktop RPM repository
tags: [packages, chatgpt]
ansible.builtin.yum_repository:
name: openai-chatgpt
description: ChatGPT
baseurl: "{{ chatgpt_desktop_rpm_repository }}"
enabled: true
gpgcheck: true
repo_gpgcheck: true
gpgkey: "file:///etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
state: present
when: chatgpt_desktop_enabled | bool
- name: Install ChatGPT desktop on selected Fedora hosts
tags: [packages, chatgpt]
ansible.builtin.dnf:
name: chatgpt
state: latest
update_cache: true
when: chatgpt_desktop_enabled | bool
- name: Define Fedora Flatpak applications - name: Define Fedora Flatpak applications
tags: [packages] tags: [packages]

View File

@@ -0,0 +1,78 @@
---
# OpenCode Desktop ships unsigned RPMs from its GitHub releases; only the
# checksum-verified download makes the local installation trustworthy.
- name: Validate OpenCode Desktop architecture on Fedora
ansible.builtin.assert:
that:
- ansible_facts['architecture'] in opencode_desktop_rpm_checksums
fail_msg: "No verified OpenCode Desktop RPM for {{ ansible_facts['architecture'] }}."
when: opencode_desktop_install_enabled | default(false) | bool
# Runs for both flows so the register below is always valid.
- name: Check for cached OpenCode Desktop RPM
ansible.builtin.stat:
path: "{{ opencode_desktop_rpm_path }}"
get_checksum: false
register: opencode_desktop_rpm_cache
- name: Download verified OpenCode Desktop RPM
ansible.builtin.get_url:
url: "{{ opencode_desktop_rpm_url }}"
dest: "{{ opencode_desktop_rpm_path }}"
checksum: "{{ opencode_desktop_rpm_checksums[ansible_facts['architecture']] }}"
owner: root
group: root
mode: "0644"
# get_url only sends HEAD in check mode and cannot populate a cold cache.
when:
- opencode_desktop_install_enabled | default(false) | bool
- not ansible_check_mode
- name: Install OpenCode Desktop on Fedora
ansible.builtin.dnf:
name: "{{ opencode_desktop_rpm_path }}"
state: present
# Upstream ships an unsigned RPM. The download above verifies its pinned
# SHA-256; do not disable signature checks in system repository settings.
disable_gpg_check: true
when:
- opencode_desktop_install_enabled | default(false) | bool
- not ansible_check_mode
or opencode_desktop_rpm_cache.stat.exists
- name: Explain OpenCode Desktop cold-cache check-mode limitation
ansible.builtin.debug:
msg: >-
A real run will download and SHA-256 verify OpenCode Desktop
{{ opencode_desktop_version }} before ensuring it is installed.
The RPM is not cached, so this dry run cannot validate DNF dependencies.
when:
- opencode_desktop_install_enabled | default(false) | bool
- ansible_check_mode
- not opencode_desktop_rpm_cache.stat.exists
# The `opencode` RPM package name is verified from the pinned release header;
# removal never touches the npm-managed opencode-ai CLI or user data.
- name: Remove OpenCode Desktop from Fedora
ansible.builtin.dnf:
name: opencode
state: absent
when: opencode_desktop_uninstall_enabled | default(false) | bool
# Clean every cached download so retirement also removes outdated pins.
- name: Find cached OpenCode Desktop RPM downloads
ansible.builtin.find:
paths: /var/cache
patterns: "opencode-desktop-*.rpm"
file_type: file
register: opencode_desktop_cached_rpms
when: opencode_desktop_uninstall_enabled | default(false) | bool
- name: Remove cached OpenCode Desktop RPM downloads
ansible.builtin.file:
path: "{{ item.path }}"
state: absent
loop: "{{ opencode_desktop_cached_rpms.files | default([]) }}"
loop_control:
label: "{{ item.path }}"
when: opencode_desktop_uninstall_enabled | default(false) | bool

View File

@@ -106,6 +106,14 @@
state: present state: present
update_cache: false update_cache: false
- name: Remove excluded packages on Void Linux
tags: [packages]
community.general.xbps:
name: "{{ void_removed_packages | default([]) }}"
state: absent
update_cache: false
when: (void_removed_packages | default([])) | length > 0
- name: Check whether the selected display manager is active - name: Check whether the selected display manager is active
tags: [packages, display-manager] tags: [packages, display-manager]
ansible.builtin.stat: ansible.builtin.stat:

View File

@@ -16,9 +16,18 @@ atlas_nextcloud_image: ""
atlas_nextcloud_postgres_image: "" atlas_nextcloud_postgres_image: ""
atlas_nextcloud_redis_image: "" atlas_nextcloud_redis_image: ""
atlas_onlyoffice_image: "" atlas_onlyoffice_image: ""
atlas_nextcloud_backup_root: "{{ atlas_mount_root }}/backup/nextcloud"
atlas_nextcloud_backup_keep: 2
# A structurally complete bundle from an earlier verified run younger than
# this many seconds is reused instead of re-preparing. Keep it below 24h so
# the nightly Borg run, spaced 24h plus its randomized delay, always refreshes
# the bundle; 0 disables reuse.
atlas_nextcloud_backup_reuse_max_seconds: 72000
atlas_nextcloud_admin: admin atlas_nextcloud_admin: admin
atlas_nextcloud_users: [] atlas_nextcloud_users: []
atlas_nextcloud_apps: [] atlas_nextcloud_apps: []
# Existing Archive directories; never import into the internal data namespace.
atlas_nextcloud_external_mounts: []
atlas_nextcloud_services: atlas_nextcloud_services:
- atlas-nextcloud-db.service - atlas-nextcloud-db.service
- atlas-nextcloud-redis.service - atlas-nextcloud-redis.service
@@ -147,7 +156,9 @@ atlas_monitor_effective_timers: >-
atlas_monitor_effective_failure_units: >- atlas_monitor_effective_failure_units: >-
{{ atlas_monitor_failure_units {{ atlas_monitor_failure_units
+ (['atlas-prometheus-pull.service'] + (['atlas-prometheus-pull.service']
if atlas_manage_prometheus_backup_pull | bool else []) }} if atlas_manage_prometheus_backup_pull | bool else [])
+ (['atlas-nextcloud-backup.service', 'atlas-nextcloud-backup-recovery.service']
if atlas_manage_nextcloud | bool else []) }}
atlas_monitor_remote_capacity: {} atlas_monitor_remote_capacity: {}
atlas_monitor_pool_warning_percent: 80 atlas_monitor_pool_warning_percent: 80
atlas_monitor_pool_critical_percent: 90 atlas_monitor_pool_critical_percent: 90
@@ -291,3 +302,58 @@ atlas_media_quadlet_services:
- atlas-immich-machine-learning.service - atlas-immich-machine-learning.service
- atlas-immich-server.service - atlas-immich-server.service
- atlas-npm.service - atlas-npm.service
atlas_manage_qbittorrent: false
atlas_qbittorrent_image: CHANGEME_PINNED_QBITTORRENT_IMAGE
atlas_qbittorrent_state_dir: "{{ atlas_app_data_mountpoint }}/qbittorrent"
atlas_qbittorrent_downloads_dir: "{{ atlas_archive_mountpoint }}/Downloads"
atlas_qbittorrent_web_port: 8090
atlas_qbittorrent_reverse_proxy_enabled: false
atlas_qbittorrent_public_domain: CHANGEME_QBITTORRENT_DOMAIN
atlas_qbittorrent_web_settings:
- {key: 'WebUI\ServerDomains', value: "{{ atlas_qbittorrent_public_domain }}"}
- {key: 'WebUI\ReverseProxySupportEnabled', value: "true"}
- {key: 'WebUI\TrustedReverseProxiesList', value: "{{ atlas_aegis_ip }}"}
- {key: 'WebUI\HostHeaderValidation', value: "true"}
- {key: 'WebUI\CSRFProtection', value: "true"}
- {key: 'WebUI\LocalHostAuth', value: "true"}
- {key: 'WebUI\AuthSubnetWhitelistEnabled', value: "false"}
atlas_manage_aria2: false
atlas_aria2_gateway_enabled: false
atlas_aria2_gateway_port: 8092
atlas_aria2_public_domain: CHANGEME_ARIA2_DOMAIN
atlas_aria2_state_dir: "{{ atlas_app_data_mountpoint }}/aria2"
atlas_aria2_downloads_dir: "{{ atlas_archive_mountpoint }}/Downloads"
atlas_aria2_rpc_port: 6800
atlas_ariang_web_port: 8091
atlas_aria2_image: CHANGEME_PINNED_ARIA2_IMAGE
atlas_ariang_image: CHANGEME_PINNED_ARIANG_IMAGE
# Rootless Paperless-ngx document management. Secrets live only in the encrypted Vault.
atlas_manage_paperless: false
atlas_paperless_dataset: "{{ atlas_zfs_pool }}/services/data/paperless"
atlas_paperless_root: "{{ atlas_app_data_mountpoint }}/paperless"
atlas_paperless_private_dir: "{{ atlas_admin_home }}/.config/atlas-paperless"
atlas_paperless_quadlet_dir: "{{ atlas_admin_home }}/.config/containers/systemd"
atlas_paperless_domain: ""
atlas_paperless_http_port: 8002
atlas_paperless_network_subnet: 10.90.11.0/24
atlas_paperless_network_gateway: 10.90.11.1
atlas_paperless_ocr_language: ita+eng
atlas_paperless_image: ""
atlas_paperless_postgres_image: ""
atlas_paperless_valkey_image: ""
atlas_paperless_tika_image: ""
atlas_paperless_gotenberg_image: ""
atlas_paperless_ollama_image: ""
atlas_paperless_llm_model: qwen2.5:1.5b-instruct-q4_K_M
atlas_paperless_embedding_model: nomic-embed-text:v1.5
atlas_paperless_services:
- atlas-paperless-db.service
- atlas-paperless-valkey.service
- atlas-paperless-tika.service
- atlas-paperless-gotenberg.service
- atlas-paperless-ollama.service
- atlas-paperless.service

View File

@@ -0,0 +1,131 @@
#!/usr/bin/python3
"""Private NPM-only JSON-RPC adapter. Never serves the secret to browsers."""
import argparse
import copy
import http.client
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import threading
MAX_BODY = 2 * 1024 * 1024
def inject(request, token, depth=0):
if depth > 4 or not isinstance(request, dict):
raise ValueError('Invalid RPC request')
result = copy.deepcopy(request)
method = result.get('method', result.get('methodName'))
params = result.setdefault('params', [])
if not isinstance(method, str) or not isinstance(params, list):
raise ValueError('Invalid RPC method or params')
if method == 'system.multicall':
if len(params) != 1 or not isinstance(params[0], list) or len(params[0]) > 128:
raise ValueError('Invalid multicall')
result['params'] = [[inject(item, token, depth + 1) for item in params[0]]]
elif method.startswith('aria2.'):
if params and isinstance(params[0], str) and params[0].startswith('token:'):
params.pop(0)
# Keep RPC security configuration owned by Ansible, not remote callers.
if method in ('aria2.changeGlobalOption', 'aria2.changeOption'):
for value in params:
if isinstance(value, dict) and any(key.startswith('rpc-') for key in value):
raise ValueError('RPC security options are not editable')
params.insert(0, 'token:' + token)
elif method not in ('system.listMethods', 'system.listNotifications'):
raise ValueError('Unsupported RPC method')
return result
def sanitize(value, token):
if isinstance(value, dict):
return {key: sanitize(item, token) for key, item in value.items()
if key not in ('rpc-secret', 'rpc-passwd', 'rpc-user')}
if isinstance(value, list):
return [sanitize(item, token) for item in value]
if isinstance(value, str):
return value.replace(token, '[redacted]')
return value
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--listen', required=True)
parser.add_argument('--port', type=int, required=True)
parser.add_argument('--upstream-port', type=int, required=True)
parser.add_argument('--peer', required=True)
parser.add_argument('--domain', required=True)
parser.add_argument('--secret-file', required=True)
args = parser.parse_args()
token = Path(args.secret_file).read_text().strip()
if len(token) != 64 or any(char not in '0123456789abcdef' for char in token):
raise ValueError('Invalid private RPC secret')
slots = threading.BoundedSemaphore(16)
class Handler(BaseHTTPRequestHandler):
def setup(self):
super().setup()
self.connection.settimeout(15)
def log_message(self, *_):
pass # No credentials, download URLs or request payloads in logs.
def reply(self, status, value):
body = json.dumps(value).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Cache-Control', 'no-store')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
if self.client_address[0] not in (args.peer, args.listen):
return self.reply(403, {'error': 'Forbidden'})
if self.path != '/jsonrpc' or self.headers.get('Host') not in (args.domain, args.domain + ':443'):
return self.reply(403, {'error': 'Forbidden'})
origin = self.headers.get('Origin')
if origin and origin != 'https://' + args.domain:
return self.reply(403, {'error': 'Forbidden origin'})
if self.headers.get('Transfer-Encoding') or self.headers.get('Content-Type', '').split(';')[0].strip() not in ('application/json', 'application/json-rpc'):
return self.reply(415, {'error': 'JSON POST required'})
if not slots.acquire(blocking=False):
return self.reply(503, {'error': 'Busy'})
connection = None
try:
length = int(self.headers.get('Content-Length', '0'))
if not 0 < length <= MAX_BODY:
return self.reply(413, {'error': 'Invalid request size'})
request = json.loads(self.rfile.read(length))
if isinstance(request, list):
if not 0 < len(request) <= 128:
raise ValueError('Invalid batch')
request = [inject(item, token) for item in request]
else:
request = inject(request, token)
body = json.dumps(request).encode()
if len(body) > MAX_BODY:
return self.reply(413, {'error': 'Request too large'})
connection = http.client.HTTPConnection(args.listen, args.upstream_port, timeout=30)
connection.request('POST', '/jsonrpc', body, {'Content-Type': 'application/json'})
response = connection.getresponse()
payload = response.read(MAX_BODY + 1)
if len(payload) > MAX_BODY:
return self.reply(502, {'error': 'Upstream response too large'})
self.reply(response.status, sanitize(json.loads(payload), token))
except (ValueError, TypeError, KeyError):
self.reply(400, {'error': 'Invalid RPC request'})
except (OSError, http.client.HTTPException):
self.reply(502, {'error': 'RPC upstream unavailable'})
finally:
if connection:
connection.close()
slots.release()
server = ThreadingHTTPServer((args.listen, args.port), Handler)
server.daemon_threads = True
server.serve_forever()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,205 @@
---
- name: Manage Atlas LAN HTTP downloader
tags: [atlas, aria2]
when: atlas_manage_aria2 | bool
block:
- name: Require isolated state, shared Downloads and pinned images
ansible.builtin.assert:
that:
- atlas_manage_storage | bool
- atlas_aria2_state_dir == atlas_app_data_mountpoint ~ '/aria2'
- atlas_aria2_downloads_dir == atlas_archive_mountpoint ~ '/Downloads'
- atlas_aria2_image is search('@sha256:[0-9a-f]{64}$')
- atlas_ariang_image is search('@sha256:[0-9a-f]{64}$')
- atlas_aria2_rpc_port != atlas_ariang_web_port
- name: Inspect the existing downloader parent datasets
community.general.zfs_facts:
name: "{{ item.dataset }}"
properties: name,mounted,mountpoint
loop:
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_archive }}"
mountpoint: "{{ atlas_archive_mountpoint }}"
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}"
mountpoint: "{{ atlas_app_data_mountpoint }}"
register: atlas_aria2_parents
- name: Require mounted downloader parent datasets
ansible.builtin.assert:
that:
- item.ansible_facts.ansible_zfs_datasets | length == 1
- item.ansible_facts.ansible_zfs_datasets[0].mounted == 'yes'
- item.ansible_facts.ansible_zfs_datasets[0].mountpoint == item.item.mountpoint
loop: "{{ atlas_aria2_parents.results }}"
loop_control:
label: "{{ item.item.dataset }}"
- name: Inspect shared Downloads without following links
ansible.builtin.stat:
path: "{{ atlas_aria2_downloads_dir }}"
follow: false
register: atlas_aria2_downloads
- name: Refuse unrelated or symlinked Downloads
ansible.builtin.assert:
that:
- >-
not atlas_aria2_downloads.stat.exists or
(atlas_aria2_downloads.stat.isdir | default(false) and
atlas_aria2_downloads.stat.uid | int == atlas_admin_uid | int)
- name: Create the private aria2 dataset
community.general.zfs:
name: "{{ atlas_zfs_pool }}/services/data/aria2"
state: present
extra_zfs_properties:
compression: zstd
mountpoint: "{{ atlas_aria2_state_dir }}"
- name: Prepare state, downloads and Quadlet directories
ansible.builtin.file:
path: "{{ item.path }}"
state: directory
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "{{ item.mode }}"
loop:
- {path: "{{ atlas_aria2_state_dir }}", mode: "0700"}
- {path: "{{ atlas_aria2_downloads_dir }}", mode: "0770"}
- {path: "{{ atlas_admin_home }}/.config/containers/systemd", mode: "0700"}
- name: Generate a private persistent RPC secret on Atlas only
become_user: "{{ atlas_admin_username }}"
ansible.builtin.command:
argv:
- python3
- -c
- >-
import os, secrets;
fd = os.open('{{ atlas_aria2_state_dir }}/rpc-secret',
os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600);
os.write(fd, (secrets.token_hex(32) + '\n').encode()); os.close(fd)
creates: "{{ atlas_aria2_state_dir }}/rpc-secret"
no_log: true
- name: Read the existing private RPC secret without displaying it
ansible.builtin.slurp:
src: "{{ atlas_aria2_state_dir }}/rpc-secret"
register: atlas_aria2_rpc_secret
no_log: true
when: not ansible_check_mode
- name: Require a strong RPC secret
ansible.builtin.assert:
that:
- atlas_aria2_rpc_secret.content | b64decode | trim is match('^[a-f0-9]{64}$')
no_log: true
when: not ansible_check_mode
- name: Initialize the session file without replacing saved downloads
ansible.builtin.copy:
content: ""
dest: "{{ atlas_aria2_state_dir }}/session"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0600"
force: false
diff: false
no_log: true
- name: Render private aria2 configuration
ansible.builtin.template:
src: atlas-aria2.conf.j2
dest: "{{ atlas_aria2_state_dir }}/aria2.conf"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0600"
register: atlas_aria2_config
no_log: true
diff: false
when: not ansible_check_mode
- name: Allow only the LAN to reach AriaNg and the token-protected API
ansible.posix.firewalld:
zone: "{{ atlas_firewalld_zone }}"
rich_rule: >-
rule family="ipv4" source address="{{ atlas_lan_subnet }}"
port port="{{ item }}" protocol="tcp" accept
permanent: true
immediate: true
state: enabled
loop:
- "{{ atlas_aria2_rpc_port }}"
- "{{ atlas_ariang_web_port }}"
- name: Keep the downloader user manager available at boot
ansible.builtin.command: "loginctl enable-linger {{ atlas_admin_username }}"
args:
creates: "/var/lib/systemd/linger/{{ atlas_admin_username }}"
- name: Render the downloader and static Web UI Quadlets
ansible.builtin.template:
src: "atlas-{{ item }}.container.j2"
dest: "{{ atlas_admin_home }}/.config/containers/systemd/atlas-{{ item }}.container"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0644"
loop: [aria2, ariang]
register: atlas_aria2_quadlets
- name: Reload the user manager after downloader Quadlet changes
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
scope: user
daemon_reload: true
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when:
- atlas_aria2_quadlets.changed
- not ansible_check_mode
- name: Start or update only the changed downloader service
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
scope: user
name: "atlas-{{ item.item }}.service"
state: >-
{{ 'restarted' if item.changed or
(item.item == 'aria2' and atlas_aria2_config.changed | default(false))
else 'started' }}
loop: "{{ atlas_aria2_quadlets.results }}"
loop_control:
label: "atlas-{{ item.item }}.service"
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when: not ansible_check_mode
- name: Verify the LAN Web UI responds
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ atlas_ariang_web_port }}/"
status_code: 200
register: atlas_ariang_http
retries: 15
delay: 2
until: atlas_ariang_http is succeeded
when: not ansible_check_mode
- name: Verify the authenticated RPC API
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ atlas_aria2_rpc_port }}/jsonrpc"
method: POST
body_format: json
body:
jsonrpc: "2.0"
id: ansible
method: aria2.getVersion
params: ["token:{{ atlas_aria2_rpc_secret.content | b64decode | trim }}"]
return_content: true
register: atlas_aria2_rpc_probe
retries: 15
delay: 2
until: (atlas_aria2_rpc_probe.content | default('{}') | from_json).result.version is defined
no_log: true
when: not ansible_check_mode

View File

@@ -0,0 +1,81 @@
---
- name: Manage the private NPM aria2 adapter
tags: [atlas, aria2_gateway]
when:
- atlas_manage_aria2 | bool
- atlas_aria2_gateway_enabled | bool
block:
- name: Require a dedicated gateway and explicit public domain
ansible.builtin.assert:
that:
- atlas_aria2_gateway_port not in [atlas_aria2_rpc_port, atlas_ariang_web_port]
- atlas_aria2_public_domain is match('^[a-z0-9][a-z0-9.-]+[.][a-z]{2,}$')
- not atlas_aria2_public_domain.startswith('CHANGEME')
- name: Install the private JSON-RPC adapter
ansible.builtin.copy:
src: atlas-aria2-rpc-gateway.py
dest: "{{ atlas_aria2_state_dir }}/rpc-gateway.py"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0600"
register: atlas_aria2_gateway_script
- name: Prepare the user unit directory
ansible.builtin.file:
path: "{{ atlas_admin_home }}/.config/systemd/user"
state: directory
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0700"
- name: Install the user gateway unit
ansible.builtin.template:
src: atlas-aria2-gateway.service.j2
dest: "{{ atlas_admin_home }}/.config/systemd/user/atlas-aria2-gateway.service"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0644"
register: atlas_aria2_gateway_unit
- name: Allow only Aegis to reach the credential-injecting adapter
ansible.posix.firewalld:
zone: "{{ atlas_firewalld_zone }}"
rich_rule: >-
rule family="ipv4" source address="{{ atlas_aegis_ip }}"
port port="{{ atlas_aria2_gateway_port }}" protocol="tcp" accept
permanent: true
immediate: true
state: enabled
- name: Enable and start the private gateway
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd_service:
scope: user
name: atlas-aria2-gateway.service
daemon_reload: "{{ atlas_aria2_gateway_unit.changed }}"
enabled: true
state: "{{ 'restarted' if atlas_aria2_gateway_script.changed or atlas_aria2_gateway_unit.changed else 'started' }}"
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when: not ansible_check_mode
- name: Verify token-free requests through the private adapter
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ atlas_aria2_gateway_port }}/jsonrpc"
headers:
Host: "{{ atlas_aria2_public_domain }}"
method: POST
body_format: json
body:
jsonrpc: "2.0"
id: ansible-gateway
method: aria2.getVersion
params: []
return_content: true
register: atlas_aria2_gateway_probe
retries: 10
delay: 2
until: atlas_aria2_gateway_probe.json.result.version is defined
when: not ansible_check_mode

View File

@@ -26,6 +26,18 @@
- name: Import Atlas iCloudPD storage and boot-started Quadlet tasks - name: Import Atlas iCloudPD storage and boot-started Quadlet tasks
ansible.builtin.import_tasks: icloudpd.yml ansible.builtin.import_tasks: icloudpd.yml
- name: Import Atlas Paperless-ngx document-management service
ansible.builtin.import_tasks: paperless.yml
- name: Import Atlas torrent service
ansible.builtin.import_tasks: qbittorrent.yml
- name: Import Atlas LAN HTTP downloader
ansible.builtin.import_tasks: aria2.yml
- name: Import Atlas private aria2 RPC gateway
ansible.builtin.import_tasks: aria2_gateway.yml
- name: Import Atlas ZFS maintenance tasks - name: Import Atlas ZFS maintenance tasks
ansible.builtin.import_tasks: zfs_maintenance.yml ansible.builtin.import_tasks: zfs_maintenance.yml
@@ -35,6 +47,9 @@
- name: Import Atlas offline USB backup tasks - name: Import Atlas offline USB backup tasks
ansible.builtin.import_tasks: usb_backup.yml ansible.builtin.import_tasks: usb_backup.yml
- name: Import recurring Nextcloud backup preparation
ansible.builtin.import_tasks: nextcloud_backup.yml
- name: Import Atlas Prometheus backup pull identity tasks - name: Import Atlas Prometheus backup pull identity tasks
ansible.builtin.import_tasks: prometheus_pull_identity.yml ansible.builtin.import_tasks: prometheus_pull_identity.yml

View File

@@ -39,6 +39,10 @@
(atlas_nextcloud_users | map(attribute='password') | list) }} (atlas_nextcloud_users | map(attribute='password') | list) }}
no_log: true no_log: true
- name: Prepare access to declared existing Archive directories
ansible.builtin.include_tasks: nextcloud_external_access.yml
when: atlas_nextcloud_external_mounts | length > 0
- name: Verify the existing application-data parent is mounted - name: Verify the existing application-data parent is mounted
community.general.zfs_facts: community.general.zfs_facts:
name: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}" name: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}"
@@ -146,6 +150,15 @@
diff: false diff: false
register: atlas_nextcloud_private_configuration register: atlas_nextcloud_private_configuration
- name: Hide ONLYOFFICE welcome and example endpoints without changing editor routes
ansible.builtin.template:
src: atlas-onlyoffice-access.conf.j2
dest: "{{ atlas_nextcloud_private_dir }}/onlyoffice-access.conf"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0644"
register: atlas_onlyoffice_access_configuration
- name: Download checksum-pinned compatible application releases - name: Download checksum-pinned compatible application releases
ansible.builtin.get_url: ansible.builtin.get_url:
url: "{{ item.url }}" url: "{{ item.url }}"
@@ -197,7 +210,8 @@
owner: "{{ atlas_admin_username }}" owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}" group: "{{ atlas_admin_group }}"
mode: "0644" mode: "0644"
loop: [atlas-nextcloud-cron.service, atlas-nextcloud-cron.timer] loop: [atlas-nextcloud-cron.service, atlas-nextcloud-cron.timer,
atlas-nextcloud-external-scan.service, atlas-nextcloud-external-scan.timer]
register: atlas_nextcloud_cron_units register: atlas_nextcloud_cron_units
- name: Manage and verify rootless Nextcloud services - name: Manage and verify rootless Nextcloud services
@@ -227,7 +241,14 @@
scope: user scope: user
name: "{{ item }}" name: "{{ item }}"
state: >- state: >-
{{ 'restarted' if (atlas_nextcloud_quadlets is changed or {{ 'restarted' if (
atlas_nextcloud_quadlets.results |
selectattr('item', 'equalto', item | replace('.service', '.container')) |
selectattr('changed') | list | length > 0 or
atlas_nextcloud_quadlets.results |
selectattr('item', 'equalto', 'atlas-nextcloud.network') |
selectattr('changed') | list | length > 0 or
(item == 'atlas-onlyoffice.service' and atlas_onlyoffice_access_configuration is changed) or
atlas_nextcloud_private_configuration is changed or atlas_nextcloud_private_configuration is changed or
atlas_nextcloud_secret_files is changed) else 'started' }} atlas_nextcloud_secret_files is changed) else 'started' }}
loop: "{{ atlas_nextcloud_services }}" loop: "{{ atlas_nextcloud_services }}"
@@ -299,6 +320,14 @@
state: "{{ 'restarted' if atlas_nextcloud_cron_units is changed else 'started' }}" state: "{{ 'restarted' if atlas_nextcloud_cron_units is changed else 'started' }}"
enabled: true enabled: true
- name: Enable periodic targeted Archive discovery
ansible.builtin.systemd:
scope: user
name: atlas-nextcloud-external-scan.timer
state: "{{ 'restarted' if atlas_nextcloud_cron_units is changed else 'started' }}"
enabled: true
when: atlas_nextcloud_external_mounts | length > 0
- name: Verify ONLYOFFICE local health without publishing the domain - name: Verify ONLYOFFICE local health without publishing the domain
ansible.builtin.uri: ansible.builtin.uri:
url: "http://127.0.0.1:{{ atlas_onlyoffice_http_port }}/healthcheck" url: "http://127.0.0.1:{{ atlas_onlyoffice_http_port }}/healthcheck"

View File

@@ -169,3 +169,18 @@
argv: [podman, exec, --user, '33', atlas-nextcloud, php, occ, background:cron] argv: [podman, exec, --user, '33', atlas-nextcloud, php, occ, background:cron]
when: atlas_nextcloud_background_mode.stdout | trim != 'cron' when: atlas_nextcloud_background_mode.stdout | trim != 'cron'
changed_when: true changed_when: true
- name: Enable shipped external storage support when required
ansible.builtin.command:
argv: [podman, exec, --user, '33', atlas-nextcloud, php, occ, app:enable, files_external]
when:
- atlas_nextcloud_external_mounts | length > 0
- "'files_external' not in (atlas_nextcloud_current_apps.stdout | from_json).enabled"
changed_when: true
- name: Maintain only the declared Archive mounts
ansible.builtin.include_tasks: nextcloud_external_mount.yml
loop: "{{ atlas_nextcloud_external_mounts }}"
loop_control:
loop_var: atlas_nextcloud_mount
label: "{{ atlas_nextcloud_mount.name }}"

View File

@@ -0,0 +1,58 @@
---
- name: Manage recurring consistent Nextcloud backup preparation
tags: [atlas, nextcloud_backup]
when: atlas_manage_nextcloud | bool
block:
- name: Validate private backup scope, retention, and bundle reuse window
ansible.builtin.assert:
that:
- atlas_nextcloud_backup_root == atlas_mount_root ~ '/backup/nextcloud'
- atlas_nextcloud_backup_keep | int >= 2
- atlas_nextcloud_backup_reuse_max_seconds | int >= 0
# Below 24h the nightly Borg run cannot reuse the previous bundle.
- atlas_nextcloud_backup_reuse_max_seconds | int < 86400
- atlas_manage_borg_backup | bool
- atlas_manage_usb_backup | bool
- name: Install recurring backup helper with shell syntax validation
ansible.builtin.template:
src: atlas-nextcloud-backup.sh.j2
dest: /usr/local/sbin/atlas-nextcloud-backup
owner: root
group: root
mode: "0750"
validate: /bin/bash -n %s
- name: Install Nextcloud backup preparation and boot recovery units
ansible.builtin.template:
src: "{{ item }}.j2"
dest: "/etc/systemd/system/{{ item }}"
owner: root
group: root
mode: "0644"
loop: [atlas-nextcloud-backup.service, atlas-nextcloud-backup-recovery.service]
- name: Create backup dependency drop-in directories
ansible.builtin.file:
path: "/etc/systemd/system/{{ item }}.d"
state: directory
owner: root
group: root
mode: "0755"
loop: [atlas-borg-backup.service, atlas-usb-backup.service]
- name: Require a fresh consistent bundle before offsite and manual USB backups
ansible.builtin.template:
src: atlas-nextcloud-backup-dependency.conf.j2
dest: "/etc/systemd/system/{{ item }}.d/nextcloud.conf"
owner: root
group: root
mode: "0644"
loop: [atlas-borg-backup.service, atlas-usb-backup.service]
- name: Reload systemd and enable interruption recovery without running a backup
ansible.builtin.systemd:
daemon_reload: true
name: atlas-nextcloud-backup-recovery.service
enabled: true
when: not ansible_check_mode

View File

@@ -0,0 +1,112 @@
---
- name: Restrict external storage to explicit Archive directories
ansible.builtin.assert:
that:
- item.source in [atlas_archive_mountpoint ~ '/Documents', atlas_icloudpd_photos_dir]
- item.target is match('^/mnt/archive-[a-z]+$')
- item.name is match('^[A-Za-z][A-Za-z ]+$')
- item.readonly is boolean
- item.user in (atlas_nextcloud_users | map(attribute='username') | list)
- item.source != atlas_icloudpd_photos_dir or item.readonly
loop: "{{ atlas_nextcloud_external_mounts }}"
- name: Inspect existing sources without creating or moving data
ansible.builtin.stat:
path: "{{ item.source }}"
follow: false
loop: "{{ atlas_nextcloud_external_mounts }}"
register: atlas_nextcloud_external_sources
- name: Refuse missing sources and symlinks
ansible.builtin.assert:
that:
- item.stat.isdir | default(false)
- not (item.stat.islnk | default(false))
loop: "{{ atlas_nextcloud_external_sources.results }}"
loop_control:
label: "{{ item.item.source }}"
- name: Verify the Archive dataset before modifying its ACL capability
community.general.zfs_facts:
name: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_archive }}"
properties: name,mounted,mountpoint
register: atlas_nextcloud_external_dataset
- name: Refuse an absent or unmounted Archive dataset
ansible.builtin.assert:
that:
- atlas_nextcloud_external_dataset.ansible_facts.ansible_zfs_datasets | length == 1
- atlas_nextcloud_external_dataset.ansible_facts.ansible_zfs_datasets[0].mounted == 'yes'
- atlas_nextcloud_external_dataset.ansible_facts.ansible_zfs_datasets[0].mountpoint == atlas_archive_mountpoint
- name: Enable persistent POSIX ACL support on the verified Archive dataset
community.general.zfs:
name: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_archive }}"
state: present
extra_zfs_properties:
acltype: posix
- name: Derive actual rootless web UID for narrowly scoped Archive ACLs
become_user: "{{ atlas_admin_username }}"
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
ansible.builtin.command:
argv:
- podman
- unshare
- python3
- -c
- >-
print(next(int(b)+33-int(a) for a,b,n in
(l.split() for l in open('/proc/self/uid_map')) if int(a)<=33<int(a)+int(n)))
register: atlas_nextcloud_external_uid
changed_when: false
check_mode: false
- name: Grant web user access only inside the declared sources
ansible.posix.acl:
path: "{{ item.source }}"
entity: "{{ atlas_nextcloud_external_uid.stdout | trim }}"
etype: user
permissions: "{{ 'rX' if item.readonly else 'rwX' }}"
recursive: true
follow: false
state: present
loop: "{{ atlas_nextcloud_external_mounts }}"
- name: Restore effective web write access inside writable external storage
ansible.posix.acl:
path: "{{ item.source }}"
etype: mask
permissions: rwX
recursive: true
follow: false
recalculate_mask: no_mask
state: present
loop: "{{ atlas_nextcloud_external_mounts }}"
when: not item.readonly
- name: Inherit web access on new files and directories
ansible.posix.acl:
path: "{{ item.source }}"
entity: "{{ atlas_nextcloud_external_uid.stdout | trim }}"
etype: user
permissions: "{{ 'rX' if item.readonly else 'rwX' }}"
default: true
recursive: true
follow: false
state: present
loop: "{{ atlas_nextcloud_external_mounts }}"
- name: Preserve administrator access to documents created through Nextcloud
ansible.posix.acl:
path: "{{ item.source }}"
entity: "{{ atlas_admin_uid }}"
etype: user
permissions: rwX
default: true
recursive: true
follow: false
state: present
loop: "{{ atlas_nextcloud_external_mounts }}"
when: not item.readonly

View File

@@ -0,0 +1,94 @@
---
- name: Inspect current system mounts without exposing credentials
ansible.builtin.command:
argv: [podman, exec, --user, '33', atlas-nextcloud, php, occ, files_external:list, --output=json]
register: atlas_nextcloud_mount_list
changed_when: false
no_log: true
- name: Select only the matching mount name
ansible.builtin.set_fact:
atlas_nextcloud_matching_mounts: >-
{{ atlas_nextcloud_mount_list.stdout | from_json |
selectattr('mount_point', 'equalto', '/' ~ atlas_nextcloud_mount.name) | list }}
no_log: true
- name: Refuse duplicates or repurposing of existing unrelated storage
ansible.builtin.assert:
that:
- atlas_nextcloud_matching_mounts | length <= 1
- >-
atlas_nextcloud_matching_mounts | length == 0 or
(atlas_nextcloud_matching_mounts[0].configuration.datadir | default('') == atlas_nextcloud_mount.target
and atlas_nextcloud_matching_mounts[0].storage == '\\OC\\Files\\Storage\\Local')
fail_msg: Existing storage conflicts with the declared Archive mount; refusing an implicit replacement.
- name: Create an absent local mount restricted to its declared user
ansible.builtin.command:
argv:
- podman
- exec
- --user
- '33'
- atlas-nextcloud
- php
- occ
- files_external:create
- "{{ atlas_nextcloud_mount.name }}"
- local
- null::null
- --config
- "datadir={{ atlas_nextcloud_mount.target }}"
- --applicable-user
- "{{ atlas_nextcloud_mount.user }}"
- --output=json
when: atlas_nextcloud_matching_mounts | length == 0
register: atlas_nextcloud_mount_created
changed_when: true
- name: Record the managed mount ID and options
ansible.builtin.set_fact:
atlas_nextcloud_mount_id: >-
{{ atlas_nextcloud_mount_created.stdout | trim if atlas_nextcloud_matching_mounts | length == 0
else atlas_nextcloud_matching_mounts[0].mount_id }}
atlas_nextcloud_mount_options: >-
{{ {} if atlas_nextcloud_matching_mounts | length == 0 else atlas_nextcloud_matching_mounts[0].options }}
- name: Restrict the managed mount to exactly its declared user
ansible.builtin.command:
argv: >-
{{ ['podman', 'exec', '--user', '33', 'atlas-nextcloud', 'php', 'occ',
'files_external:applicable', atlas_nextcloud_mount_id | string,
'--add-user=' ~ atlas_nextcloud_mount.user] +
(atlas_nextcloud_matching_mounts[0].applicable_groups |
map('regex_replace', '^', '--remove-group=') | list) +
(atlas_nextcloud_matching_mounts[0].applicable_users |
reject('equalto', atlas_nextcloud_mount.user) |
map('regex_replace', '^', '--remove-user=') | list) }}
when:
- atlas_nextcloud_matching_mounts | length > 0
- >-
atlas_nextcloud_matching_mounts[0].applicable_groups | length > 0 or
atlas_nextcloud_matching_mounts[0].applicable_users != [atlas_nextcloud_mount.user]
changed_when: true
- name: Maintain read-only photos and external change detection
ansible.builtin.command:
argv: [podman, exec, --user, '33', atlas-nextcloud, php, occ, files_external:option,
"{{ atlas_nextcloud_mount_id }}", "{{ item.key }}", "{{ item.value | to_json }}"]
loop:
- {key: readonly, value: "{{ atlas_nextcloud_mount.readonly }}"}
- {key: filesystem_check_changes, value: 1}
- {key: enable_sharing, value: false}
# Nextcloud persists option values as strings ("1" / "" for booleans).
when: >-
item.key not in atlas_nextcloud_mount_options or
atlas_nextcloud_mount_options[item.key] | string !=
(('1' if item.value else '') if item.value is boolean else item.value | string)
changed_when: true
- name: Verify the managed local storage is accessible
ansible.builtin.command:
argv: [podman, exec, --user, '33', atlas-nextcloud, php, occ, files_external:verify,
"{{ atlas_nextcloud_mount_id }}"]
changed_when: false

View File

@@ -0,0 +1,255 @@
---
- name: Manage Atlas rootless Paperless-ngx
tags: [atlas, paperless]
when: atlas_manage_paperless | bool
block:
- name: Require isolated Paperless state, public domain and pinned images
ansible.builtin.assert:
that:
- atlas_manage_storage | bool
- atlas_manage_firewall | bool
- atlas_paperless_root == atlas_app_data_mountpoint ~ '/paperless'
- atlas_paperless_dataset == atlas_zfs_pool ~ '/services/data/paperless'
- atlas_paperless_domain is match('^[a-z0-9]+([.-][a-z0-9]+)+$')
- atlas_paperless_http_port | int > 1024
- atlas_paperless_http_port | int < 65536
- atlas_paperless_network_subnet != atlas_nextcloud_network_subnet
- item is search('@sha256:[0-9a-f]{64}$')
loop:
- "{{ atlas_paperless_image }}"
- "{{ atlas_paperless_postgres_image }}"
- "{{ atlas_paperless_valkey_image }}"
- "{{ atlas_paperless_tika_image }}"
- "{{ atlas_paperless_gotenberg_image }}"
- "{{ atlas_paperless_ollama_image }}"
- name: Require dedicated Paperless Vault secrets without exposing them
ansible.builtin.assert:
that:
- vault_paperless_database_password | default('') is match('^[a-zA-Z0-9]{32,}$')
- vault_paperless_secret_key | default('') | length >= 64
no_log: true
- name: Verify the existing application-data parent is mounted
community.general.zfs_facts:
name: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}"
properties: name,mounted,mountpoint
register: atlas_paperless_parent
- name: Require the verified application-data parent
ansible.builtin.assert:
that:
- atlas_paperless_parent.ansible_facts.ansible_zfs_datasets | length == 1
- atlas_paperless_parent.ansible_facts.ansible_zfs_datasets[0].mounted == 'yes'
- atlas_paperless_parent.ansible_facts.ansible_zfs_datasets[0].mountpoint == atlas_app_data_mountpoint
- name: Create dedicated Paperless component datasets
community.general.zfs:
name: "{{ atlas_paperless_dataset }}{{ item }}"
state: present
extra_zfs_properties:
compression: zstd
mountpoint: "{{ atlas_paperless_root }}{{ item }}"
loop: ['', /data, /media, /consume, /database, /cache, /ollama]
- name: Prepare private Paperless paths and Quadlet directory
ansible.builtin.file:
path: "{{ item }}"
state: directory
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0700"
loop:
- "{{ atlas_paperless_root }}"
- "{{ atlas_paperless_root }}/data"
- "{{ atlas_paperless_root }}/media"
- "{{ atlas_paperless_root }}/consume"
- "{{ atlas_paperless_root }}/ollama"
- "{{ atlas_paperless_private_dir }}"
- "{{ atlas_paperless_quadlet_dir }}"
- name: Derive the rootless PostgreSQL host UID
become_user: "{{ atlas_admin_username }}"
ansible.builtin.command:
argv:
- podman
- unshare
- python3
- -c
- >-
print(next(int(host) + 999 - int(container) for container, host, size in
(line.split() for line in open('/proc/self/uid_map'))
if int(container) <= 999 < int(container) + int(size)))
register: atlas_paperless_postgres_host_uid
check_mode: false
changed_when: false
- name: Allow the rootless PostgreSQL UID to traverse its dataset root
ansible.builtin.file:
path: "{{ atlas_paperless_root }}/database"
state: directory
owner: "{{ atlas_paperless_postgres_host_uid.stdout | trim }}"
group: "{{ atlas_admin_group }}"
mode: "0700"
- name: Allow the rootless Valkey UID to write its persistent cache
ansible.builtin.file:
path: "{{ atlas_paperless_root }}/cache"
state: directory
owner: "{{ atlas_paperless_postgres_host_uid.stdout | trim }}"
group: "{{ atlas_admin_group }}"
mode: "0700"
register: atlas_paperless_cache_root
- name: Store Paperless secrets in private mounted files
ansible.builtin.copy:
content: "{{ item.value }}\n"
dest: "{{ atlas_paperless_private_dir }}/{{ item.name }}"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0644"
loop:
- {name: postgres-password, value: "{{ vault_paperless_database_password }}"}
- {name: secret-key, value: "{{ vault_paperless_secret_key }}"}
no_log: true
diff: false
register: atlas_paperless_secret_files
- name: Admit only the Aegis gateway to the Paperless listener
ansible.posix.firewalld:
rich_rule: >-
rule family="ipv4" source address="{{ atlas_aegis_ip }}"
port port="{{ atlas_paperless_http_port }}" protocol="tcp" accept
zone: "{{ atlas_firewalld_zone }}"
state: enabled
permanent: true
immediate: true
- name: Keep the Paperless rootless user manager available at boot
ansible.builtin.command:
argv: [loginctl, enable-linger, "{{ atlas_admin_username }}"]
args:
creates: "/var/lib/systemd/linger/{{ atlas_admin_username }}"
- name: Render the private Paperless Quadlets
ansible.builtin.template:
src: "{{ item }}.j2"
dest: "{{ atlas_paperless_quadlet_dir }}/{{ item }}"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0644"
loop:
- atlas-paperless.network
- atlas-paperless-db.container
- atlas-paperless-valkey.container
- atlas-paperless-tika.container
- atlas-paperless-gotenberg.container
- atlas-paperless-ollama.container
- atlas-paperless.container
register: atlas_paperless_quadlets
- name: Pull, start and verify Paperless
become_user: "{{ atlas_admin_username }}"
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when: not ansible_check_mode
block:
- name: Pull the pinned Paperless images before starting services
containers.podman.podman_image:
name: "{{ item }}"
state: present
loop:
- "{{ atlas_paperless_image }}"
- "{{ atlas_paperless_postgres_image }}"
- "{{ atlas_paperless_valkey_image }}"
- "{{ atlas_paperless_tika_image }}"
- "{{ atlas_paperless_gotenberg_image }}"
- "{{ atlas_paperless_ollama_image }}"
- name: Reload the rootless user manager for Paperless
ansible.builtin.systemd:
scope: user
daemon_reload: true
- name: Start Paperless component services
ansible.builtin.systemd:
scope: user
name: "{{ item }}"
state: >-
{{ 'restarted' if
(atlas_paperless_quadlets.results |
selectattr('item', 'equalto', item | replace('.service', '.container')) |
selectattr('changed') | list | length > 0) or
(atlas_paperless_quadlets.results |
selectattr('item', 'equalto', 'atlas-paperless.network') |
selectattr('changed') | list | length > 0) or
(atlas_paperless_secret_files is changed and
item in ['atlas-paperless-db.service', 'atlas-paperless.service']) or
(atlas_paperless_cache_root is changed and
item == 'atlas-paperless-valkey.service') else 'started' }}
enabled: true
loop: "{{ atlas_paperless_services }}"
- name: Verify the Paperless HTTP service through its LAN listener
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ atlas_paperless_http_port }}/"
status_code: [200, 302]
register: atlas_paperless_http
retries: 60
delay: 5
until: atlas_paperless_http is succeeded
- name: Verify the private Ollama API from Paperless
ansible.builtin.command:
argv:
- podman
- exec
- atlas-paperless
- python3
- -c
- >-
import urllib.request;
urllib.request.urlopen('http://atlas-paperless-ollama:11434/api/tags', timeout=10).close()
register: atlas_paperless_ollama_health
changed_when: false
retries: 30
delay: 5
until: atlas_paperless_ollama_health.rc == 0
- name: Check whether the local AI models are present
ansible.builtin.command:
argv: [podman, exec, atlas-paperless-ollama, ollama, show, "{{ item }}"]
loop:
- "{{ atlas_paperless_llm_model }}"
- "{{ atlas_paperless_embedding_model }}"
register: atlas_paperless_model_checks
changed_when: false
failed_when: false
- name: Download missing local AI models
ansible.builtin.command:
argv: [podman, exec, atlas-paperless-ollama, ollama, pull, "{{ item.item }}"]
loop: "{{ atlas_paperless_model_checks.results }}"
when: item.rc != 0
loop_control:
label: "{{ item.item }}"
- name: Verify private Office conversion endpoints from Paperless
ansible.builtin.command:
argv:
- podman
- exec
- atlas-paperless
- python3
- -c
- >-
import urllib.request;
urls = ['http://atlas-paperless-tika:9998/version',
'http://atlas-paperless-gotenberg:3000/health'];
[urllib.request.urlopen(url, timeout=10).close() for url in urls]
register: atlas_paperless_office_health
changed_when: false
retries: 30
delay: 5
until: atlas_paperless_office_health.rc == 0

View File

@@ -0,0 +1,186 @@
---
- name: Manage Atlas rootless qBittorrent
tags: [atlas, qbittorrent]
when: atlas_manage_qbittorrent | bool
block:
- name: Require isolated paths and a pinned image
ansible.builtin.assert:
that:
- atlas_manage_storage | bool
- atlas_qbittorrent_state_dir == atlas_app_data_mountpoint ~ '/qbittorrent'
- atlas_qbittorrent_downloads_dir == atlas_archive_mountpoint ~ '/Downloads'
- atlas_qbittorrent_image is search('@sha256:[0-9a-f]{64}$')
- name: Inspect the existing parent datasets
community.general.zfs_facts:
name: "{{ item.dataset }}"
properties: name,mounted,mountpoint
loop:
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_archive }}"
mountpoint: "{{ atlas_archive_mountpoint }}"
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}"
mountpoint: "{{ atlas_app_data_mountpoint }}"
register: atlas_qbittorrent_parents
- name: Refuse missing or unmounted parent datasets
ansible.builtin.assert:
that:
- item.ansible_facts.ansible_zfs_datasets | length == 1
- item.ansible_facts.ansible_zfs_datasets[0].mounted == 'yes'
- item.ansible_facts.ansible_zfs_datasets[0].mountpoint == item.item.mountpoint
loop: "{{ atlas_qbittorrent_parents.results }}"
loop_control:
label: "{{ item.item.dataset }}"
- name: Inspect the proposed download directory without following links
ansible.builtin.stat:
path: "{{ atlas_qbittorrent_downloads_dir }}"
follow: false
register: atlas_qbittorrent_downloads
- name: Refuse unrelated or symlinked download paths
ansible.builtin.assert:
that:
- >-
not atlas_qbittorrent_downloads.stat.exists or
(atlas_qbittorrent_downloads.stat.isdir | default(false) and
atlas_qbittorrent_downloads.stat.uid | int == atlas_admin_uid | int)
- name: Create the dedicated configuration dataset
community.general.zfs:
name: "{{ atlas_zfs_pool }}/services/data/qbittorrent"
state: present
extra_zfs_properties:
compression: zstd
mountpoint: "{{ atlas_qbittorrent_state_dir }}"
- name: Prepare private state and the SMB download directory
ansible.builtin.file:
path: "{{ item.path }}"
state: directory
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "{{ item.mode }}"
loop:
- {path: "{{ atlas_qbittorrent_state_dir }}", mode: "0700"}
- {path: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config", mode: "0700"}
- {path: "{{ atlas_qbittorrent_downloads_dir }}", mode: "0770"}
- {path: "{{ atlas_admin_home }}/.config/containers/systemd", mode: "0700"}
- name: Seed qBittorrent settings without overwriting application-managed state
ansible.builtin.template:
src: atlas-qbittorrent.conf.j2
dest: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config/qBittorrent.conf"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0600"
force: false
diff: false
- name: Allow only the declared LAN to reach the Web UI
ansible.posix.firewalld:
zone: "{{ atlas_firewalld_zone }}"
rich_rule: >-
rule family="ipv4" source address="{{ atlas_lan_subnet }}"
port port="{{ atlas_qbittorrent_web_port }}" protocol="tcp" accept
permanent: true
immediate: true
state: enabled
- name: Keep the rootless user manager available at boot
ansible.builtin.command: "loginctl enable-linger {{ atlas_admin_username }}"
args:
creates: "/var/lib/systemd/linger/{{ atlas_admin_username }}"
- name: Render the rootless torrent Quadlet
ansible.builtin.template:
src: atlas-qbittorrent.container.j2
dest: "{{ atlas_admin_home }}/.config/containers/systemd/atlas-qbittorrent.container"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0644"
register: atlas_qbittorrent_quadlet
- name: Reload the user manager after a new or changed Quadlet
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
scope: user
daemon_reload: true
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when:
- atlas_qbittorrent_quadlet.changed
- not ansible_check_mode
- name: Manage the declared qBittorrent reverse-proxy settings
when: atlas_qbittorrent_reverse_proxy_enabled | bool
block:
- name: Require a specific public domain and existing Aegis gateway
ansible.builtin.assert:
that:
- atlas_qbittorrent_public_domain is match('^[a-z0-9]+([.-][a-z0-9]+)+$')
- "'CHANGEME' not in atlas_aegis_ip"
- name: Check whether managed Web settings need an update
community.general.ini_file:
path: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config/qBittorrent.conf"
section: Preferences
option: "{{ item.key }}"
value: "{{ item.value }}"
no_extra_spaces: true
mode: "0600"
loop: "{{ atlas_qbittorrent_web_settings }}"
check_mode: true
register: atlas_qbittorrent_web_probe
no_log: true
diff: false
- name: Stop only qBittorrent before editing its application-managed settings
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
name: atlas-qbittorrent.service
scope: user
state: stopped
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when:
- atlas_qbittorrent_web_probe.changed
- not ansible_check_mode
- name: Preserve credentials and change only the declared Web settings
community.general.ini_file:
path: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config/qBittorrent.conf"
section: Preferences
option: "{{ item.key }}"
value: "{{ item.value }}"
no_extra_spaces: true
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0600"
loop: "{{ atlas_qbittorrent_web_settings }}"
when: atlas_qbittorrent_web_probe.changed
no_log: true
diff: false
- name: Start qBittorrent and restart only after a Quadlet change
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
name: atlas-qbittorrent.service
scope: user
state: "{{ 'restarted' if atlas_qbittorrent_quadlet.changed else 'started' }}"
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when: not ansible_check_mode
- name: Verify the Web UI responds on the LAN address
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ atlas_qbittorrent_web_port }}/"
status_code: 200
register: atlas_qbittorrent_http
retries: 15
delay: 2
until: atlas_qbittorrent_http is succeeded
when: not ansible_check_mode

View File

@@ -10,6 +10,7 @@
properties: properties:
compression: zstd compression: zstd
mountpoint: "{{ atlas_archive_mountpoint }}" mountpoint: "{{ atlas_archive_mountpoint }}"
acltype: posix
- name: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_services }}" - name: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_services }}"
mountpoint: "{{ atlas_services_mountpoint }}" mountpoint: "{{ atlas_services_mountpoint }}"
owner: "{{ atlas_admin_username }}" owner: "{{ atlas_admin_username }}"

View File

@@ -0,0 +1,17 @@
# Managed by Ansible. NPM authenticates callers; this private adapter adds RPC credentials.
[Unit]
Description=Atlas private aria2 RPC gateway
After=atlas-aria2.service
Requires=atlas-aria2.service
PartOf=atlas-aria2.service
[Service]
ExecStart=/usr/bin/python3 {{ atlas_aria2_state_dir }}/rpc-gateway.py --listen {{ ansible_host }} --port {{ atlas_aria2_gateway_port }} --upstream-port {{ atlas_aria2_rpc_port }} --peer {{ atlas_aegis_ip }} --domain {{ atlas_aria2_public_domain }} --secret-file {{ atlas_aria2_state_dir }}/rpc-secret
Restart=on-failure
RestartSec=5
NoNewPrivileges=true
UMask=0077
RestrictAddressFamilies=AF_INET AF_UNIX
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,30 @@
# Managed by Ansible. Never expose this file: it contains the RPC secret.
dir=/downloads
input-file=/config/session
save-session=/config/session
save-session-interval=30
auto-save-interval=30
continue=true
allow-overwrite=false
auto-file-renaming=false
max-concurrent-downloads=1
max-connection-per-server=1
split=1
max-tries=20
retry-wait=10
connect-timeout=30
timeout=60
check-certificate=true
file-allocation=none
umask=007
enable-rpc=true
rpc-listen-all=true
rpc-listen-port=6800
rpc-allow-origin-all=true
rpc-secret={{ atlas_aria2_rpc_secret.content | b64decode | trim }}
rpc-max-request-size=2M
enable-dht=false
enable-dht6=false
enable-peer-exchange=false
bt-enable-lpd=false
console-log-level=warn

View File

@@ -0,0 +1,30 @@
# Managed by Ansible. Bypass upstream init, tracker updates and deletion hooks.
[Unit]
Description=Atlas rootless HTTP downloader
RequiresMountsFor={{ atlas_aria2_state_dir }} {{ atlas_aria2_downloads_dir }}
[Container]
ContainerName=atlas-aria2
Image={{ atlas_aria2_image }}
UserNS=keep-id
User={{ atlas_admin_uid }}
Group={{ atlas_admin_gid }}
Entrypoint=/usr/local/bin/aria2c
Exec=--conf-path=/config/aria2.conf
PublishPort={{ ansible_host }}:{{ atlas_aria2_rpc_port }}:6800
Volume={{ atlas_aria2_state_dir }}:/config:Z
Volume={{ atlas_aria2_downloads_dir }}:/downloads:z
ReadOnly=true
Tmpfs=/tmp:rw,nosuid,nodev
NoNewPrivileges=true
DropCapability=all
StopTimeout=60
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
TimeoutStopSec=90
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,22 @@
# Managed by Ansible. Static frontend only; no host data or RPC secret mounted.
[Unit]
Description=Atlas AriaNg LAN Web UI
[Container]
ContainerName=atlas-ariang
Image={{ atlas_ariang_image }}
UserNS=keep-id
User={{ atlas_admin_uid }}
Group={{ atlas_admin_gid }}
PublishPort={{ ansible_host }}:{{ atlas_ariang_web_port }}:6880
ReadOnly=true
NoNewPrivileges=true
DropCapability=all
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,3 @@
[Unit]
Requires=atlas-nextcloud-backup.service
After=atlas-nextcloud-backup.service

View File

@@ -0,0 +1,19 @@
[Unit]
Description=Recover interrupted Nextcloud backup preparation after boot
Requires=zfs.target user@{{ atlas_admin_uid }}.service
After=zfs.target user@{{ atlas_admin_uid }}.service
{% if atlas_manage_monitoring | bool %}
OnFailure=atlas-monitor-failure@%n.service
{% endif %}
[Service]
Type=oneshot
User=root
UMask=0077
StateDirectory=atlas-nextcloud-backup
StateDirectoryMode=0700
ExecStart=/usr/local/sbin/atlas-nextcloud-backup --recover
TimeoutStartSec=5min
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,24 @@
[Unit]
Description=Prepare a consistent Nextcloud bundle before Atlas backups
Requires=zfs.target user@{{ atlas_admin_uid }}.service
After=zfs.target user@{{ atlas_admin_uid }}.service atlas-nextcloud-backup-recovery.service
{% if atlas_manage_monitoring | bool %}
OnFailure=atlas-monitor-failure@%n.service
{% endif %}
[Service]
Type=oneshot
User=root
UMask=0077
StateDirectory=atlas-nextcloud-backup
StateDirectoryMode=0700
ExecStart=/usr/local/sbin/atlas-nextcloud-backup
ExecStopPost=/usr/local/sbin/atlas-nextcloud-backup --recover
# systemctl set-environment ATLAS_NEXTCLOUD_BACKUP_FORCE=1 makes the next run
# ignore the bundle reuse window; unset the variable afterwards.
PassEnvironment=ATLAS_NEXTCLOUD_BACKUP_FORCE
TimeoutStartSec=3h
TimeoutStopSec=5min
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7

View File

@@ -0,0 +1,164 @@
#!/usr/bin/env bash
set -Eeuo pipefail
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
umask 077
readonly dataset={{ atlas_nextcloud_dataset | quote }}
readonly source_root={{ atlas_nextcloud_root | quote }}
readonly backup_root={{ atlas_nextcloud_backup_root | quote }}
readonly state=/var/lib/atlas-nextcloud-backup
readonly keep={{ atlas_nextcloud_backup_keep | int }}
readonly reuse_max={{ atlas_nextcloud_backup_reuse_max_seconds | int }}
readonly owner={{ atlas_admin_username | quote }}
readonly uid={{ atlas_admin_uid | int }}
user_run() {
runuser -u "$owner" -- env XDG_RUNTIME_DIR="/run/user/$uid" \
DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" "$@"
}
occ() { user_run podman exec --user 33 atlas-nextcloud php occ "$@"; }
exec 8>/run/lock/atlas-nextcloud-backup.lock
flock 8
exec 9>/run/lock/atlas-zfs-snapshot.lock
mkdir -p "$state"
chmod 0700 "$state"
resume() {
[[ -e "$state/paused" ]] || return 0
user_run systemctl --user start atlas-nextcloud.service atlas-onlyoffice.service
local ready=false
for _ in {1..60}; do
if occ maintenance:mode --off >/dev/null 2>&1; then ready=true; break; fi
sleep 2
done
[[ "$ready" == true ]] || { echo 'Nextcloud resume failed; recovery marker retained' >&2; return 1; }
user_run systemctl --user start atlas-nextcloud-cron.timer
# Persist maintenance-off before clearing durable interruption ownership.
sync -f "$source_root/app"
rm "$state/paused"
sync -f "$state"
echo 'Nextcloud/Office resumed and cron timer restored'
}
recover() {
resume || return 1
[[ -e "$state/stamp" ]] || return 0
local stamp snapshot mount source
stamp=$(cat "$state/stamp")
[[ "$stamp" =~ ^[0-9]{8}T[0-9]{6}Z-[0-9]+$ ]] || return 65
snapshot="nc-backup-$stamp"
flock 9
for component in files app; do
mount="$source_root/$component/.zfs/snapshot/$snapshot"
source=$(findmnt -rn -M "$mount" -o SOURCE || true)
if [[ -n "$source" ]]; then
[[ "$source" == "$dataset/$component@$snapshot" ]] || return 65
umount "$mount" || return 1
fi
done
if zfs list -H -t snapshot "$dataset@$snapshot" >/dev/null 2>&1; then
zfs destroy -r "$dataset@$snapshot" || return 1
fi
flock -u 9
# Only this job's private, unpublished staging directory can be removed.
rm -rf -- "$backup_root/.partial-$stamp"
rm "$state/stamp"
}
if [[ "${1:-}" == --recover ]]; then recover; exit; fi
recover
# Fast path: a structurally complete bundle from an earlier verified run is
# reused while younger than the reuse window, without pausing the applications.
# ATLAS_NEXTCLOUD_BACKUP_FORCE=1 ignores the window and prepares one anyway.
if [[ "${ATLAS_NEXTCLOUD_BACKUP_FORCE:-0}" != 1 ]] && [[ "$reuse_max" -gt 0 ]]; then
target="$(readlink -f "$backup_root/latest" 2>/dev/null || true)"
if [[ -n "$target" && "$target" == "$backup_root/versions/"* ]]; then
name="${target##*/}"
if [[ "$name" =~ ^[0-9]{8}T[0-9]{6}Z-[0-9]+$ ]]; then
bundle_utc="${name:0:4}-${name:4:2}-${name:6:2} ${name:9:2}:${name:11:2}:${name:13:2} UTC"
created="$(date -u -d "$bundle_utc" +%s 2>/dev/null || true)"
if [[ -n "$created" ]]; then
now="$(date -u +%s)"
if [[ "$((now - created))" -le "$reuse_max" ]]; then
reusable=true
for component in manifest.txt SHA256SUMS database.dump \
postgres-globals.sql database-toc.txt images.txt; do
[[ -s "$target/$component" ]] || { reusable=false; break; }
done
for component in app files; do
[[ -d "$target/$component" ]] || { reusable=false; break; }
done
if [[ "$reusable" == true ]]; then
echo "Reusing verified Nextcloud bundle $name (age $((now - created))s <= ${reuse_max}s); preparation skipped"
exit 0
fi
fi
fi
fi
fi
fi
[[ "$(zfs get -H -o value mounted "$dataset")" == yes ]]
[[ "$(zfs get -H -o value mountpoint "$dataset")" == "$source_root" ]]
[[ "$(zfs get -H -o value mounted {{ (atlas_zfs_pool ~ '/backup') | quote }})" == yes ]]
[[ "$(zfs get -H -o value mountpoint {{ (atlas_zfs_pool ~ '/backup') | quote }})" == {{ (atlas_mount_root ~ '/backup') | quote }} ]]
for component in app files; do
[[ "$(zfs get -H -o value mounted "$dataset/$component")" == yes ]]
[[ "$(zfs get -H -o value mountpoint "$dataset/$component")" == "$source_root/$component" ]]
done
for unit in atlas-nextcloud.service atlas-onlyoffice.service atlas-nextcloud-cron.timer; do
user_run systemctl --user is-active --quiet "$unit"
done
occ status --output=json | python3 -c 'import json,sys; s=json.load(sys.stdin); assert s["installed"] and not s["maintenance"] and not s["needsDbUpgrade"]'
mkdir -p "$backup_root/versions"
chmod 0700 "$backup_root" "$backup_root/versions"
stamp="$(date -u +%Y%m%dT%H%M%SZ)-$$"
snapshot="nc-backup-$stamp"
stage="$backup_root/.partial-$stamp"
mkdir "$stage"
printf '%s\n' "$stamp" > "$state/stamp"
sync -f "$state"
cleanup() {
local rc=$?
trap - EXIT
if ! recover; then rc=1; fi
exit "$rc"
}
trap cleanup EXIT
trap 'exit 143' HUP INT TERM
# Wait for snapshot serialization before interrupting application availability.
flock 9
touch "$state/paused"
sync -f "$state"
user_run systemctl --user stop atlas-nextcloud-cron.timer atlas-nextcloud-cron.service
occ maintenance:mode --on
user_run systemctl --user stop atlas-onlyoffice.service atlas-nextcloud.service
user_run podman exec atlas-nextcloud-db pg_dumpall -U nextcloud --globals-only > "$stage/postgres-globals.sql"
user_run podman exec atlas-nextcloud-db pg_dump -U nextcloud -d nextcloud --format=custom > "$stage/database.dump"
zfs snapshot -r "$dataset@$snapshot"
flock -u 9
resume
# Copy immutable snapshot views; hashing and transfer never extend the outage.
previous=$(readlink -f "$backup_root/latest" 2>/dev/null || true)
for component in app files; do
args=(-aHAX)
if [[ "$previous" == "$backup_root/versions/"* && -d "$previous/$component" ]]; then
args+=("--link-dest=$previous/$component")
fi
if [[ "$component" == app ]]; then args+=(--exclude=/data); fi
rsync "${args[@]}" "$source_root/$component/.zfs/snapshot/$snapshot/" "$stage/$component/"
done
user_run podman exec -i atlas-nextcloud-db pg_restore --list < "$stage/database.dump" > "$stage/database-toc.txt"
user_run podman inspect --format '{% raw %}{{.ImageName}}{% endraw %}' atlas-nextcloud atlas-nextcloud-db atlas-nextcloud-redis atlas-onlyoffice > "$stage/images.txt"
(cd "$stage"; find app files -type f -exec sha256sum '{}' +; sha256sum database.dump postgres-globals.sql images.txt) > "$stage/SHA256SUMS"
(cd "$stage"; sha256sum --quiet --check SHA256SUMS)
printf 'snapshot=%s@%s\ncreated_utc=%s\n' "$dataset" "$snapshot" "$stamp" > "$stage/manifest.txt"
mv "$stage" "$backup_root/versions/$stamp"
ln -s "versions/$stamp" "$backup_root/.latest-$stamp"
mv -Tf "$backup_root/.latest-$stamp" "$backup_root/latest"
sync -f "$backup_root"
# Prune only timestamped job-owned versions after verified atomic publication.
mapfile -t versions < <(find "$backup_root/versions" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | grep -E '^[0-9]{8}T[0-9]{6}Z-[0-9]+$' | sort -r)
{% raw %}
for ((index=keep; index<${#versions[@]}; index++)); do
{% endraw %}
rm -rf -- "$backup_root/versions/${versions[$index]}"
done
echo "Published verified consistent Nextcloud bundle $stamp; local retention=$keep"

View File

@@ -0,0 +1,12 @@
[Unit]
Description=Discover existing Archive documents and iCloud photos in Nextcloud
Requires=atlas-nextcloud.service
After=atlas-nextcloud.service
[Service]
Type=oneshot
{% for mount in atlas_nextcloud_external_mounts %}
ExecStart=/usr/bin/podman exec --user 33 atlas-nextcloud php occ files:scan "--path={{ mount.user }}/files/{{ mount.name }}" --quiet
{% endfor %}
TimeoutStartSec=90min
NoNewPrivileges=true

View File

@@ -0,0 +1,10 @@
[Unit]
Description=Periodic discovery of Archive changes made outside Nextcloud
[Timer]
OnBootSec=15min
OnUnitInactiveSec=1h
Unit=atlas-nextcloud-external-scan.service
[Install]
WantedBy=timers.target

View File

@@ -11,6 +11,20 @@ $CONFIG = [
'skeletondirectory' => '', 'skeletondirectory' => '',
'maintenance_window_start' => 1, 'maintenance_window_start' => 1,
'default_phone_region' => 'IT', 'default_phone_region' => 'IT',
// Preserve the standard providers and add Apple HEIC/HEIF previews.
'enabledPreviewProviders' => [
'OC\\Preview\\PNG',
'OC\\Preview\\JPEG',
'OC\\Preview\\GIF',
'OC\\Preview\\BMP',
'OC\\Preview\\XBitmap',
'OC\\Preview\\Krita',
'OC\\Preview\\WebP',
'OC\\Preview\\MarkDown',
'OC\\Preview\\TXT',
'OC\\Preview\\OpenDocument',
'OC\\Preview\\HEIC',
],
'twofactor_enforced' => false, 'twofactor_enforced' => false,
'onlyoffice' => [ 'onlyoffice' => [
'DocumentServerUrl' => 'https://{{ atlas_onlyoffice_domain }}/', 'DocumentServerUrl' => 'https://{{ atlas_onlyoffice_domain }}/',

View File

@@ -2,7 +2,7 @@
Description=Atlas Nextcloud Description=Atlas Nextcloud
Requires=atlas-nextcloud-db.service atlas-nextcloud-redis.service Requires=atlas-nextcloud-db.service atlas-nextcloud-redis.service
After=atlas-nextcloud-db.service atlas-nextcloud-redis.service After=atlas-nextcloud-db.service atlas-nextcloud-redis.service
RequiresMountsFor={{ atlas_nextcloud_root }}/app {{ atlas_nextcloud_root }}/files RequiresMountsFor={{ atlas_nextcloud_root }}/app {{ atlas_nextcloud_root }}/files{% for mount in atlas_nextcloud_external_mounts %} {{ mount.source }}{% endfor %}
[Container] [Container]
ContainerName=atlas-nextcloud ContainerName=atlas-nextcloud
@@ -26,6 +26,10 @@ Environment=PHP_UPLOAD_LIMIT=2G
Volume={{ atlas_nextcloud_root }}/app:/var/www/html:Z Volume={{ atlas_nextcloud_root }}/app:/var/www/html:Z
Volume={{ atlas_nextcloud_root }}/files:/var/www/html/data:Z Volume={{ atlas_nextcloud_root }}/files:/var/www/html/data:Z
Volume={{ atlas_nextcloud_app_cache }}:/mnt/atlas-apps:ro,z Volume={{ atlas_nextcloud_app_cache }}:/mnt/atlas-apps:ro,z
{% for mount in atlas_nextcloud_external_mounts %}
# Shared Archive label, not the private :Z label used for internal state.
Volume={{ mount.source }}:{{ mount.target }}:{{ 'ro' if mount.readonly else 'rw' }},z
{% endfor %}
Volume={{ atlas_nextcloud_private_dir }}/postgres-password:/run/secrets/postgres-password:ro,z Volume={{ atlas_nextcloud_private_dir }}/postgres-password:/run/secrets/postgres-password:ro,z
Volume={{ atlas_nextcloud_private_dir }}/admin-password:/run/secrets/admin-password:ro,z Volume={{ atlas_nextcloud_private_dir }}/admin-password:/run/secrets/admin-password:ro,z
Volume={{ atlas_nextcloud_private_dir }}/redis-password:/run/secrets/redis-password:ro,z Volume={{ atlas_nextcloud_private_dir }}/redis-password:/run/secrets/redis-password:ro,z

View File

@@ -0,0 +1,8 @@
# Managed by Ansible; loaded inside the ONLYOFFICE Nginx server block.
# Return-only server rewrite rules run before the vendor welcome redirect.
if ($uri = /) {
return 404;
}
if ($uri ~* "^/([0-9]+\.[0-9]+\.[0-9]+[-.][A-Za-z0-9_-]+/)?(welcome|example)(/|$)") {
return 404;
}

View File

@@ -10,6 +10,8 @@ NetworkAlias=atlas-onlyoffice
PublishPort={{ ansible_host }}:{{ atlas_onlyoffice_http_port }}:80 PublishPort={{ ansible_host }}:{{ atlas_onlyoffice_http_port }}:80
PublishPort=127.0.0.1:{{ atlas_onlyoffice_http_port }}:80 PublishPort=127.0.0.1:{{ atlas_onlyoffice_http_port }}:80
EnvironmentFile={{ atlas_nextcloud_private_dir }}/onlyoffice.env EnvironmentFile={{ atlas_nextcloud_private_dir }}/onlyoffice.env
Environment=EXAMPLE_ENABLED=false
Volume={{ atlas_nextcloud_private_dir }}/onlyoffice-access.conf:/etc/nginx/includes/ds-atlas-access.conf:ro,Z
Volume={{ atlas_nextcloud_root }}/office/data:/var/www/onlyoffice/Data:Z Volume={{ atlas_nextcloud_root }}/office/data:/var/www/onlyoffice/Data:Z
Volume={{ atlas_nextcloud_root }}/office/lib:/var/lib/onlyoffice:Z Volume={{ atlas_nextcloud_root }}/office/lib:/var/lib/onlyoffice:Z
Volume={{ atlas_nextcloud_root }}/office/logs:/var/log/onlyoffice:Z Volume={{ atlas_nextcloud_root }}/office/logs:/var/log/onlyoffice:Z

View File

@@ -0,0 +1,27 @@
[Unit]
Description=Atlas Paperless PostgreSQL
RequiresMountsFor={{ atlas_paperless_root }}/database
[Container]
ContainerName=atlas-paperless-db
Image={{ atlas_paperless_postgres_image }}
Network=atlas-paperless.network
NetworkAlias=atlas-paperless-db
Environment=POSTGRES_DB=paperless
Environment=POSTGRES_USER=paperless
Environment=POSTGRES_PASSWORD_FILE=/run/secrets/postgres-password
Volume={{ atlas_paperless_private_dir }}/postgres-password:/run/secrets/postgres-password:ro,z
Volume={{ atlas_paperless_root }}/database:/var/lib/postgresql/data:Z
PodmanArgs=--memory=1g
HealthCmd=pg_isready -U paperless -d paperless
HealthInterval=30s
HealthStartPeriod=60s
NoNewPrivileges=true
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,20 @@
[Unit]
Description=Atlas Paperless private Gotenberg
[Container]
ContainerName=atlas-paperless-gotenberg
Image={{ atlas_paperless_gotenberg_image }}
Network=atlas-paperless.network
NetworkAlias=atlas-paperless-gotenberg
# Keep external content and JavaScript disabled for email/Office conversion.
Exec=gotenberg --chromium-disable-javascript=true --chromium-allow-list=^file:///tmp/.*
PodmanArgs=--memory=2g
NoNewPrivileges=true
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,27 @@
[Unit]
Description=Atlas private Paperless Ollama
RequiresMountsFor={{ atlas_paperless_root }}/ollama
[Container]
ContainerName=atlas-paperless-ollama
Image={{ atlas_paperless_ollama_image }}
UserNS=keep-id:uid={{ atlas_admin_uid }},gid={{ atlas_admin_gid }}
User={{ atlas_admin_uid }}:{{ atlas_admin_gid }}
Network=atlas-paperless.network
Environment=OLLAMA_HOST=0.0.0.0:11434
Environment=OLLAMA_MODELS=/models
Environment=OLLAMA_NUM_PARALLEL=1
Environment=OLLAMA_MAX_LOADED_MODELS=1
Environment=OLLAMA_KEEP_ALIVE=2m
Environment=OLLAMA_NO_CLOUD=true
Volume={{ atlas_paperless_root }}/ollama:/models:Z
PodmanArgs=--memory=3g
NoNewPrivileges=true
DropCapability=all
[Service]
Restart=on-failure
RestartSec=10
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,18 @@
[Unit]
Description=Atlas Paperless private Apache Tika
[Container]
ContainerName=atlas-paperless-tika
Image={{ atlas_paperless_tika_image }}
Network=atlas-paperless.network
NetworkAlias=atlas-paperless-tika
PodmanArgs=--memory=1g
NoNewPrivileges=true
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,21 @@
[Unit]
Description=Atlas Paperless private Valkey broker
RequiresMountsFor={{ atlas_paperless_root }}/cache
[Container]
ContainerName=atlas-paperless-valkey
Image={{ atlas_paperless_valkey_image }}
Network=atlas-paperless.network
NetworkAlias=atlas-paperless-valkey
Volume={{ atlas_paperless_root }}/cache:/data:Z
Exec=valkey-server --appendonly yes
PodmanArgs=--memory=256m
NoNewPrivileges=true
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,54 @@
[Unit]
Description=Atlas Paperless-ngx
Requires=atlas-paperless-db.service atlas-paperless-valkey.service atlas-paperless-tika.service atlas-paperless-gotenberg.service atlas-paperless-ollama.service
After=atlas-paperless-db.service atlas-paperless-valkey.service atlas-paperless-tika.service atlas-paperless-gotenberg.service atlas-paperless-ollama.service
RequiresMountsFor={{ atlas_paperless_root }}/data {{ atlas_paperless_root }}/media {{ atlas_paperless_root }}/consume
[Container]
ContainerName=atlas-paperless
Image={{ atlas_paperless_image }}
UserNS=keep-id:uid={{ atlas_admin_uid }},gid={{ atlas_admin_gid }}
Network=atlas-paperless.network
PublishPort={{ ansible_host }}:{{ atlas_paperless_http_port }}:8000
Environment=USERMAP_UID={{ atlas_admin_uid }}
Environment=USERMAP_GID={{ atlas_admin_gid }}
Environment=PAPERLESS_REDIS=redis://atlas-paperless-valkey:6379
Environment=PAPERLESS_DBENGINE=postgresql
Environment=PAPERLESS_DBHOST=atlas-paperless-db
Environment=PAPERLESS_DBNAME=paperless
Environment=PAPERLESS_DBUSER=paperless
Environment=PAPERLESS_DBPASS_FILE=/run/secrets/postgres-password
Environment=PAPERLESS_SECRET_KEY_FILE=/run/secrets/secret-key
Environment=PAPERLESS_URL=https://{{ atlas_paperless_domain }}
Environment=PAPERLESS_TIME_ZONE={{ atlas_timezone }}
Environment=PAPERLESS_OCR_LANGUAGE={{ atlas_paperless_ocr_language }}
Environment=PAPERLESS_CONSUMPTION_DIR=/usr/src/paperless/consume
Environment=PAPERLESS_DATA_DIR=/usr/src/paperless/data
Environment=PAPERLESS_MEDIA_ROOT=/usr/src/paperless/media
Environment=PAPERLESS_TIKA_ENABLED=1
Environment=PAPERLESS_TIKA_ENDPOINT=http://atlas-paperless-tika:9998
Environment=PAPERLESS_TIKA_GOTENBERG_ENDPOINT=http://atlas-paperless-gotenberg:3000
Environment=PAPERLESS_AI_ENABLED=true
Environment=PAPERLESS_AI_LLM_BACKEND=ollama
Environment=PAPERLESS_AI_LLM_ENDPOINT=http://atlas-paperless-ollama:11434
Environment=PAPERLESS_AI_LLM_MODEL={{ atlas_paperless_llm_model }}
Environment=PAPERLESS_AI_LLM_EMBEDDING_BACKEND=ollama
Environment=PAPERLESS_AI_LLM_EMBEDDING_MODEL={{ atlas_paperless_embedding_model }}
Environment=PAPERLESS_AI_LLM_CONTEXT_SIZE=2048
Environment=PAPERLESS_AI_LLM_REQUEST_TIMEOUT=300
Volume={{ atlas_paperless_root }}/data:/usr/src/paperless/data:Z
Volume={{ atlas_paperless_root }}/media:/usr/src/paperless/media:Z
Volume={{ atlas_paperless_root }}/consume:/usr/src/paperless/consume:Z
Volume={{ atlas_paperless_private_dir }}/postgres-password:/run/secrets/postgres-password:ro,z
Volume={{ atlas_paperless_private_dir }}/secret-key:/run/secrets/secret-key:ro,z
PodmanArgs=--memory=2g
NoNewPrivileges=true
DropCapability=all
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,5 @@
# Managed by Ansible: private rootless Paperless network.
[Network]
NetworkName=atlas-paperless
Subnet={{ atlas_paperless_network_subnet }}
Gateway={{ atlas_paperless_network_gateway }}

View File

@@ -0,0 +1,17 @@
; Seeded once by Ansible. Subsequent settings are managed through the Web UI.
[BitTorrent]
Session\DefaultSavePath=/downloads
Session\TempPath=/downloads/.incomplete
Session\TempPathEnabled=true
Session\Port=6881
[Meta]
MigrationVersion=9999
[Network]
PortForwardingEnabled=false
[Preferences]
WebUI\Port={{ atlas_qbittorrent_web_port }}
WebUI\LocalHostAuth=true
WebUI\AuthSubnetWhitelistEnabled=false
WebUI\CSRFProtection=true
WebUI\ClickjackingProtection=true
WebUI\HostHeaderValidation=true

View File

@@ -0,0 +1,33 @@
# Managed by Ansible. No VPN, host networking or router port forwarding.
[Unit]
Description=Atlas rootless qBittorrent
RequiresMountsFor={{ atlas_qbittorrent_state_dir }} {{ atlas_qbittorrent_downloads_dir }}
[Container]
ContainerName=atlas-qbittorrent
Image={{ atlas_qbittorrent_image }}
UserNS=keep-id
User={{ atlas_admin_uid }}
Group={{ atlas_admin_gid }}
PublishPort={{ ansible_host }}:{{ atlas_qbittorrent_web_port }}:{{ atlas_qbittorrent_web_port }}
Environment=QBT_LEGAL_NOTICE=confirm
Environment=QBT_WEBUI_PORT={{ atlas_qbittorrent_web_port }}
Environment=XDG_CACHE_HOME=/tmp/cache
Environment=TZ={{ atlas_timezone }}
Environment=UMASK=007
Volume={{ atlas_qbittorrent_state_dir }}:/config:Z
Volume={{ atlas_qbittorrent_downloads_dir }}:/downloads:z
ReadOnly=true
Tmpfs=/tmp:rw,nosuid,nodev
NoNewPrivileges=true
DropCapability=all
StopTimeout=1800
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
TimeoutStopSec=1900
[Install]
WantedBy=default.target

View File

@@ -562,6 +562,10 @@
name: "{{ item.value.npm_package }}" name: "{{ item.value.npm_package }}"
global: true global: true
state: latest state: latest
register: ai_agent_npm_install
retries: "{{ ai_agents_npm_install_retries }}"
delay: "{{ ai_agents_npm_install_retry_delay }}"
until: ai_agent_npm_install is succeeded
loop: "{{ ai_agents | dict2items | selectattr('value.npm_package', 'defined') | list }}" loop: "{{ ai_agents | dict2items | selectattr('value.npm_package', 'defined') | list }}"
when: when:
- item.value.install_enabled | bool - item.value.install_enabled | bool

View File

@@ -0,0 +1,144 @@
#!/usr/bin/env python3
"""Read-only discovery and registry plan; never read stored login credentials."""
import configparser
import io
import json
from pathlib import Path
import re
import sys
def read_ini(path):
result = configparser.RawConfigParser()
result.optionxform = str
if path.exists():
with path.open() as source:
result.read_file(source)
return result
def preferences(path):
if not path.exists():
return {}
result = {}
for key, value in re.findall(
r'^\s*user_pref\("([^"\n]+)",\s*(.*?)\);',
path.read_text(), re.MULTILINE,
):
try:
result[key] = json.loads(value)
except ValueError:
continue
return result
def has_account(path):
# user.js alone is only a bootstrap, not an account used by Thunderbird.
prefs = preferences(path / 'prefs.js')
for account in str(prefs.get('mail.accountmanager.accounts', '')).split(','):
server = prefs.get('mail.account.' + account.strip() + '.server')
prefix = 'mail.server.' + str(server) + '.'
if (prefs.get(prefix + 'type') in ('imap', 'pop3', 'nntp')
and prefs.get(prefix + 'hostname')):
return True
return False
def profile_path(root, registry, section):
value = registry.get(section, 'Path')
return (root / value if registry.get(section, 'IsRelative', fallback='1') == '1'
else Path(value)).resolve()
def render(registry):
output = io.StringIO()
registry.write(output, space_around_delimiters=False)
return output.getvalue()
def plan(home, profile_dir, profile_name):
home = Path(home)
# A legacy directory takes precedence over the XDG registry on this build.
roots = [home / '.thunderbird', home / '.config/thunderbird']
root = next((p for p in roots if p.exists()), roots[1])
registries = {p: read_ini(p / 'profiles.ini') for p in roots}
candidates = []
install_ids = set()
for base, registry in registries.items():
installs = read_ini(base / 'installs.ini')
defaults = {registry.get(s, 'Default', fallback='')
for s in registry.sections() if s.startswith('Install')}
defaults.update(installs.get(s, 'Default', fallback='')
for s in installs.sections())
for section in registry.sections():
if not re.fullmatch(r'Profile\d+', section):
continue
path = profile_path(base, registry, section)
if has_account(path):
candidates.append((registry.get(section, 'Path') not in defaults,
base != root, str(path), path))
# Reuse installation associations, including those in the other root.
install_ids.update(s[7:] for s in registry.sections() if s.startswith('Install'))
install_ids.update(installs.sections())
# Also find unregistered profiles, without following arbitrary subtrees.
if base.exists():
for child in sorted(base.iterdir()):
if child.is_dir() and has_account(child):
candidates.append((True, base != root, str(child.resolve()), child.resolve()))
existing = bool(candidates)
selected = min(candidates)[3] if existing else root / profile_dir
if not existing:
number = 0
while selected.exists():
bootstrap = selected / 'user.js'
if (not (selected / 'prefs.js').exists() and bootstrap.exists()
and bootstrap.read_text().startswith('// Managed by Ansible from profile_desktop_gnome')):
break
number += 1
selected = root / (profile_dir + '-' + str(number))
registry = registries[root]
section = next((s for s in registry.sections()
if re.fullmatch(r'Profile\d+', s)
and profile_path(root, registry, s) == selected), None)
if section is None:
number = 0
while registry.has_section('Profile' + str(number)):
number += 1
section = 'Profile' + str(number)
registry.add_section(section)
registry.set(section, 'Name', profile_name if not existing else selected.name)
registry.set(section, 'IsRelative', '0')
registry.set(section, 'Path', str(selected))
for other in registry.sections():
if re.fullmatch(r'Profile\d+', other):
registry.remove_option(other, 'Default')
registry.set(section, 'Default', '1')
if not registry.has_section('General'):
registry.add_section('General')
registry.set('General', 'StartWithLastProfile', '1')
registry.set('General', 'Version', '2')
value = registry.get(section, 'Path')
installs = read_ini(root / 'installs.ini')
for install in sorted(install_ids):
# Do not redirect a separate installation with another configured account.
defaults = []
for base, source in registries.items():
default = source.get('Install' + install, 'Default', fallback='')
if not default:
default = read_ini(base / 'installs.ini').get(install, 'Default', fallback='')
if default:
defaults.append((base / default).resolve())
if any(p != selected and has_account(p) for p in defaults):
continue
for target, name in ((registry, 'Install' + install), (installs, install)):
if not target.has_section(name):
target.add_section(name)
target.set(name, 'Default', value)
target.set(name, 'Locked', '1')
return dict(root=str(root), profile=str(selected), existing_account=existing,
profiles_ini=render(registry), installs_ini=render(installs))
if __name__ == '__main__':
print(json.dumps(plan(*sys.argv[1:])))

View File

@@ -0,0 +1,56 @@
---
- name: Find the installed Cline Desktop launcher
ansible.builtin.stat:
path: "/usr/share/applications/{{ cline_desktop_launcher }}"
get_checksum: false
register: cline_desktop_launcher_stat
- name: Verify Cline Desktop installed its expected launcher
ansible.builtin.assert:
that: cline_desktop_launcher_stat.stat.isreg | default(false)
fail_msg: "Cline Desktop did not install {{ cline_desktop_launcher }}."
when: not ansible_check_mode
- name: Find the GNOME account for the Cline favorite
ansible.builtin.getent:
database: passwd
key: "{{ username }}"
when: cline_desktop_launcher_stat.stat.isreg | default(false)
- name: Update only the Cline and OpenCode entries in GNOME favorites
become_user: "{{ username }}"
environment:
HOME: "{{ user_home }}"
XDG_RUNTIME_DIR: "/run/user/{{ ansible_facts.getent_passwd[username][1] }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ ansible_facts.getent_passwd[username][1] }}/bus"
when: cline_desktop_launcher_stat.stat.isreg | default(false)
block:
- name: Read the current GNOME favorites for Cline Desktop
ansible.builtin.command:
argv: [gsettings, get, org.gnome.shell, favorite-apps]
register: cline_gnome_favorites_current
changed_when: false
check_mode: false
- name: Pin the Cline Desktop launcher without reordering other favorites
ansible.builtin.command:
argv:
- gsettings
- set
- org.gnome.shell
- favorite-apps
- "{{ cline_gnome_favorites_desired | to_json }}"
vars:
cline_gnome_favorites_existing: "{{ cline_gnome_favorites_current.stdout | regex_replace('^@as ', '') | from_yaml }}"
cline_gnome_favorites_desired: >-
{%- set ns = namespace(apps=[]) -%}
{%- for app in cline_gnome_favorites_existing -%}
{%- set launcher = cline_desktop_launcher
if app in ['ai.opencode.desktop.desktop', 'opencode-desktop.desktop'] else app -%}
{%- if launcher != cline_desktop_launcher or launcher not in ns.apps -%}
{%- set ns.apps = ns.apps + [launcher] -%}
{%- endif -%}
{%- endfor -%}
{{ ns.apps if cline_desktop_launcher in ns.apps else ns.apps + [cline_desktop_launcher] }}
when: cline_gnome_favorites_desired != cline_gnome_favorites_existing
changed_when: true

View File

@@ -41,7 +41,7 @@
owner: "{{ username }}" owner: "{{ username }}"
group: "{{ user_group }}" group: "{{ user_group }}"
mode: "{{ item.mode }}" mode: "{{ item.mode }}"
loop: "{{ desktop_common_dotfiles | default([]) }}" loop: "{{ (desktop_common_dotfiles | default([])) + (desktop_gnome_dotfiles | default([])) }}"
loop_control: loop_control:
label: "{{ item.dest }}" label: "{{ item.dest }}"
@@ -279,3 +279,17 @@
loop_control: loop_control:
label: "{{ item }}" label: "{{ item }}"
when: workstation_firewall_backend | default('firewalld') == 'firewalld' when: workstation_firewall_backend | default('firewalld') == 'firewalld'
- name: Configure Thunderbird for iCloud
tags: [dotfiles, dotfiles:desktop, gnome, thunderbird]
ansible.builtin.import_tasks: thunderbird.yml
when: thunderbird_icloud_enabled | default(false) | bool
- name: Configure native VS Code
tags: [vscode]
ansible.builtin.import_tasks: vscode.yml
- name: Pin Cline Desktop in GNOME
tags: [cline_desktop]
ansible.builtin.import_tasks: cline_desktop.yml
when: cline_desktop_install_enabled | default(false) | bool

View File

@@ -0,0 +1,126 @@
---
- name: Inspect existing Thunderbird profiles without changing them
tags: [thunderbird]
ansible.builtin.command:
argv:
- "{{ ansible_facts.python.executable }}"
- -c
- "{{ lookup('ansible.builtin.file', role_path + '/files/thunderbird_profile.py') }}"
- "{{ user_home }}"
- "{{ thunderbird_profile_dir }}"
- "{{ thunderbird_profile_name }}"
become: true
become_user: "{{ username }}"
register: thunderbird_profile_probe
changed_when: false
check_mode: false
- name: Select an existing account or plan an iCloud bootstrap
tags: [thunderbird]
ansible.builtin.set_fact:
thunderbird_selected: "{{ thunderbird_profile_probe.stdout | from_json }}"
- name: Require the iCloud address only when no configured account exists
tags: [thunderbird]
ansible.builtin.assert:
that:
- vault_icloud_email is defined
- vault_icloud_email | length > 0
- vault_icloud_email != 'REPLACE_ME'
- vault_icloud_email is match('^[^@\\s]+@[^@\\s]+$')
fail_msg: >-
vault_icloud_email must hold the iCloud mail address before a new
Thunderbird profile can be provisioned.
quiet: true
when: not thunderbird_selected.existing_account
- name: Check whether Thunderbird is running
tags: [thunderbird]
ansible.builtin.command:
argv: [pgrep, -u, "{{ username }}", -x, thunderbird]
register: thunderbird_running
changed_when: false
failed_when: thunderbird_running.rc not in [0, 1]
check_mode: false
- name: Require Thunderbird to be closed before selecting its profile
tags: [thunderbird]
ansible.builtin.assert:
that: thunderbird_running.rc == 1
fail_msg: Close Thunderbird before running the thunderbird tag; it is never stopped automatically.
- name: Create the selected Thunderbird registry directory
tags: [thunderbird]
ansible.builtin.file:
path: "{{ thunderbird_selected.root }}"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0700"
- name: Create a new profile only when no configured account exists
tags: [thunderbird]
ansible.builtin.file:
path: "{{ thunderbird_selected.profile }}"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0700"
when: not thunderbird_selected.existing_account
- name: Seed iCloud defaults only in a profile without a configured account
tags: [thunderbird]
ansible.builtin.template:
src: thunderbird/user.js.j2
dest: "{{ thunderbird_selected.profile }}/user.js"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0600"
force: false
no_log: true
when: not thunderbird_selected.existing_account
- name: Discover the Thunderbird installation directory for first-start profile adoption
tags: [thunderbird]
ansible.builtin.stat:
path: "{{ item }}/application.ini"
loop: [/usr/lib64/thunderbird, /usr/lib/thunderbird]
register: thunderbird_installation
when: not thunderbird_selected.existing_account
- name: Seed compatibility information so Thunderbird adopts the new default profile
tags: [thunderbird]
ansible.builtin.copy:
content: |
[Compatibility]
LastPlatformDir={{ item.item }}
LastAppDir={{ item.item }}
dest: "{{ thunderbird_selected.profile }}/compatibility.ini"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0600"
force: false
loop: "{{ thunderbird_installation.results }}"
loop_control:
label: "{{ item.item }}"
when:
- not thunderbird_selected.existing_account
- item.stat.exists | default(false)
- name: Select the profile while preserving other registered profiles
tags: [thunderbird]
ansible.builtin.copy:
content: "{{ item.content }}"
dest: "{{ thunderbird_selected.root }}/{{ item.name }}"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0600"
backup: true
loop:
- name: profiles.ini
content: "{{ thunderbird_selected.profiles_ini }}"
- name: installs.ini
content: "{{ thunderbird_selected.installs_ini }}"
loop_control:
label: "{{ item.name }}"
when: item.content | length > 0

View File

@@ -0,0 +1,70 @@
---
- name: Configure Microsoft VS Code repository
ansible.builtin.yum_repository:
name: code
description: Visual Studio Code
baseurl: https://packages.microsoft.com/yumrepos/vscode
enabled: true
gpgcheck: true
gpgkey: https://packages.microsoft.com/keys/microsoft.asc
- name: Install native VS Code
ansible.builtin.dnf:
name: code
state: present
- name: List installed VS Code extensions
ansible.builtin.command:
argv: [code, --list-extensions]
become: true
become_user: "{{ username }}"
environment:
HOME: "{{ user_home }}"
register: vscode_installed_extensions
changed_when: false
check_mode: false
when:
- vscode_extensions | length > 0
- not ansible_check_mode
- name: Install missing VS Code extensions
ansible.builtin.command:
argv: [code, --install-extension, "{{ item }}"]
become: true
become_user: "{{ username }}"
environment:
HOME: "{{ user_home }}"
loop: "{{ vscode_extensions }}"
when:
- not ansible_check_mode
- item | lower not in (vscode_installed_extensions.stdout_lines | default([]) | map('lower') | list)
changed_when: true
- name: Ensure VS Code user configuration directory exists
ansible.builtin.file:
path: "{{ user_home }}/.config/Code/User"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0755"
when: vscode_settings is not none or vscode_keybindings | length > 0
- name: Deploy explicitly managed VS Code settings
ansible.builtin.copy:
dest: "{{ user_home }}/.config/Code/User/settings.json"
content: "{{ vscode_settings | to_nice_json }}\n"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0644"
backup: true
when: vscode_settings is not none
- name: Deploy managed VS Code keybindings
ansible.builtin.copy:
dest: "{{ user_home }}/.config/Code/User/keybindings.json"
content: "{{ vscode_keybindings | to_nice_json }}\n"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0644"
backup: true
when: vscode_keybindings | length > 0

View File

@@ -0,0 +1,66 @@
// Managed by Ansible from profile_desktop_gnome (tag: thunderbird).
// Thunderbird rewrites prefs.js on exit, so the declared defaults live here
// and are re-applied at every start. Seeded only when no account exists;
// Ansible does not overwrite this file or configure an existing account.
//
// The account password is intentionally absent: iCloud mail requires an
// app-specific password, which Thunderbird prompts for and stores in its own
// credential store on first use.
// Mail account
user_pref("mail.accountmanager.accounts", "account1");
user_pref("mail.accountmanager.defaultaccount", "account1");
user_pref("mail.account.account1.server", "server1");
user_pref("mail.account.account1.identities", "id1");
user_pref("mail.server.server1.type", "imap");
user_pref("mail.server.server1.hostname", "{{ thunderbird_icloud_imap_host }}");
user_pref("mail.server.server1.port", {{ thunderbird_icloud_imap_port }});
user_pref("mail.server.server1.socketType", 3);
user_pref("mail.server.server1.authMethod", 3);
user_pref("mail.server.server1.userName", "{{ thunderbird_icloud_email }}");
user_pref("mail.server.server1.name", "{{ thunderbird_icloud_account_name }}");
user_pref("mail.server.server1.directory-rel", "[ProfD]ImapMail/{{ thunderbird_icloud_imap_host }}");
user_pref("mail.server.server1.directory", "{{ thunderbird_selected.profile }}/ImapMail/{{ thunderbird_icloud_imap_host }}");
user_pref("mail.server.server1.max_cached_connections", 5);
user_pref("mail.server.server1.check_new_mail", true);
user_pref("mail.server.server1.check_time", 10);
user_pref("mail.server.server1.login_at_startup", true);
user_pref("mail.server.server1.empty_trash", false);
user_pref("mail.identity.id1.fullName", "{{ thunderbird_full_name }}");
user_pref("mail.identity.id1.useremail", "{{ thunderbird_icloud_email }}");
user_pref("mail.identity.id1.valid", true);
user_pref("mail.identity.id1.smtpServer", "smtp1");
user_pref("mail.identity.id1.compose_html", true);
user_pref("mail.identity.id1.fcc_folder", "mailbox://{{ thunderbird_icloud_email }}@{{ thunderbird_icloud_imap_host }}/Sent%20Messages");
user_pref("mail.identity.id1.draft_folder", "mailbox://{{ thunderbird_icloud_email }}@{{ thunderbird_icloud_imap_host }}/Drafts");
user_pref("mail.smtpservers", "smtp1");
user_pref("mail.smtpserver.smtp1.hostname", "{{ thunderbird_icloud_smtp_host }}");
user_pref("mail.smtpserver.smtp1.port", {{ thunderbird_icloud_smtp_port }});
user_pref("mail.smtpserver.smtp1.try_ssl", 2);
user_pref("mail.smtpserver.smtp1.authMethod", 3);
user_pref("mail.smtpserver.smtp1.username", "{{ thunderbird_icloud_email }}");
user_pref("mail.smtpserver.smtp1.description", "{{ thunderbird_icloud_account_name }} SMTP");
// Calendar (CalDAV). Calendars are discovered from the registry branch.
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.type", "caldav");
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.name", "{{ thunderbird_icloud_account_name }}");
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.uri", "{{ thunderbird_icloud_caldav_url }}");
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.username", "{{ thunderbird_icloud_email }}");
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.refreshInterval", 30);
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.readOnly", false);
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.disabled", false);
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.color", "#3a87ad");
user_pref("calendar.list.sortOrder", "{{ thunderbird_icloud_calendar_id }}");
// Address book (CardDAV). dirType 102 is nsIAbManager.CARDDAV_DIRECTORY_TYPE.
user_pref("ldap_2.servers.icloud.dirType", 102);
user_pref("ldap_2.servers.icloud.uid", "{{ thunderbird_icloud_addressbook_uid }}");
user_pref("ldap_2.servers.icloud.description", "{{ thunderbird_icloud_account_name }}");
user_pref("ldap_2.servers.icloud.filename", "abook-icloud.sqlite");
user_pref("ldap_2.servers.icloud.isOffline", false);
user_pref("ldap_2.servers.icloud.position", 3);
user_pref("ldap_2.servers.icloud.carddav.url", "{{ thunderbird_icloud_carddav_url }}");
user_pref("ldap_2.servers.icloud.carddav.username", "{{ thunderbird_icloud_email }}");

View File

@@ -42,6 +42,10 @@
global: true global: true
state: latest state: latest
become: true become: true
register: ai_agent_npm_install
retries: "{{ ai_agents_npm_install_retries }}"
delay: "{{ ai_agents_npm_install_retry_delay }}"
until: ai_agent_npm_install is succeeded
loop: "{{ ai_agents | dict2items | selectattr('value.npm_package', 'defined') | list }}" loop: "{{ ai_agents | dict2items | selectattr('value.npm_package', 'defined') | list }}"
when: when:
- item.value.install_enabled | bool - item.value.install_enabled | bool

View File

@@ -0,0 +1,66 @@
ARG MAVEN_VERSION=3.9.16
ARG NODE_VERSION=20.18.3
FROM docker.io/library/maven:${MAVEN_VERSION}-eclipse-temurin-25 AS maven
FROM docker.io/library/node:${NODE_VERSION}-bookworm-slim AS node
# Java 25 runs both the application and the language servers.
FROM mcr.microsoft.com/devcontainers/java:25-bookworm
USER root
COPY --from=maven /usr/share/maven/ /usr/share/maven/
COPY --from=node /usr/local/bin/node /usr/local/bin/node
COPY --from=node /usr/local/lib/node_modules/npm/ /usr/local/lib/node_modules/npm/
RUN ln -s /usr/share/maven/bin/mvn /usr/local/bin/mvn \
&& ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
&& ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \
&& java -version \
&& mvn -v \
&& node --version \
&& npm install --global --no-audit --no-fund @anthropic-ai/claude-code@2.1.312 cline@3.0.74 \
&& npm cache clean --force
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client zoxide \
&& arch="$(dpkg --print-architecture)" \
&& case "$arch" in \
amd64) sha256=ea4f0222950ee750a3d38dd80d03bce4cee07a3f63928fc47548383bcaf23093 ;; \
arm64) sha256=0edc36cf514f1bd84becac3e94ee8ae9f8818c6a1f99f7b2ee67b362afa253d3 ;; \
*) echo "Unsupported architecture for delta: $arch" >&2; exit 1 ;; \
esac \
&& curl -fsSL --retry 3 "https://github.com/dandavison/delta/releases/download/0.19.2/git-delta_0.19.2_${arch}.deb" -o /tmp/git-delta.deb \
&& echo "$sha256 /tmp/git-delta.deb" | sha256sum -c - \
&& apt-get install -y --no-install-recommends /tmp/git-delta.deb \
&& rm -rf /var/lib/apt/lists/* /tmp/git-delta.deb
ARG KUBECTL_VERSION=1.37.1
ARG HELM_VERSION=4.2.2
RUN arch="$(dpkg --print-architecture)" \
&& case "$arch" in \
amd64) kubectl_sha=65691ff77eb6fa44c908b77a1082c9f092c3b9733b5cefabec0d1104890e21a8; helm_sha=9adafecab4d406853bba163a70e9f104f47dbbf65ce24b7653bae7e36150bcb6 ;; \
arm64) kubectl_sha=ff749f4b78d9c4f1ec87307df9b50119ed819e2094aa9810cb9acffc3286c8c7; helm_sha=78803142087a0069fa4b50d3f32a84d3ef25c14d1ee8a40fbccf86a6216d2f36 ;; \
*) echo "Unsupported architecture for kubectl/helm: $arch" >&2; exit 1 ;; \
esac \
&& curl -fsSL --retry 3 "https://dl.k8s.io/release/v${KUBECTL_VERSION}/bin/linux/${arch}/kubectl" -o /tmp/kubectl \
&& echo "$kubectl_sha /tmp/kubectl" | sha256sum -c - \
&& install -m 0755 /tmp/kubectl /usr/local/bin/kubectl \
&& curl -fsSL --retry 3 "https://get.helm.sh/helm-v${HELM_VERSION}-linux-${arch}.tar.gz" -o /tmp/helm.tgz \
&& echo "$helm_sha /tmp/helm.tgz" | sha256sum -c - \
&& tar -xzf /tmp/helm.tgz -C /tmp "linux-${arch}/helm" \
&& install -m 0755 "/tmp/linux-${arch}/helm" /usr/local/bin/helm \
&& rm -rf /tmp/kubectl /tmp/helm.tgz "/tmp/linux-${arch}" \
&& kubectl version --client \
&& helm version --short
ARG GLAB_VERSION=1.114.0
RUN arch="$(dpkg --print-architecture)" \
&& case "$arch" in \
amd64) sha256=6df680f88a2a45700d1dd6a08a44a74838473ef3dcc5cb1ad243f4d1fd704ad0 ;; \
arm64) sha256=c2bcb44cc10d849cccb879e687f3b9e102a3415c3d02f0cecfd9ce1442519350 ;; \
*) echo "Unsupported architecture for glab: $arch" >&2; exit 1 ;; \
esac \
&& curl -fsSL --retry 3 "https://gitlab.com/gitlab-org/cli/-/releases/v${GLAB_VERSION}/downloads/glab_${GLAB_VERSION}_linux_${arch}.deb" -o /tmp/glab.deb \
&& echo "$sha256 /tmp/glab.deb" | sha256sum -c - \
&& apt-get update \
&& apt-get install -y --no-install-recommends /tmp/glab.deb \
&& rm -rf /var/lib/apt/lists/* /tmp/glab.deb \
&& glab --version
COPY --chown=vscode:vscode bashrc /home/vscode/.bashrc
COPY --chown=vscode:vscode bashrc.aliases /home/vscode/.bashrc.aliases
USER vscode
# Keep this file writable so VS Code can register its Git credential helper.
RUN git config --file /home/vscode/.gitconfig include.path /run/ecaas-git/gitconfig

View File

@@ -0,0 +1,49 @@
ARG MAVEN_VERSION=3.9.16
FROM docker.io/library/maven:${MAVEN_VERSION}-eclipse-temurin-11 AS maven
FROM docker.io/library/node:22.23.4-bookworm-slim AS node
# Java 21 runs the language servers only. The final image keeps Java 11 on PATH.
FROM mcr.microsoft.com/devcontainers/java:21-bookworm AS ide
FROM mcr.microsoft.com/devcontainers/java:11-bookworm
USER root
COPY --from=ide /usr/lib/jvm/msopenjdk-current/ /opt/jdk-21/
COPY --from=maven /usr/share/maven/ /usr/share/maven/
COPY --from=node /usr/local/bin/node /usr/local/bin/node
COPY --from=node /usr/local/lib/node_modules/npm/ /usr/local/lib/node_modules/npm/
RUN ln -s /usr/share/maven/bin/mvn /usr/local/bin/mvn \
&& ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
&& ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \
&& java -version \
&& /opt/jdk-21/bin/java -version \
&& mvn -v \
&& npm install --global --no-audit --no-fund @anthropic-ai/claude-code@2.1.312 cline@3.0.74 \
&& npm cache clean --force
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client zoxide \
&& arch="$(dpkg --print-architecture)" \
&& case "$arch" in \
amd64) sha256=ea4f0222950ee750a3d38dd80d03bce4cee07a3f63928fc47548383bcaf23093 ;; \
arm64) sha256=0edc36cf514f1bd84becac3e94ee8ae9f8818c6a1f99f7b2ee67b362afa253d3 ;; \
*) echo "Unsupported architecture for delta: $arch" >&2; exit 1 ;; \
esac \
&& curl -fsSL --retry 3 "https://github.com/dandavison/delta/releases/download/0.19.2/git-delta_0.19.2_${arch}.deb" -o /tmp/git-delta.deb \
&& echo "$sha256 /tmp/git-delta.deb" | sha256sum -c - \
&& apt-get install -y --no-install-recommends /tmp/git-delta.deb \
&& rm -rf /var/lib/apt/lists/* /tmp/git-delta.deb
ARG GLAB_VERSION=1.114.0
RUN arch="$(dpkg --print-architecture)" \
&& case "$arch" in \
amd64) sha256=6df680f88a2a45700d1dd6a08a44a74838473ef3dcc5cb1ad243f4d1fd704ad0 ;; \
arm64) sha256=c2bcb44cc10d849cccb879e687f3b9e102a3415c3d02f0cecfd9ce1442519350 ;; \
*) echo "Unsupported architecture for glab: $arch" >&2; exit 1 ;; \
esac \
&& curl -fsSL --retry 3 "https://gitlab.com/gitlab-org/cli/-/releases/v${GLAB_VERSION}/downloads/glab_${GLAB_VERSION}_linux_${arch}.deb" -o /tmp/glab.deb \
&& echo "$sha256 /tmp/glab.deb" | sha256sum -c - \
&& apt-get update \
&& apt-get install -y --no-install-recommends /tmp/glab.deb \
&& rm -rf /var/lib/apt/lists/* /tmp/glab.deb \
&& glab --version
COPY --chown=vscode:vscode bashrc /home/vscode/.bashrc
COPY --chown=vscode:vscode bashrc.aliases /home/vscode/.bashrc.aliases
USER vscode
# Keep this file writable so VS Code can register its Git credential helper.
RUN git config --file /home/vscode/.gitconfig include.path /run/ecaas-git/gitconfig

View File

@@ -0,0 +1,107 @@
---
- name: Refuse to deploy the cdp workspace outside WSL
ansible.builtin.assert:
that:
- "'wsl2' in (ansible_facts.kernel | default('') | lower)"
- ansible_facts.distribution | default('') == 'Fedora'
fail_msg: Run this deployment from the Fedora WSL 2 distribution on deadalus.
- name: Prepare the cdp workspace and private configuration
vars:
ecaas_agent_state: "{{ user_home }}/.local/state/ecaas-devcontainer"
ecaas_git_available_cas: >-
{{ ecaas_git_ca_probe.results | selectattr('stat.isreg', 'defined') |
selectattr('stat.isreg') | map(attribute='item') | list }}
block:
- name: Prepare the shared Git configuration
ansible.builtin.import_tasks: ecaas_git.yml
- name: Ensure the cdp dev container directory exists
ansible.builtin.file:
path: "{{ workstation_cdp_workspace }}/.devcontainer"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0755"
- name: Ensure the local Maven directory mounted into the container exists
ansible.builtin.file:
path: "{{ user_home }}/.m2"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0755"
- name: Ensure the local Kubernetes directory mounted into the container exists
ansible.builtin.file:
path: "{{ user_home }}/.kube"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0700"
- name: Ensure the persistent Bash history directory mounted into the container exists
ansible.builtin.file:
path: "{{ user_home }}/.local/state/devcontainer-bash-history/cdp"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0700"
- name: Ensure the private ecaas Git state directory exists
ansible.builtin.file:
path: "{{ ecaas_agent_state }}"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0700"
- name: Ensure the local agent configuration directories mounted into the container exist
ansible.builtin.file:
path: "{{ user_home }}/{{ item.path }}"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "{{ item.mode }}"
loop:
- { path: .claude, mode: "0700" }
- { path: .cline, mode: "0700" }
- { path: .agents, mode: "0755" }
- { path: .config/ai, mode: "0755" }
- { path: .config/glab-cli, mode: "0700" }
- name: Deploy the cdp dev container configuration
ansible.builtin.template:
src: cdp-devcontainer.json.j2
dest: "{{ workstation_cdp_workspace }}/.devcontainer/devcontainer.json"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0644"
backup: true
- name: Deploy the cdp dev container build files
ansible.builtin.copy:
src: "{{ item.src }}"
dest: "{{ workstation_cdp_workspace }}/.devcontainer/{{ item.dest }}"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0644"
backup: true
loop:
- src: cdp-devcontainer.Dockerfile
dest: Dockerfile
- src: "{{ playbook_dir }}/../dotfiles/common/.bashrc"
dest: bashrc
loop_control:
label: "{{ item.dest }}"
- name: Deploy the shared Bash aliases without the production tunnel
ansible.builtin.copy:
content: >-
{{ lookup('ansible.builtin.file', playbook_dir ~ '/../dotfiles/common/.bashrc.aliases')
| regex_replace('(?m)^(#[^\n]*Nginx Proxy Manager[^\n]*\n)?alias npm-tunnel=[^\n]*\n?', '') }}
dest: "{{ workstation_cdp_workspace }}/.devcontainer/bashrc.aliases"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0644"
backup: true

View File

@@ -0,0 +1,130 @@
---
- name: Refuse to deploy the ecaas workspace outside WSL
ansible.builtin.assert:
that:
- "'wsl2' in (ansible_facts.kernel | default('') | lower)"
- ansible_facts.distribution | default('') == 'Fedora'
fail_msg: Run this deployment from the Fedora WSL 2 distribution on deadalus.
- name: Prepare the ecaas workspace and private configuration
vars:
ecaas_agent_state: "{{ user_home }}/.local/state/ecaas-devcontainer"
ecaas_git_available_cas: >-
{{ ecaas_git_ca_probe.results | selectattr('stat.isreg', 'defined') |
selectattr('stat.isreg') | map(attribute='item') | list }}
block:
- name: Prepare the ecaas Git configuration
ansible.builtin.import_tasks: ecaas_git.yml
- name: Ensure the ecaas dev container directory exists
ansible.builtin.file:
path: "{{ workstation_ecaas_workspace }}/.devcontainer"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0755"
- name: Ensure the local Maven directory mounted into the container exists
ansible.builtin.file:
path: "{{ user_home }}/.m2"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0755"
- name: Ensure the persistent Bash history directory mounted into the container exists
ansible.builtin.file:
path: "{{ user_home }}/.local/state/devcontainer-bash-history/ecaas"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0700"
- name: Ensure the private ecaas Git state directory exists
ansible.builtin.file:
path: "{{ ecaas_agent_state }}"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0700"
- name: Ensure the local agent configuration directories mounted into the container exist
ansible.builtin.file:
path: "{{ user_home }}/{{ item.path }}"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "{{ item.mode }}"
loop:
- { path: .claude, mode: "0700" }
- { path: .cline, mode: "0700" }
- { path: .agents, mode: "0755" }
- { path: .config/ai, mode: "0755" }
- { path: .config/glab-cli, mode: "0700" }
- name: Read the WSL Claude account state
ansible.builtin.slurp:
src: "{{ user_home }}/.claude.json"
register: ecaas_claude_account_state
failed_when: false
no_log: true
- name: Read the Claude state used when CLAUDE_CONFIG_DIR is set
ansible.builtin.slurp:
src: "{{ user_home }}/.claude/.claude.json"
register: ecaas_claude_dir_state
failed_when: false
no_log: true
- name: Seed missing Claude account and onboarding state for the container
ansible.builtin.copy:
content: >-
{{ (ecaas_claude_account_state.content | b64decode | from_json
| dict2items
| selectattr('key', 'in', ['oauthAccount', 'hasCompletedOnboarding', 'userID'])
| items2dict)
| combine(ecaas_claude_dir_state.content | default('e30=' | b64encode) | b64decode | from_json)
| to_nice_json }}
dest: "{{ user_home }}/.claude/.claude.json"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0600"
when: ecaas_claude_account_state.content is defined
no_log: true
diff: false
- name: Deploy the ecaas dev container configuration
ansible.builtin.template:
src: ecaas-devcontainer.json.j2
dest: "{{ workstation_ecaas_workspace }}/.devcontainer/devcontainer.json"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0644"
backup: true
- name: Deploy the ecaas dev container build files
ansible.builtin.copy:
src: "{{ item.src }}"
dest: "{{ workstation_ecaas_workspace }}/.devcontainer/{{ item.dest }}"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0644"
backup: true
loop:
- src: ecaas-devcontainer.Dockerfile
dest: Dockerfile
- src: "{{ playbook_dir }}/../dotfiles/common/.bashrc"
dest: bashrc
loop_control:
label: "{{ item.dest }}"
- name: Deploy the shared Bash aliases without the production tunnel
ansible.builtin.copy:
content: >-
{{ lookup('ansible.builtin.file', playbook_dir ~ '/../dotfiles/common/.bashrc.aliases')
| regex_replace('(?m)^(#[^\n]*Nginx Proxy Manager[^\n]*\n)?alias npm-tunnel=[^\n]*\n?', '') }}
dest: "{{ workstation_ecaas_workspace }}/.devcontainer/bashrc.aliases"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0644"
backup: true

View File

@@ -0,0 +1,65 @@
---
- name: Locate the Git CA files configured for the workstation
ansible.builtin.stat:
path: "{{ user_home }}/.local/share/certs/{{ item.certificate }}"
follow: true
get_checksum: false
get_mime: false
loop: "{{ workstation_git_https_cas }}"
loop_control:
label: "{{ item.certificate }}"
register: ecaas_git_ca_probe
- name: Require the ecaas Git CA before deploying the dev container
ansible.builtin.assert:
that:
- workstation_ecaas_git_required_ca in (ecaas_git_available_cas | map(attribute='certificate') | list)
fail_msg: "Install the existing workstation CA at {{ user_home }}/.local/share/certs/{{ workstation_ecaas_git_required_ca }} first."
- name: Verify the available Git CA files are public PEM certificates
ansible.builtin.shell: |
if grep -q -- 'PRIVATE KEY-----' "$ECAAS_GIT_CA"; then
exit 1
fi
openssl x509 -in "$ECAAS_GIT_CA" -noout
environment:
ECAAS_GIT_CA: "{{ user_home }}/.local/share/certs/{{ item.item.certificate }}"
become_user: "{{ username }}"
check_mode: false
changed_when: false
when: item.stat.isreg | default(false)
loop: "{{ ecaas_git_ca_probe.results }}"
loop_control:
label: "{{ item.item.certificate }}"
- name: Ensure the private ecaas Git configuration directory exists
ansible.builtin.file:
path: "{{ ecaas_agent_state }}/git"
state: directory
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0700"
- name: Render the workstation Git configuration for the ecaas container
ansible.builtin.template:
src: "{{ playbook_dir }}/templates/workstation/.gitconfig.j2"
dest: "{{ ecaas_agent_state }}/git/gitconfig"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0600"
vars:
workstation_git_in_devcontainer: true
workstation_git_container_cas: "{{ ecaas_git_available_cas }}"
no_log: true
diff: false
- name: Deploy the workstation Git ignore and delta theme files
ansible.builtin.copy:
src: "{{ playbook_dir }}/../dotfiles/workstation/{{ item }}"
dest: "{{ ecaas_agent_state }}/git/{{ item }}"
owner: "{{ username }}"
group: "{{ user_group }}"
mode: "0644"
loop:
- .gitignore_global
- .themes.gitignore

View File

@@ -1,4 +1,14 @@
--- ---
- name: Deploy the ecaas Java 11 dev container
ansible.builtin.import_tasks: ecaas_devcontainer.yml
when: workstation_ecaas_workspace is defined
tags: [ecaas_devcontainer]
- name: Deploy the cdp Java 25 dev container
ansible.builtin.import_tasks: cdp_devcontainer.yml
when: workstation_cdp_workspace is defined
tags: [cdp_devcontainer]
- name: Ensure Windows Emacs authoring directories exist - name: Ensure Windows Emacs authoring directories exist
tags: [dotfiles, dotfiles:workstation, emacs, wsl] tags: [dotfiles, dotfiles:workstation, emacs, wsl]
ansible.builtin.file: ansible.builtin.file:
@@ -55,51 +65,6 @@
loop_control: loop_control:
label: "{{ item.dest }}" label: "{{ item.dest }}"
- name: Check whether the pinned Java version is installed with Mise
tags: [packages, mise, java, wsl]
ansible.builtin.command:
cmd: "mise where java@{{ workstation_mise_java_version }}"
become_user: "{{ username }}"
environment:
HOME: "{{ user_home }}"
register: workstation_mise_java_where
changed_when: false
failed_when: false
- name: Check whether the pinned Java 25 version is installed with Mise
tags: [packages, mise, java, wsl]
ansible.builtin.command:
cmd: "mise where java@{{ workstation_mise_java_25_version }}"
become_user: "{{ username }}"
environment:
HOME: "{{ user_home }}"
register: workstation_mise_java_25_where
changed_when: false
failed_when: false
- name: Check whether the pinned Maven version is installed with Mise
tags: [packages, mise, maven, wsl]
ansible.builtin.command:
cmd: "mise where maven@{{ workstation_mise_maven_version }}"
become_user: "{{ username }}"
environment:
HOME: "{{ user_home }}"
register: workstation_mise_maven_where
changed_when: false
failed_when: false
- name: Install the pinned Mise tools
tags: [packages, mise, java, maven, wsl]
ansible.builtin.command:
cmd: mise install
become_user: "{{ username }}"
environment:
HOME: "{{ user_home }}"
when: >-
workstation_mise_java_where.rc != 0 or
workstation_mise_java_25_where.rc != 0 or
workstation_mise_maven_where.rc != 0
- name: Ensure WSL boot configuration file exists - name: Ensure WSL boot configuration file exists
tags: [packages, services] tags: [packages, services]
ansible.builtin.file: ansible.builtin.file:

View File

@@ -0,0 +1,64 @@
{
"name": "cdp — Java 25 / Node 20",
"build": {
"dockerfile": "Dockerfile",
"args": {
"MAVEN_VERSION": {{ workstation_maven_version | to_json }},
"NODE_VERSION": {{ workstation_cdp_node_version | to_json }}
}
},
"remoteUser": "vscode",
"updateRemoteUserUID": true,
"containerEnv": {
"CLAUDE_CONFIG_DIR": "/home/vscode/.claude",
"HISTFILE": "/home/vscode/.bash_history.d/history"
},
"remoteEnv": {
"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}"
},
"features": {
"ghcr.io/devcontainers/features/docker-outside-of-docker:1": {
"moby": false
}
},
"mounts": [
{{ ('type=bind,source=' ~ ecaas_agent_state ~ '/git,target=/run/ecaas-git,readonly') | to_json }},
{% for ca in ecaas_git_available_cas %}
{{ ('type=bind,source=' ~ user_home ~ '/.local/share/certs/' ~ ca.certificate ~ ',target=/run/ecaas-git-ca/' ~ ca.certificate ~ ',readonly') | to_json }},
{% endfor %}
{{ ('type=bind,source=' ~ user_home ~ '/.config/ai,target=/home/vscode/.config/ai,readonly') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.local/state/devcontainer-bash-history/cdp,target=/home/vscode/.bash_history.d') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.claude,target=/home/vscode/.claude') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.cline,target=/home/vscode/.cline') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.agents,target=/home/vscode/.agents,readonly') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.m2,target=/home/vscode/.m2') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.config/glab-cli,target=/home/vscode/.config/glab-cli') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.kube,target=/home/vscode/.kube') | to_json }}
],
"forwardPorts": [4200, 4201, 4202, 4210, 8083, 8084],
"customizations": {
"vscode": {
"extensions": [
"vscjava.vscode-java-pack",
"vmware.vscode-boot-dev-pack",
"redhat.vscode-xml",
"redhat.vscode-yaml",
"ms-kubernetes-tools.vscode-kubernetes-tools",
"angular.ng-template",
"dbaeumer.vscode-eslint",
"saoudrizwan.claude-dev",
"emmanuelbeziat.vscode-great-icons"
],
"settings": {
"workbench.iconTheme": "vscode-great-icons",
"java.configuration.runtimes": [
{
"name": "JavaSE-25",
"path": "/usr/lib/jvm/msopenjdk-current",
"default": true
}
]
}
}
}
}

View File

@@ -0,0 +1,61 @@
{
"name": "ecaas — Java 11",
"build": {
"dockerfile": "Dockerfile",
"args": {
"MAVEN_VERSION": {{ workstation_maven_version | to_json }}
}
},
"remoteUser": "vscode",
"updateRemoteUserUID": true,
"containerEnv": {
"CLAUDE_CONFIG_DIR": "/home/vscode/.claude",
"HISTFILE": "/home/vscode/.bash_history.d/history"
},
"remoteEnv": {
"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}"
},
"features": {
"ghcr.io/devcontainers/features/docker-outside-of-docker:1": {
"moby": false
}
},
"mounts": [
{{ ('type=bind,source=' ~ ecaas_agent_state ~ '/git,target=/run/ecaas-git,readonly') | to_json }},
{% for ca in ecaas_git_available_cas %}
{{ ('type=bind,source=' ~ user_home ~ '/.local/share/certs/' ~ ca.certificate ~ ',target=/run/ecaas-git-ca/' ~ ca.certificate ~ ',readonly') | to_json }},
{% endfor %}
{{ ('type=bind,source=' ~ user_home ~ '/.config/ai,target=/home/vscode/.config/ai,readonly') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.local/state/devcontainer-bash-history/ecaas,target=/home/vscode/.bash_history.d') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.claude,target=/home/vscode/.claude') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.cline,target=/home/vscode/.cline') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.agents,target=/home/vscode/.agents,readonly') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.m2,target=/home/vscode/.m2') | to_json }},
{{ ('type=bind,source=' ~ user_home ~ '/.config/glab-cli,target=/home/vscode/.config/glab-cli') | to_json }}
],
"forwardPorts": [8080],
"customizations": {
"vscode": {
"extensions": [
"vscjava.vscode-java-pack",
"vmware.vscode-boot-dev-pack",
"redhat.vscode-xml",
"redhat.vscode-yaml",
"saoudrizwan.claude-dev",
"emmanuelbeziat.vscode-great-icons"
],
"settings": {
"workbench.iconTheme": "vscode-great-icons",
"java.jdt.ls.java.home": "/opt/jdk-21",
"spring-boot.ls.java.home": "/opt/jdk-21",
"java.configuration.runtimes": [
{
"name": "JavaSE-11",
"path": "/usr/lib/jvm/msopenjdk-current",
"default": true
}
]
}
}
}
}

View File

@@ -33,6 +33,19 @@
loop_control: loop_control:
label: "{{ item.key }}" label: "{{ item.key }}"
- name: Reject conflicting AI desktop-app lifecycle flags
tags: [always, ai_desktop_apps]
ansible.builtin.assert:
that:
- not (item.value.install_enabled | default(false)
and item.value.uninstall_enabled | default(false) | bool)
fail_msg: >-
{{ item.key }} has both install_enabled and uninstall_enabled set to true.
Choose either installation or removal before running the playbook.
loop: "{{ ai_desktop_apps | default({}) | dict2items }}"
loop_control:
label: "{{ item.key }}"
roles: roles:
- role: dotfiles_common - role: dotfiles_common
when: when:
@@ -122,6 +135,9 @@
roles: roles:
- profile_desktop_gnome - profile_desktop_gnome
- role: desktop_ai_media
when: desktop_ai_media_enabled | default(false) | bool
tags: [ai_media]
- name: Configure Fedora workstation development layer - name: Configure Fedora workstation development layer
hosts: workstation_dev_fedora hosts: workstation_dev_fedora
@@ -136,3 +152,12 @@
roles: roles:
- profile_workstation_dev_wsl - profile_workstation_dev_wsl
- name: Deploy project devcontainer generator
hosts: platform_fedora
become: true
tags: [devcontainer_generator]
roles:
- role: devcontainer_generator
when: "'graphical_desktop' in group_names or 'workstation_dev_fedora' in group_names"

View File

@@ -1,8 +1,10 @@
{% set in_container = workstation_git_in_devcontainer | default(false) %}
{% set git_support_dir = '/run/ecaas-git' if in_container else '~' %}
[init] [init]
defaultBranch = main defaultBranch = main
[core] [core]
excludesfile = ~/.gitignore_global excludesfile = {{ git_support_dir }}/.gitignore_global
pager = delta pager = delta
[user] [user]
@@ -24,11 +26,21 @@
[merge] [merge]
conflictstyle = diff3 conflictstyle = diff3
tool = bobide tool = {{ 'vscode' if in_container else 'bobide' }}
[mergetool] [mergetool]
prompt = false prompt = false
{% if in_container %}
[mergetool "vscode"]
cmd = code --wait --merge \"$REMOTE\" \"$LOCAL\" \"$BASE\" \"$MERGED\"
[diff]
tool = vscode
[difftool "vscode"]
cmd = code --wait --diff \"$LOCAL\" \"$REMOTE\"
{% else %}
[mergetool "bobide"] [mergetool "bobide"]
cmd = bobide --reuse-window --wait $MERGED cmd = bobide --reuse-window --wait $MERGED
@@ -37,6 +49,7 @@
[difftool "bobide"] [difftool "bobide"]
cmd = bobide --reuse-window --wait --diff $LOCAL $REMOTE cmd = bobide --reuse-window --wait --diff $LOCAL $REMOTE
{% endif %}
[color] [color]
ui = always ui = always
@@ -79,7 +92,7 @@
gcunreachablenow = gc --prune=now gcunreachablenow = gc --prune=now
[include] [include]
path = ~/.themes.gitignore path = {{ git_support_dir }}/.themes.gitignore
[delta] [delta]
features = catppuccin-mocha navigate features = catppuccin-mocha navigate
@@ -88,14 +101,16 @@
tabs = 4 tabs = 4
side-by-side = true side-by-side = true
[http "https://gitlab.ecaas.datacenter.comune.roma"] {% for ca in workstation_git_container_cas | default(workstation_git_https_cas) %}
[http "{{ ca.url }}"]
{% if not in_container %}
sslBackend = openssl sslBackend = openssl
sslCAInfo = ~/.local/share/certs/ecaas.datacenter.comune.roma.crt {% endif %}
sslCAInfo = {{ '/run/ecaas-git-ca' if in_container else '~/.local/share/certs' }}/{{ ca.certificate }}
[http "https://gitlab.datacenter.comune.roma"]
sslBackend = openssl
sslCAInfo = ~/.local/share/certs/datacenter.comune.roma.crt
{% endfor %}
{% if not in_container %}
[credential] [credential]
helper = store helper = store
{% endif %}

View File

@@ -0,0 +1,11 @@
RUN apt-get update \
&& arch="$(dpkg --print-architecture)" \
&& case "$arch" in \
amd64) sha256=ea4f0222950ee750a3d38dd80d03bce4cee07a3f63928fc47548383bcaf23093 ;; \
arm64) sha256=0edc36cf514f1bd84becac3e94ee8ae9f8818c6a1f99f7b2ee67b362afa253d3 ;; \
*) echo "Unsupported architecture for delta: $arch" >&2; exit 1 ;; \
esac \
&& curl -fsSL --retry 3 "https://github.com/dandavison/delta/releases/download/0.19.2/git-delta_0.19.2_${arch}.deb" -o /tmp/git-delta.deb \
&& echo "$sha256 /tmp/git-delta.deb" | sha256sum -c - \
&& apt-get install -y --no-install-recommends /tmp/git-delta.deb \
&& rm -rf /var/lib/apt/lists/* /tmp/git-delta.deb

Some files were not shown because too many files have changed in this diff Show More